问:
c# .net: Extend existing class with method that should be overriden when initialized
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

```<code>String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}
</code>```

How is this solved in C#?

答:
If you have many different calculations logic, consider passing the transformation function to the class. Wrap the value which you will work with by a class and also store an appropriate tranformation in the same class:

```<code>public class Foo
{
    public string Value;
    private Func<string, string> doStringCalc;

    public Foo(string value, Func<string, string> doStringCalc)
    {
        this.Value = value;
        this.doStringCalc = doStringCalc;
    }

    public void ExecuteTransform()
    {
        this.Value = this.doStringCalc(this.Value);
    }
}
</code>```

Then add different transforms as follows:

```<code>var foo1 = new Foo("A", (initialValue) => initialValue + initialValue);
var foo2 = new Foo("B", (initialValue) => initialValue + "bar");
var foo3 = new Foo("C", (initialValue) => " ");

foo1.ExecuteTransform();
foo2.ExecuteTransform();
foo3.ExecuteTransform();

Debug.WriteLine(foo1.Value); // prints "AA"
Debug.WriteLine(foo2.Value); // prints "Bbar"
Debug.WriteLine(foo3.Value); // prints " "
</code>```

Body:
Is something like that possible?

Let's say I have the String Class. And I want to add a Method DoStringCalc(). Now I want one Class which holds all these special strings and calls DoStringCalc() on all of them. But every String can have a different logic in DoStringCalc() and there can be thousands of them.

Most logical for me (coming from java) would be to override the Method DoStringCalc() when initializing a new String. e.g:

String hello = new String() {
    public override DoStringCalc() {
        //do something here
    }
}

How is this solved in C#?

Body:
If you have many different calculations logic, consider passing the transformation function to the class. Wrap the value which you will work with by a class and also store an appropriate tranformation in the same class:

public class Foo
{
    public string Value;
    private Func<string, string> doStringCalc;

    public Foo(string value, Func<string, string> doStringCalc)
    {
        this.Value = value;
        this.doStringCalc = doStringCalc;
    }

    public void ExecuteTransform()
    {
        this.Value = this.doStringCalc(this.Value);
    }
}

Then add different transforms as follows:

var foo1 = new Foo("A", (initialValue) => initialValue + initialValue);
var foo2 = new Foo("B", (initialValue) => initialValue + "bar");
var foo3 = new Foo("C", (initialValue) => " ");

foo1.ExecuteTransform();
foo2.ExecuteTransform();
foo3.ExecuteTransform();

Debug.WriteLine(foo1.Value); // prints "AA"
Debug.WriteLine(foo2.Value); // prints "Bbar"
Debug.WriteLine(foo3.Value); // prints " "


来源: stackexchange

问:
Text value in custom Ribbon
I created a custom ribbon using VBA (not CUSTOM UI EDITOR), I need to have a simple, static text showing value of cell A1, but I cannot find the XML code for that. this is what I have:

```<code>Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

'ribbonXML = ribbonXML + "<mso:ribbon startFromScratch='true' />" & vbNewLine

ribbonXML = "<customUI      xmlns='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "   <ribbon startFromScratch = 'true'>" & vbNewLine
ribbonXML = ribbonXML + "    <qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <tabs>" & vbNewLine

ribbonXML = ribbonXML + "      <tab id='Menu' label='Menu' insertBeforeQ='mso:TabFormat'>" & vbNewLine
'grupo geral
ribbonXML = ribbonXML + "        <group id='geral' label='Geral' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='capa' label='Capa' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='RmsNavigationBarHome'      onAction='Capa1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='resumo' label='Resumo' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='ChartChangeType'      onAction='resumo1'/>" & vbNewLine
ribbonXML = ribbonXML + "        </group>" & vbNewLine
'grupo performance

ribbonXML = ribbonXML + "        <group id='performance' label='Performance' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='prom' label='Prom' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='CopyToPersonalContacts'      onAction='prom1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='super' label='Super' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='WorkgroupAdmin'      onAction='super1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='ranking' label='Ranking' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='Numbering'      onAction='ranking1'/>" & vbNewLine

ribbonXML = ribbonXML + "        </group>" & vbNewLine

'Cliente
ribbonXML = ribbonXML + "        <group id='cliente' label='Cliente' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='Responsible' label='Responsible' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='OrganizationChartInsert'      onAction='responsavel1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='des' label='Des' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='GroupJunkEmail'      onAction='des1'/>" & vbNewLine
ribbonXML = ribbonXML + "        </group>" & vbNewLine

'relatorios novo
ribbonXML = ribbonXML + "        <group id='relatorios1' label='Relatorios' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='an' label='An' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='TrustCenter'      onAction='historico1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='causas' label='Causas' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='GroupContactOptions'      onAction='causas1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='reenvios' label='Reenvios' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='ProposeNewTime'      onAction='reenvios1'/>" & vbNewLine

ribbonXML = ribbonXML + "        </group>" & vbNewLine

'reenvios
'ribbonXML = ribbonXML + "        <group id='reenvios' label='Reenvios' autoScale='true'>" & vbNewLine
'ribbonXML = ribbonXML + "          <button id='reenvios' label='Reenvios' " & vbNewLine
'ribbonXML = ribbonXML + "imageMso='AppointmentColor8'      onAction='reenvios1'/>" & vbNewLine
'
'ribbonXML = ribbonXML + "        </group>" & vbNewLine

ribbonXML = ribbonXML + "      </tab>" & vbNewLine
'ribbonXML = ribbonXML + "    <tab mso:tab label ='Inserir' visible='false'>"
ribbonXML = ribbonXML + "    </tabs>" & vbNewLine

ribbonXML = ribbonXML + "  </ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub
</code>```

All buttons work fine, I have found many codes showing how to add an editable box, but none showing a simple static box showing value from a cell.

答:
You need an editBox-control or labelControl with callbacks to VBA functions, like you have for the onAction-events in your example.

I couldn't get your sample code to work though, so this is a general example. If you want a labelControl, the same getText-sub will work, but the XML-code is different.

XML:

```<code><editBox id="txt1" getText="GetText" getEnabled="GetEnabled' />
<labelControl id="lbl1" getLabel="GetText" />
</code>```

VBA:

```<code>'***** Callback for txt1 getText
Sub GetText(control As IRibbonControl, ByRef returnedVal)
    '***** Return the value in cell A1 in sheet #1 in the workbook that holds the code
    returnedVal = ThisWorkbook.Sheets(1).Cells(1, 1).Value
End Sub

'***** Callback for txt1 getEnabled
Sub GetEnabled(control As IRibbonControl, ByRef returnedVal)
    '***** Return wheter you want the editBox to be enabled or not
    returnedVal = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Text value in custom Ribbon

Body:
I created a custom ribbon using VBA (not CUSTOM UI EDITOR), I need to have a simple, static text showing value of cell A1, but I cannot find the XML code for that. this is what I have:

Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

'ribbonXML = ribbonXML + "<mso:ribbon startFromScratch='true' />" & vbNewLine

ribbonXML = "<customUI      xmlns='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "   <ribbon startFromScratch = 'true'>" & vbNewLine
ribbonXML = ribbonXML + "    <qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <tabs>" & vbNewLine

ribbonXML = ribbonXML + "      <tab id='Menu' label='Menu' insertBeforeQ='mso:TabFormat'>" & vbNewLine
'grupo geral
ribbonXML = ribbonXML + "        <group id='geral' label='Geral' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='capa' label='Capa' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='RmsNavigationBarHome'      onAction='Capa1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='resumo' label='Resumo' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='ChartChangeType'      onAction='resumo1'/>" & vbNewLine
ribbonXML = ribbonXML + "        </group>" & vbNewLine
'grupo performance

ribbonXML = ribbonXML + "        <group id='performance' label='Performance' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='prom' label='Prom' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='CopyToPersonalContacts'      onAction='prom1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='super' label='Super' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='WorkgroupAdmin'      onAction='super1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='ranking' label='Ranking' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='Numbering'      onAction='ranking1'/>" & vbNewLine

ribbonXML = ribbonXML + "        </group>" & vbNewLine

'Cliente
ribbonXML = ribbonXML + "        <group id='cliente' label='Cliente' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='Responsible' label='Responsible' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='OrganizationChartInsert'      onAction='responsavel1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='des' label='Des' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='GroupJunkEmail'      onAction='des1'/>" & vbNewLine
ribbonXML = ribbonXML + "        </group>" & vbNewLine

'relatorios novo
ribbonXML = ribbonXML + "        <group id='relatorios1' label='Relatorios' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <button id='an' label='An' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='TrustCenter'      onAction='historico1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='causas' label='Causas' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='GroupContactOptions'      onAction='causas1'/>" & vbNewLine

ribbonXML = ribbonXML + "          <button id='reenvios' label='Reenvios' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='ProposeNewTime'      onAction='reenvios1'/>" & vbNewLine

ribbonXML = ribbonXML + "        </group>" & vbNewLine

'reenvios
'ribbonXML = ribbonXML + "        <group id='reenvios' label='Reenvios' autoScale='true'>" & vbNewLine
'ribbonXML = ribbonXML + "          <button id='reenvios' label='Reenvios' " & vbNewLine
'ribbonXML = ribbonXML + "imageMso='AppointmentColor8'      onAction='reenvios1'/>" & vbNewLine
'
'ribbonXML = ribbonXML + "        </group>" & vbNewLine

ribbonXML = ribbonXML + "      </tab>" & vbNewLine
'ribbonXML = ribbonXML + "    <tab mso:tab label ='Inserir' visible='false'>"
ribbonXML = ribbonXML + "    </tabs>" & vbNewLine

ribbonXML = ribbonXML + "  </ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

All buttons work fine, I have found many codes showing how to add an editable box, but none showing a simple static box showing value from a cell.

Body:
You need an editBox-control or labelControl with callbacks to VBA functions, like you have for the onAction-events in your example.

I couldn't get your sample code to work though, so this is a general example. If you want a labelControl, the same getText-sub will work, but the XML-code is different.

XML:

<editBox id="txt1" getText="GetText" getEnabled="GetEnabled' />
<labelControl id="lbl1" getLabel="GetText" />

VBA:

'***** Callback for txt1 getText
Sub GetText(control As IRibbonControl, ByRef returnedVal)
    '***** Return the value in cell A1 in sheet #1 in the workbook that holds the code
    returnedVal = ThisWorkbook.Sheets(1).Cells(1, 1).Value
End Sub

'***** Callback for txt1 getEnabled
Sub GetEnabled(control As IRibbonControl, ByRef returnedVal)
    '***** Return wheter you want the editBox to be enabled or not
    returnedVal = True
End Sub


问:
Laravel 5- Foreach loop saves just last record?
I want to save my array data but when I tried with foreach loop, it saves just last records.

Here is form blade (without unneccesary html code) ;

```<code>@foreach($categories as $key=>$category)

  <input type="hidden"  name="menusettings[{{$key}}][menu_name]" value="{{$category->category_name}}">
  <input type="hidden"  name="menusettings[{{$key}}][menu_slug]" value="category/{{$category->category_slug}}" >
  <input type="checkbox" checked name="menusettings[{{$key}}][menu_status]">
  <input type="number" value="$i" name="menusettings[{{$key}}][menu_order]" >

@endforeach
</code>```

And Controller;
public function postUpdateMenu(Request $requests){

```<code>        $menu = new Menu;

                $request = $requests->get('menusettings');

                foreach ($request as $reques) {

                    $menu_status = isset($reques['menu_status']) ? 1 : 0;

                    $menu->menu_name = $reques['menu_name'];
                    $menu->menu_slug = $reques['menu_slug'];
                    $menu->menu_status = $menu_status;
                    $menu->menu_order = $reques['menu_order'];

                    $menu->save();
                }

    return back();

}
</code>```

Any advice ?

答:
First of all. The code you are writing is not recommended.

Still if you want to go your way:
Try by replacing your code with the following:

```<code>            $request = $requests->get('menusettings');

            foreach ($request as $reques) {
                // every time the loop executes a new instance needs to be assigned.
                $menu = new Menu;
                $menu_status = isset($reques['menu_status']) ? 1 : 0;

                $menu->menu_name = $reques['menu_name'];
                $menu->menu_slug = $reques['menu_slug'];
                $menu->menu_status = $menu_status;
                $menu->menu_order = $reques['menu_order'];

                $menu->save();
            }

            return back();
</code>```

The method shown above is not at all recommended as every time the loop executes a connection is made to the database.
Now lets consider the other option(Recommended as this is better.)
You will also need to declare the following array in your Menu model

```<code>protected $fillable = [ 'menu_name','menu_slug', 'menu_status','menu_order','created_at' , 'updated_at'];
</code>```

Controller Code:

```<code>        $request = $requests->get('menusettings');
        $now = date('Y-m-d H:i:s'); //alternatively you may also use Carbon::now
        $menu = [];

        foreach ($request as $reques) {
            $menu_status = isset($reques['menu_status']) ? 1 : 0;

            $menu[] = [ 'menu_name' => $reques['menu_name'] , 'menu_slug' => $reques['menu_slug'] , 'menu_status' => $menu_status , 'menu_order' => $reques['menu_order'] , 'created_at' => $now , 'updated_at' => $now];
        }
        Menu::insert($menu);
        return back();
</code>```

Body:
I want to save my array data but when I tried with foreach loop, it saves just last records.

Here is form blade (without unneccesary html code) ;

@foreach($categories as $key=>$category)

  <input type="hidden"  name="menusettings[{{$key}}][menu_name]" value="{{$category->category_name}}">
  <input type="hidden"  name="menusettings[{{$key}}][menu_slug]" value="category/{{$category->category_slug}}" >
  <input type="checkbox" checked name="menusettings[{{$key}}][menu_status]">
  <input type="number" value="$i" name="menusettings[{{$key}}][menu_order]" >

@endforeach

And Controller;
public function postUpdateMenu(Request $requests){

        $menu = new Menu;

                $request = $requests->get('menusettings');

                foreach ($request as $reques) {

                    $menu_status = isset($reques['menu_status']) ? 1 : 0;

                    $menu->menu_name = $reques['menu_name'];
                    $menu->menu_slug = $reques['menu_slug'];
                    $menu->menu_status = $menu_status;
                    $menu->menu_order = $reques['menu_order'];

                    $menu->save();
                }

    return back();

}

Any advice ?

Body:
First of all. The code you are writing is not recommended.

Still if you want to go your way:
Try by replacing your code with the following:

            $request = $requests->get('menusettings');

            foreach ($request as $reques) {
                // every time the loop executes a new instance needs to be assigned.
                $menu = new Menu;
                $menu_status = isset($reques['menu_status']) ? 1 : 0;

                $menu->menu_name = $reques['menu_name'];
                $menu->menu_slug = $reques['menu_slug'];
                $menu->menu_status = $menu_status;
                $menu->menu_order = $reques['menu_order'];

                $menu->save();
            }

            return back();

The method shown above is not at all recommended as every time the loop executes a connection is made to the database.
Now lets consider the other option(Recommended as this is better.)
You will also need to declare the following array in your Menu model

protected $fillable = [ 'menu_name','menu_slug', 'menu_status','menu_order','created_at' , 'updated_at'];

Controller Code:

        $request = $requests->get('menusettings');
        $now = date('Y-m-d H:i:s'); //alternatively you may also use Carbon::now
        $menu = [];

        foreach ($request as $reques) {
            $menu_status = isset($reques['menu_status']) ? 1 : 0;

            $menu[] = [ 'menu_name' => $reques['menu_name'] , 'menu_slug' => $reques['menu_slug'] , 'menu_status' => $menu_status , 'menu_order' => $reques['menu_order'] , 'created_at' => $now , 'updated_at' => $now];
        }
        Menu::insert($menu);
        return back();


问:
Convert a list of objects to an array of one of the object's properties
Say I have the following class:

```<code>public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}
</code>```

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

```<code>void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)
</code>```

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

答:
I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Yes, LINQ can do this. It's simply:

```<code>MyList.Select(x => x.Name).ToArray();
</code>```

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following class:

public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Body:
I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Yes, LINQ can do this. It's simply:

MyList.Select(x => x.Name).ToArray();

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.


问:
Sorting Product by names in POS (js)
How do I sort my product names in POS product list?
Here's my code, which says names.sort() is not a function.
In js file</p>

```<code>for(var i = 0, len = this.product_list.length; i < len; i++)
{
    var product_node = this.render_product(this.product_list[i]);
    var names = this.product_list[i].display_name
    var sorted_names = names.sort();
    console.log('Sorted Names',sorted_names)
}
</code>```

答:
Do something like this, </p>

```<code>var names=[];//array for names
   for(var i = 0, len = this.product_list.length; i < len; i++)
{
    var product_node = this.render_product(this.product_list[i]);
    names.push(this.product_list[i].display_name);//push name in the array
}
names.sort();//sort names
console.log(names);//sorted array
</code>```

Title: Sorting Product by names in POS (js)

Body:
How do I sort my product names in POS product list?
Here's my code, which says names.sort() is not a function.
In js file

for(var i = 0, len = this.product_list.length; i < len; i++)
{
    var product_node = this.render_product(this.product_list[i]);
    var names = this.product_list[i].display_name
    var sorted_names = names.sort();
    console.log('Sorted Names',sorted_names)
}

Body:
Do something like this,

var names=[];//array for names
   for(var i = 0, len = this.product_list.length; i < len; i++)
{
    var product_node = this.render_product(this.product_list[i]);
    names.push(this.product_list[i].display_name);//push name in the array
}
names.sort();//sort names
console.log(names);//sorted array


问:
Open my new page in pop up in asp.net
I have a regular page.When i clicked on a button it will be open in that page with some asp controls. what i need is that i want to open that page in a pop up page with close button inside it.I searched but i didn't find a properly cod for this. can any body help me?
thanks

答:
hi all Kindly use the below code

```<code>function ShowPopup() {
        $("#panOne").dialog({
            autoOpen: true,
            appendTo: "form",
            height: 600,
            width: 900
        });
    }
</code>```

appendTo: "form" is Important as if you are not using it will autopostback all values

Title: Open my new page in pop up in asp.net

Body:
hi all Kindly use the below code

function ShowPopup() {
        $("#panOne").dialog({
            autoOpen: true,
            appendTo: "form",
            height: 600,
            width: 900
        });
    }

appendTo: "form" is Important as if you are not using it will autopostback all values


问:
How to use dwsXPlatform.CollectFiles TCollectFileProgressEvent
As I am new to events in delphi I am struggling on how to use dwsXPlatform.TCollectFileProgressEvent in conjunction with dwsXPlatform.CollectFiles.

In the DWScript repository there is no sample or even test code for it.

```<code>type
        TForm1 = class(TForm)
                btn1: TButton;
                mmoDirList: TMemo;
                mmoOnCollectFiles: TMemo;
                procedure btn1Click(Sender: TObject);
        private
                OnCollectFileProgressEvent: TCollectFileProgressEvent;
        end;
{...}
procedure TForm1.btn1Click(Sender: TObject);
begin
        mmoDirList.Clear;
        CollectFiles('c:\MyDelphiFiles', '*.pas', mmoDirList.Lines, True, OnCollectFileProgressEvent);
end;
</code>```

答:
[SOLVED]</p>

```<code>unit MainFormU;

interface

uses
        Winapi.Windows,
        Winapi.Messages,
        System.SysUtils,
        System.Variants,
        System.Classes,
        Vcl.Graphics,
        Vcl.Controls,
        Vcl.Forms,
        Vcl.Dialogs,
        Vcl.StdCtrls,
        dwsXPlatform;

type
        TForm1 = class(TForm)
                btn1: TButton;
                mmoDirList: TMemo;
                mmoOnCollectFiles: TMemo;
    chkEnableOnCollectEvent: TCheckBox;
                procedure btn1Click(Sender: TObject);
                procedure OnCollectFileProgressEvent(const aDirectory: string; var aSkipScan: Boolean);
        private
                FOnCollectFiles: TCollectFileProgressEvent;
        end;

var
        Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
        mmoDirList.Clear;
        mmoOnCollectFiles.Clear;

        if chkEnableOnCollectEvent.Checked then
                FOnCollectFiles := OnCollectFileProgressEvent
        else
                FOnCollectFiles := nil;

        // procedure CollectFiles(const directory: UnicodeString;
        //                              fileMask: UnicodeString;
        //                              list: TStrings;
        //                              recurseSubdirectories: Boolean = False;
        //                              onProgress: TCollectFileProgressEvent = nil);

        CollectFiles('c:\MyFolder\', '*.pas', mmoDirList.Lines, True, FOnCollectFiles);
end;

procedure TForm1.OnCollectFileProgressEvent(const aDirectory: string; var aSkipScan: Boolean);
begin
        if aDirectory = 'c:\MyFolder\SkipThisFolder\' then begin
                ShowMessage('Folder ' + aDirectory + ' was skipped!');
                aSkipScan := True;
        end;

        mmoOnCollectFiles.Lines.Add(aDirectory);
end;

end.
</code>```

Body:
As I am new to events in delphi I am struggling on how to use dwsXPlatform.TCollectFileProgressEvent in conjunction with dwsXPlatform.CollectFiles.

In the DWScript repository there is no sample or even test code for it.

type
        TForm1 = class(TForm)
                btn1: TButton;
                mmoDirList: TMemo;
                mmoOnCollectFiles: TMemo;
                procedure btn1Click(Sender: TObject);
        private
                OnCollectFileProgressEvent: TCollectFileProgressEvent;
        end;
{...}
procedure TForm1.btn1Click(Sender: TObject);
begin
        mmoDirList.Clear;
        CollectFiles('c:\MyDelphiFiles', '*.pas', mmoDirList.Lines, True, OnCollectFileProgressEvent);
end;

Body:
[SOLVED]

unit MainFormU;

interface

uses
        Winapi.Windows,
        Winapi.Messages,
        System.SysUtils,
        System.Variants,
        System.Classes,
        Vcl.Graphics,
        Vcl.Controls,
        Vcl.Forms,
        Vcl.Dialogs,
        Vcl.StdCtrls,
        dwsXPlatform;

type
        TForm1 = class(TForm)
                btn1: TButton;
                mmoDirList: TMemo;
                mmoOnCollectFiles: TMemo;
    chkEnableOnCollectEvent: TCheckBox;
                procedure btn1Click(Sender: TObject);
                procedure OnCollectFileProgressEvent(const aDirectory: string; var aSkipScan: Boolean);
        private
                FOnCollectFiles: TCollectFileProgressEvent;
        end;

var
        Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
        mmoDirList.Clear;
        mmoOnCollectFiles.Clear;

        if chkEnableOnCollectEvent.Checked then
                FOnCollectFiles := OnCollectFileProgressEvent
        else
                FOnCollectFiles := nil;

        // procedure CollectFiles(const directory: UnicodeString;
        //                              fileMask: UnicodeString;
        //                              list: TStrings;
        //                              recurseSubdirectories: Boolean = False;
        //                              onProgress: TCollectFileProgressEvent = nil);

        CollectFiles('c:\MyFolder\', '*.pas', mmoDirList.Lines, True, FOnCollectFiles);
end;

procedure TForm1.OnCollectFileProgressEvent(const aDirectory: string; var aSkipScan: Boolean);
begin
        if aDirectory = 'c:\MyFolder\SkipThisFolder\' then begin
                ShowMessage('Folder ' + aDirectory + ' was skipped!');
                aSkipScan := True;
        end;

        mmoOnCollectFiles.Lines.Add(aDirectory);
end;

end.


问:
Can't access camera from Android webView (chrome frame) in context of webRTC
App is based on webRTC vs websocket .
Android studio 2.3.2 last version.

I already use:

https protocol , autoplay ,  android version 7.0 (min > android 5.0) .
 App works on all supported browsers only android webview generate error.

This is first lines of errors log in logcat (android studio last ver):

E/chromium: [ERROR:audio_manager_android.cc(264)] Unable to select audio device! E/cr_VideoCapture: allocate: manager.openCamera:
                                                                                SecurityException: validateConnectLocked:1112: Caller
  "com.testwebrtc.nikola.myapplication" cannot
  open camera "1" without camera permission
                                                                                at
  android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:628)
                                                                                at
  android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:347)
                                                                                at
  android.hardware.camera2.CameraManager.openCamera(CameraManager.java:450)
                                                                                at
  org.chromium.media.VideoCaptureCamera2.startCapture(VideoCaptureCamera2.java:661)

Other variant for error:

[ERROR:web_contents_delegate.cc(199)]
  WebContentsDelegate::CheckMediaAccessPermission: Not supported.

This is error log from chrome/webview (from errorCallBack - getUserMedia ):

```<code>      An error occcurred [CODE NotAllowedError]

      other error variant:

      trackstarterror
</code>```

Android Code looks like:

```<code>package com.project.TEST.xxx;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(1) )
                .commit();

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        private WebView mWebRTCWebView;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            mWebRTCWebView = (WebView) rootView.findViewById(R.id.fragment_main_webview);

            setUpWebViewDefaults(mWebRTCWebView);

            mWebRTCWebView.loadUrl("https://example.com/");

            mWebRTCWebView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onPermissionRequest(final PermissionRequest request) {
                    Log.d(TAG, "onPermissionRequest");
                    getActivity().runOnUiThread(new Runnable() {
                        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void run() {

                            request.grant(request.getResources());

                        }
                    });
                }

            });

            return rootView;
        }

        @Override
        public void onStop() {
            super.onStop();

            /**
             * When the application falls into the background we want to stop the media stream
             * such that the camera is free to use by other apps.
             */
            mWebRTCWebView.evaluateJavascript("if(window.localStream){window.localStream.stop();}", null);
        }

        /*
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
*/

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);

            Activity a;

            if (context instanceof Activity){
                a=(Activity) context;

            }

        }

        /**
         * Convenience method to set some generic defaults for a
         * given WebView
         *
         * @param webView
         */
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private void setUpWebViewDefaults(WebView webView) {
            WebSettings settings = webView.getSettings();

            // Enable Javascript
            settings.setJavaScriptEnabled(true);

            // Use WideViewport and Zoom out if there is no viewport defined
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);

            // Enable pinch to zoom without the zoom buttons
            settings.setBuiltInZoomControls(true);

            // Allow use of Local Storage
            settings.setDomStorageEnabled(true);

            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                // Hide the zoom controls for HONEYCOMB+
                settings.setDisplayZoomControls(false);
            }

            // Enable remote debugging via chrome://inspect
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WebView.setWebContentsDebuggingEnabled(true);
            }

            webView.setWebViewClient(new WebViewClient());

            // AppRTC requires third party cookies to work
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(mWebRTCWebView, true);
        }
    }

}
</code>```

Build.gradle-project :

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

gradle - module:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.project.test.xxx"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-fexceptions"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Android  Manifest.xml :

```<code>....
  <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT" />
    <uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="true" />
    <uses-feature android:name="android.hardware.camera.front" android:required="true" />
    <uses-feature android:name="android.hardware.camera" android:required="true" />
    <uses-feature android:name="android.hardware.camera.level.full" android:required="true" />
    <uses-feature android:name="android.hardware.camera.capability.raw" android:required="true" />
    <uses-feature android:name="android.hardware.camera.any" android:required="true" />
    <uses-feature android:name="android.hardware.microphone" android:required="true" />
    <uses-feature android:name="android.hardware.camera2" android:required="true" />

...
</code>```

答:
The WebView requests permission from the App, but the App is not granted these permissions from the user.

You should invoke App's permission request to the user, as mentioned in this document.

Now I found that the permissions WebRTC requires is those:

```<code>onPermissionRequest: android.webkit.resource.VIDEO_CAPTURE
onPermissionRequest: android.webkit.resource.AUDIO_CAPTURE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
App is based on webRTC vs websocket .
Android studio 2.3.2 last version.

I already use:

https protocol , autoplay ,  android version 7.0 (min > android 5.0) .
 App works on all supported browsers only android webview generate error.

This is first lines of errors log in logcat (android studio last ver):

E/chromium: [ERROR:audio_manager_android.cc(264)] Unable to select audio device! E/cr_VideoCapture: allocate: manager.openCamera:
                                                                                SecurityException: validateConnectLocked:1112: Caller
  "com.testwebrtc.nikola.myapplication" cannot
  open camera "1" without camera permission
                                                                                at
  android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:628)
                                                                                at
  android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:347)
                                                                                at
  android.hardware.camera2.CameraManager.openCamera(CameraManager.java:450)
                                                                                at
  org.chromium.media.VideoCaptureCamera2.startCapture(VideoCaptureCamera2.java:661)

Other variant for error:

[ERROR:web_contents_delegate.cc(199)]
  WebContentsDelegate::CheckMediaAccessPermission: Not supported.

This is error log from chrome/webview (from errorCallBack - getUserMedia ):

      An error occcurred [CODE NotAllowedError]

      other error variant:

      trackstarterror

Android Code looks like:

package com.project.TEST.xxx;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(1) )
                .commit();

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        private WebView mWebRTCWebView;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            mWebRTCWebView = (WebView) rootView.findViewById(R.id.fragment_main_webview);

            setUpWebViewDefaults(mWebRTCWebView);

            mWebRTCWebView.loadUrl("https://example.com/");

            mWebRTCWebView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onPermissionRequest(final PermissionRequest request) {
                    Log.d(TAG, "onPermissionRequest");
                    getActivity().runOnUiThread(new Runnable() {
                        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void run() {

                            request.grant(request.getResources());

                        }
                    });
                }

            });

            return rootView;
        }

        @Override
        public void onStop() {
            super.onStop();

            /**
             * When the application falls into the background we want to stop the media stream
             * such that the camera is free to use by other apps.
             */
            mWebRTCWebView.evaluateJavascript("if(window.localStream){window.localStream.stop();}", null);
        }

        /*
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
*/

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);

            Activity a;

            if (context instanceof Activity){
                a=(Activity) context;

            }

        }

        /**
         * Convenience method to set some generic defaults for a
         * given WebView
         *
         * @param webView
         */
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private void setUpWebViewDefaults(WebView webView) {
            WebSettings settings = webView.getSettings();

            // Enable Javascript
            settings.setJavaScriptEnabled(true);

            // Use WideViewport and Zoom out if there is no viewport defined
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);

            // Enable pinch to zoom without the zoom buttons
            settings.setBuiltInZoomControls(true);

            // Allow use of Local Storage
            settings.setDomStorageEnabled(true);

            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                // Hide the zoom controls for HONEYCOMB+
                settings.setDisplayZoomControls(false);
            }

            // Enable remote debugging via chrome://inspect
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WebView.setWebContentsDebuggingEnabled(true);
            }

            webView.setWebViewClient(new WebViewClient());

            // AppRTC requires third party cookies to work
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(mWebRTCWebView, true);
        }
    }

}

Build.gradle-project :

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

gradle - module:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.project.test.xxx"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-fexceptions"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Android  Manifest.xml :

....
  <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT" />
    <uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="true" />
    <uses-feature android:name="android.hardware.camera.front" android:required="true" />
    <uses-feature android:name="android.hardware.camera" android:required="true" />
    <uses-feature android:name="android.hardware.camera.level.full" android:required="true" />
    <uses-feature android:name="android.hardware.camera.capability.raw" android:required="true" />
    <uses-feature android:name="android.hardware.camera.any" android:required="true" />
    <uses-feature android:name="android.hardware.microphone" android:required="true" />
    <uses-feature android:name="android.hardware.camera2" android:required="true" />

...

Body:
The WebView requests permission from the App, but the App is not granted these permissions from the user.

You should invoke App's permission request to the user, as mentioned in this document.

Now I found that the permissions WebRTC requires is those:

onPermissionRequest: android.webkit.resource.VIDEO_CAPTURE
onPermissionRequest: android.webkit.resource.AUDIO_CAPTURE


答:
One option is to pass in an Action as part of the class constructor (or a Func if you want to return a value). For example:

```<code>public class MyThing
{
    private Action<MyThing> _doCalc { get; set; }

    public MyThing(Action<MyThing> doCalc)
    {
        _doCalc = doCalc;

    }

    public void DoCalc()
    {
        _doCalc(this);
    }

    public string SomeString { get; set; }
}
</code>```

And call it like this:

```<code>var thing = new MyThing(t => Console.WriteLine(t.SomeString));
thing.SomeString = "Hello world";
thing.DoCalc();
</code>```

Another variation of this would be to create a generic wrapper class, for example:

```<code>public class Wrapper<T>
{
    private Action<T> _doCalc { get; set; }

    public Wrapper(Action<T> doCalc)
    {
        _doCalc = doCalc;
    }

    public T Value { get; set; }

    public void DoCalc()
    {
        _doCalc(this.Value);
    }
}
</code>```

And now you can do this:

```<code>var stringWrapper = new Wrapper<string>(t => Console.WriteLine("string wrapper"));
var intWrapper = new Wrapper<int>(t => Console.WriteLine("int wrapper"));

stringWrapper.DoCalc();
intWrapper.DoCalc();
</code>```

Title: c# .net: Extend existing class with method that should be overriden when initialized

Body:
One option is to pass in an Action as part of the class constructor (or a Func if you want to return a value). For example:

public class MyThing
{
    private Action<MyThing> _doCalc { get; set; }

    public MyThing(Action<MyThing> doCalc)
    {
        _doCalc = doCalc;

    }

    public void DoCalc()
    {
        _doCalc(this);
    }

    public string SomeString { get; set; }
}

And call it like this:

var thing = new MyThing(t => Console.WriteLine(t.SomeString));
thing.SomeString = "Hello world";
thing.DoCalc();

Another variation of this would be to create a generic wrapper class, for example:

public class Wrapper<T>
{
    private Action<T> _doCalc { get; set; }

    public Wrapper(Action<T> doCalc)
    {
        _doCalc = doCalc;
    }

    public T Value { get; set; }

    public void DoCalc()
    {
        _doCalc(this.Value);
    }
}

And now you can do this:

var stringWrapper = new Wrapper<string>(t => Console.WriteLine("string wrapper"));
var intWrapper = new Wrapper<int>(t => Console.WriteLine("int wrapper"));

stringWrapper.DoCalc();
intWrapper.DoCalc();


问:
phalconphp hasMany() and belongsTo() not joining
I've been trying to retrieve my data by doing a findFirst() call, but it doesn't work. I've been trying so much and seeking everywhere, but didn't find solution.

I have these tables:

```<code>- fruit
    fruit_id
    fruit_name
- fruit_color
    fruit_id
    fruit_color_name
</code>```

In my fruit model @Initialize(), I declare:

```<code>$this->hasOne('fruit_id', 'fruitColor', 'fruit_id');
</code>```

In my fruit_color model, @initalize(), I have:

```<code>$this->belongsTo('fruit_id', 'fruit', 'fruit_id');
</code>```

When I call find() or findFirst() methods, I can't retrieve anything. when I print out and the debug, I see that no join has been called and I only get a simple SELECT (*).

Do you have any clue?

答:
I think you did not understand the idea of model relations. I will try to explain with examples.

Model relations do not make Joins at all. They will make additional query when you request the related model.

Model Relations

```<code>public function initialize()
{
    $this->hasMany('id', 'Models\ServicesVideos', 'service_id', [
        'alias' => 'videos',
        'params' => [
            'order' => 'position ASC',
            'conditions' => 'type = :type:',
            'bind' => [
                'type' => get_class($this)
            ]
        ]
    ]);
}
</code>```

With the relation defined above you can use it like so:

```<code>$user = Users::findFirst(12);
$user->videos; // This will return all videos for this user
</code>```

More info about Model Relations: https://docs.phalconphp.com/en/3.2/db-models-relationships

However if you need to join two or more tables you want to use the Query Builder.

```<code>$lang = $this->getDI()->getSession()->language;
$cacheFile = 'news-'. $lang;
$items = $this->modelsManager->createBuilder()
    ->columns([
        'main.id',
        'main.title',
        'main.slug',
        'main.summary',

        'upload.id AS imageId',
        'upload.filename AS imageFilename',
        'upload.ver AS uploadVersion',
    ])
    ->from(['main' => 'Models\News'])
    ->leftJoin('Models\Uploads', 'upload.foreign_key = main.id AND upload.section = "newsImage" AND upload.is_active = "1" AND upload.is_default = "1"', 'upload')
    ->where('main.is_active = 1')
    ->andWhere('main.lang = :lang:', ['lang' => $lang])
    ->orderBy('main.ord ASC')
    ->getQuery()->cache(['key' => $cacheFile])->execute();
</code>```

More info about the Query Builder: https://docs.phalconphp.com/en/3.2/db-models

Body:
I've been trying to retrieve my data by doing a findFirst() call, but it doesn't work. I've been trying so much and seeking everywhere, but didn't find solution.

I have these tables:

- fruit
    fruit_id
    fruit_name
- fruit_color
    fruit_id
    fruit_color_name

In my fruit model @Initialize(), I declare:

$this->hasOne('fruit_id', 'fruitColor', 'fruit_id');

In my fruit_color model, @initalize(), I have:

$this->belongsTo('fruit_id', 'fruit', 'fruit_id');

When I call find() or findFirst() methods, I can't retrieve anything. when I print out and the debug, I see that no join has been called and I only get a simple SELECT (*).

Do you have any clue?

Body:
I think you did not understand the idea of model relations. I will try to explain with examples.

Model relations do not make Joins at all. They will make additional query when you request the related model.

Model Relations

public function initialize()
{
    $this->hasMany('id', 'Models\ServicesVideos', 'service_id', [
        'alias' => 'videos',
        'params' => [
            'order' => 'position ASC',
            'conditions' => 'type = :type:',
            'bind' => [
                'type' => get_class($this)
            ]
        ]
    ]);
}

With the relation defined above you can use it like so:

$user = Users::findFirst(12);
$user->videos; // This will return all videos for this user

More info about Model Relations: https://docs.phalconphp.com/en/3.2/db-models-relationships

However if you need to join two or more tables you want to use the Query Builder.

$lang = $this->getDI()->getSession()->language;
$cacheFile = 'news-'. $lang;
$items = $this->modelsManager->createBuilder()
    ->columns([
        'main.id',
        'main.title',
        'main.slug',
        'main.summary',

        'upload.id AS imageId',
        'upload.filename AS imageFilename',
        'upload.ver AS uploadVersion',
    ])
    ->from(['main' => 'Models\News'])
    ->leftJoin('Models\Uploads', 'upload.foreign_key = main.id AND upload.section = "newsImage" AND upload.is_active = "1" AND upload.is_default = "1"', 'upload')
    ->where('main.is_active = 1')
    ->andWhere('main.lang = :lang:', ['lang' => $lang])
    ->orderBy('main.ord ASC')
    ->getQuery()->cache(['key' => $cacheFile])->execute();

More info about the Query Builder: https://docs.phalconphp.com/en/3.2/db-models


问:
How to prevent page from refreshing on selection of First Drop Down List value
I have Two 'DropDownLists' which I want to Fill with the help of first 'DropDownList'. I have successfully filled both 'DropDownLists' but when I select the value from the first 'DropDownList', my page refreshes every time. Please help me. What should I do or how to prevent page form refreshing?</p>

答:
You can fill the second DropDownList on client-side using AJAX, instead of server-side to avoid postback

Ajax

```<code>$('#firstDropDown').change(function() {
    $.ajax
    ({
        type: "GET",
        url: "yourCodebehind.aspx/yourMethod"
        data: '{arg: "' + $('#firstDropDown').val() + '" }',
        dataType: "json",
        success: function(result)
        {
            for (var i = 0; i < result.d.length; i++) {
                $('#secondDropDown').append('<option>'+result.d[i]+'</option>');
        }
    });
});
</code>```

yourCodebehind.aspx

```<code>[System.Web.Services.WebMethod]
public static Array yourMethod(var arg)
{
    //Fetch your data
    return array;
}
</code>```

Body:
You can fill the second DropDownList on client-side using AJAX, instead of server-side to avoid postback

Ajax

$('#firstDropDown').change(function() {
    $.ajax
    ({
        type: "GET",
        url: "yourCodebehind.aspx/yourMethod"
        data: '{arg: "' + $('#firstDropDown').val() + '" }',
        dataType: "json",
        success: function(result)
        {
            for (var i = 0; i < result.d.length; i++) {
                $('#secondDropDown').append('<option>'+result.d[i]+'</option>');
        }
    });
});

yourCodebehind.aspx

[System.Web.Services.WebMethod]
public static Array yourMethod(var arg)
{
    //Fetch your data
    return array;
}


问:
is this Laravel Relationship error undefined variable $task
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

```<code>@foreach($task->files as $file) //line 14
                <div>
                    <div><i class="fa fa-check-square-o"></i>
                        <span>

                            <a href="{{ $file->file_url }}" target="_blank">{{ $file->file_name }}</a>

                   </span>
                    </div>
                </div>
</code>```

and My FileController is this

```<code>use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);
</code>```

and route is this

```<code>Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);
</code>```

but got this error

```<code>ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)
</code>```

how can fix this problem?

file Model

```<code>use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}
</code>```

答:
You have to pass $task data to your view (blade file) like this</p>

```<code>return view('files.form', $task);
</code>```

Body:
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

@foreach($task->files as $file) //line 14

                            file_url }}" target="_blank">{{ $file->file_name }}

and My FileController is this

use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);

and route is this

Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);

but got this error

ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)

how can fix this problem?

file Model

use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}

Body:
You have to pass $task data to your view (blade file) like this

return view('files.form', $task);


问:
How to read auto-filled username/password from a form using Ember
Right now I have a form that has two input: username and password. If I typed them manually, my validation function can pick up the values. However, if the values are filled by broswer's autofill feature. Ember cannot get the value due to no event is fired.
So I have this code (from https://stackoverflow.com/questions/22324473/browser-autofill-databinding):

```<code>import Ember from 'ember';
export default Ember.TextField.reopen({
  triggerEvents: function () {
    Ember.run.next(this, function () {
      this.$().trigger("change");
    });
  }.on("didInsertElement")
});
</code>```

And I imported it into app.js

Somehow, it is still not working. Will didInsertElement be triggered by autofill? I am not sure.

I use this.get('xxx') to get the values.

If you have a better way to allow ember detect autofill. I am open to it.

答:
Just add observer for form fields.
Example:

```<code>// app/components/test-form.js
import Component from '@ember/component';
    export default Component.extend({
      isChanged: Ember.observer('login', 'password', function() {
        this.validate();
      }),
      validate() {
        let login = this.get('login');
        let password = this.get('password');
        console.log('validate', login, password);
      },
      actions: {
        submit() {
          console.log('submit');
        }
      }
    });

// app/templates/components/test-form.hbs
<form>
  <label>Login
  {{input type="text" value=login change='validate' }}
  </label>
  <label>Password
  {{input type="password" value=password change='validate' }}
  </label>
  <button {{action 'submit'}}>Click</button>
</form>
</code>```

PS. Tested in Firefox only.

Body:
Right now I have a form that has two input: username and password. If I typed them manually, my validation function can pick up the values. However, if the values are filled by broswer's autofill feature. Ember cannot get the value due to no event is fired.
So I have this code (from https://stackoverflow.com/questions/22324473/browser-autofill-databinding):

import Ember from 'ember';
export default Ember.TextField.reopen({
  triggerEvents: function () {
    Ember.run.next(this, function () {
      this.$().trigger("change");
    });
  }.on("didInsertElement")
});

And I imported it into app.js

Somehow, it is still not working. Will didInsertElement be triggered by autofill? I am not sure.

I use this.get('xxx') to get the values.

If you have a better way to allow ember detect autofill. I am open to it.

Body:
Just add observer for form fields.
Example:

// app/components/test-form.js
import Component from '@ember/component';
    export default Component.extend({
      isChanged: Ember.observer('login', 'password', function() {
        this.validate();
      }),
      validate() {
        let login = this.get('login');
        let password = this.get('password');
        console.log('validate', login, password);
      },
      actions: {
        submit() {
          console.log('submit');
        }
      }
    });

// app/templates/components/test-form.hbs
<form>
  <label>Login
  {{input type="text" value=login change='validate' }}
  </label>
  <label>Password
  {{input type="password" value=password change='validate' }}
  </label>
  <button {{action 'submit'}}>Click</button>
</form>

PS. Tested in Firefox only.


问:
How to pass a php variable from hidden input value to a php script?
I have this form INSIDE a table :

```<code>while($row=mysqli_fetch_array($result)){
    echo "<tr>";
        echo "<td>".$row['first_name'] . "</td>";
        echo "<td>" . $row['last_name'] . "</td>";
        <td>
            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>
       </td>
</code>```

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

```<code><?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>
</code>```

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

答:
```<code><form action="send_notification.php" method="POST">
</code>```

here you specified that you want the value passed with POST

```<code> $id=$_GET['first_name'];
</code>```

and here you just ask it to be in the GET superglobal, it should be pretty obvious now, use $_POST, also, the name of your hidden input is id, and you ask for first name

but i was just wondering, the td on line 5 in your php isn't missing an echo or a closing php tag ? thats a strange way to do things, it seems you are mixing php echos with html containing php tags

Body:
I have this form INSIDE a table :

while($row=mysqli_fetch_array($result)){
    echo "
";
        echo "".$row['first_name'] . "	";
        echo "" . $row['last_name'] . "	";

            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

<?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

Body:
<form action="send_notification.php" method="POST">

here you specified that you want the value passed with POST

 $id=$_GET['first_name'];

and here you just ask it to be in the GET superglobal, it should be pretty obvious now, use $_POST, also, the name of your hidden input is id, and you ask for first name

but i was just wondering, the td on line 5 in your php isn't missing an echo or a closing php tag ? thats a strange way to do things, it seems you are mixing php echos with html containing php tags


问:
Data structure for game Dots and Boxes
What would be a good data structure to represent the status of the game Dots and Boxes?

I came up with using 2 matrices of boolean, for horizontal and vertical lines, but maybe there's a more elegant way of doing this (and the operations: add line, check line, check square).

答:
I would use a single two-dimensional array that corresponds to the play area size.  Each element in the array can then store either an object (or structure, depending on language used) that contains 4 bools, one for each side.  Checking to see if a box is complete becomes as simple as returning the logical ands of the object at the given co-ordinates.  </p>

<p>The single two-dimensional array makes maintenance and troubleshooting errors much easier. </p>

Title: Data structure for game Dots and Boxes

Body:
I would use a single two-dimensional array that corresponds to the play area size.  Each element in the array can then store either an object (or structure, depending on language used) that contains 4 bools, one for each side.  Checking to see if a box is complete becomes as simple as returning the logical ands of the object at the given co-ordinates.

The single two-dimensional array makes maintenance and troubleshooting errors much easier.


问:
iOS Enterprise App: Distribute Over the air : Untrusted Enterprise Developer
I have uploaded my .ipa and manifest.plist to my server (say : https: // www.xxxxxxx . xom/app/). And I created a install page in that server.

In that install html page I have the  hyper link to download my app

```<code><a href="itms-services://?action=download-manifest&url=http s: // xxxxxxx.com/ios/manifest.plist">
Download My  iOS App
</a>
</code>```

If I try to install the app through this install page, the app get downloaded and installed. When I tap the app, it shows "untrusted Enterprise developer". And also I cant able to see "Profile and device management" in the setting app

Kindly help me how can i get rid of this "Untrusted Enterprise Developer"

Note:
I have already installed different certificate in my phone. Thats why It is not showing for my phone. But it is working in other iPhones

答:
Here is proper document from Apple - Install custom enterprise apps on iOS

Installing and Trusting an Enterprise App

When you first open an enterprise app you've manually installed, you see a notification that the developer of the app isn't trusted on your device. You can dismiss this message but you can't open the app.

After dismissing this message you can establish trust for this app developer.

(Tap) Settings ▶ General ▶ Profiles or Profiles & Device Management.

You then see a a profile for the developer under the "Enterprise App" heading.

Tap the profile to establish trust for this developer.

You're then prompted to confirm your choice. Once you trust this profile, you can manually install other apps from the same developer and open them immediately. This developer remains trusted until you use the Delete App button to remove all apps from the developer.

Body:
I have uploaded my .ipa and manifest.plist to my server (say : https: // www.xxxxxxx . xom/app/). And I created a install page in that server.

In that install html page I have the  hyper link to download my app

Download My  iOS App

If I try to install the app through this install page, the app get downloaded and installed. When I tap the app, it shows "untrusted Enterprise developer". And also I cant able to see "Profile and device management" in the setting app

Kindly help me how can i get rid of this "Untrusted Enterprise Developer"

Note:
I have already installed different certificate in my phone. Thats why It is not showing for my phone. But it is working in other iPhones


问:
Table with position: fixed doesn't scroll with overflow: scroll
I have two tables: the first is a header, the second contains data. I want to see the header when I scroll down, so its table has position: fixed. The tables can be too large to be shown on the screen at once, so I wrapped them in a div with overflow: scroll;.

My problem can be see here: https://jsfiddle.net/xa86wgw9/3/

When I scroll down, the header doesn't move; that's what I want. But when I scroll to the right, the header stay on the left... is there a way to have the two table stay aligned ? css and javascript can be used.

EDIT: I'm currently working on IE10, so position: sticky isn't an option.

答:
It is not necessary to use 2 tables to achieve what you want.It is possible by 1 table code itself.

Fiddle created here to test the scrolling of the body section and keeping the header fixed
http://jsfiddle.net/pxgq1j4p/

You need to use

```<code><thead>
<tbody>
</code>```

Body:
It is not necessary to use 2 tables to achieve what you want.It is possible by 1 table code itself.

Fiddle created here to test the scrolling of the body section and keeping the header fixed
http://jsfiddle.net/pxgq1j4p/

You need to use

<thead>
<tbody>


答:
According to the documentation TCollectFileProgressEvent is dseclared as following:

```<code>TCollectFileProgressEvent = procedure (const directory : String; var skipScan : Boolean) of object;
</code>```

Let's split that into 3 pieces:

1)    TCollectFileProgressEvent

2)    procedure (const directory : String; var skipScan : Boolean)

3)    of object

The first part TCollectFileProgressEvent is the name of the event type. You don't need that for any thing in your example.

The second part procedure .... Is a recipe of how you should declare the event

The third part "of object" means that your procedure needs to be placed on a class.

Let me show you some code:

```<code>  TForm1 = class(TForm)
    btn1: TButton;
    mmoDirList: TMemo;
    mmoOnCollectFiles: TMemo;
    procedure btn1Click(Sender: TObject);
  private
    procedure CollectFileProgress(const directory : String; var skipScan : Boolean);
  end;

{ TForm1 }

procedure TForm1.btn1Click(Sender: TObject);
begin
  mmoDirList.Clear;
  CollectFiles('c:\MyDelphiFiles', '*.pas', mmoDirList.Lines, True, CollectFileProgress);
end;

procedure TForm1.CollectFileProgress(const directory: String; var skipScan: Boolean);
begin
  mmoDirList.Lines.Add(directory);
end;
</code>```

Title: How to use dwsXPlatform.CollectFiles TCollectFileProgressEvent

Body:
As I am new to events in delphi I am struggling on how to use dwsXPlatform.TCollectFileProgressEvent in conjunction with dwsXPlatform.CollectFiles.

In the DWScript repository there is no sample or even test code for it.

type
        TForm1 = class(TForm)
                btn1: TButton;
                mmoDirList: TMemo;
                mmoOnCollectFiles: TMemo;
                procedure btn1Click(Sender: TObject);
        private
                OnCollectFileProgressEvent: TCollectFileProgressEvent;
        end;
{...}
procedure TForm1.btn1Click(Sender: TObject);
begin
        mmoDirList.Clear;
        CollectFiles('c:\MyDelphiFiles', '*.pas', mmoDirList.Lines, True, OnCollectFileProgressEvent);
end;

Body:
According to the documentation TCollectFileProgressEvent is dseclared as following:

TCollectFileProgressEvent = procedure (const directory : String; var skipScan : Boolean) of object;

Let's split that into 3 pieces:

1)    TCollectFileProgressEvent

2)    procedure (const directory : String; var skipScan : Boolean)

3)    of object

The first part TCollectFileProgressEvent is the name of the event type. You don't need that for any thing in your example.

The second part procedure .... Is a recipe of how you should declare the event

The third part "of object" means that your procedure needs to be placed on a class.

Let me show you some code:

  TForm1 = class(TForm)
    btn1: TButton;
    mmoDirList: TMemo;
    mmoOnCollectFiles: TMemo;
    procedure btn1Click(Sender: TObject);
  private
    procedure CollectFileProgress(const directory : String; var skipScan : Boolean);
  end;

{ TForm1 }

procedure TForm1.btn1Click(Sender: TObject);
begin
  mmoDirList.Clear;
  CollectFiles('c:\MyDelphiFiles', '*.pas', mmoDirList.Lines, True, CollectFileProgress);
end;

procedure TForm1.CollectFileProgress(const directory: String; var skipScan: Boolean);
begin
  mmoDirList.Lines.Add(directory);
end;


问:
Non-null variable is being called null?
```<code>protected var categoryXML:XML;
protected var categoryArr:ArrayCollection;
protected var categoryList:IList;

for (var i:int=0;i<getLength(categoryXML.category);i++) {
   trace(categoryXML.category[i].name);
   categoryArr[i] = categoryXML.category[i].name;
}
</code>```

I'm having trouble with this bit of code...

The trace here works great, and I get the response I expect, but when I try to add it to the categoryArr variable, I get yelled at and told it's null.

What could cause the difference here?

Thanks!

答: did you try to create your ArrayCollection : categoryArr = new ArrayCollection(); ?

Title: Non-null variable is being called null?

Body:
protected var categoryXML:XML;
protected var categoryArr:ArrayCollection;
protected var categoryList:IList;

for (var i:int=0;i<getLength(categoryXML.category);i++) {
   trace(categoryXML.category[i].name);
   categoryArr[i] = categoryXML.category[i].name;
}

I'm having trouble with this bit of code...

The trace here works great, and I get the response I expect, but when I try to add it to the categoryArr variable, I get yelled at and told it's null.

What could cause the difference here?

Thanks!


问:
switch to "trace" log level, but only for current web request (nLog)
I would like the ability to turn on trace-level logging in nLog, on production, but only for the current web request.

In other words, I'd like to be able to do something like...

http://mywebsite.com?logeverything=true

... which would do trace-level logging, but only for that web request, not the hundreds of other requests that are happening at the same time.  I'd also like the logs for that request to go to a different file than where the rest of the logging is going to.  An acceptable alternative to a query string would be to turn on the trace-level logging but only if the web request is local.

I could write my own Logger class and override the nLog log methods to do something along these lines, but my web project uses a number of different assemblies and and switching all the projects to use a new logger class would be something of a pain.

Anyone doing anything like this?

答:
This could be done without the need of wrappers.

Install also NLog.Web (or in the case of ASP.NET Core: NLog.Web.AspNetCore nd follow the installation tutorial

Create your trace logs in c#

Write to session it's your request

Filter your logs in the .config

<logger name="*" writeTo="myFile">
   <filters>
     <when condition="${aspnet-session:Variable=myRequest} != 1" action="Ignore" />
  </filters>
</logger>
```

in this case I use the session, but you could also use ${aspnet-request-url}    - but that makes the config a bit more complicated

Body:
This could be done without the need of wrappers.

Install also NLog.Web (or in the case of ASP.NET Core: NLog.Web.AspNetCore nd follow the installation tutorial

Create your trace logs in c#

Write to session it's your request

Filter your logs in the .config

<logger name="*" writeTo="myFile">
   <filters>
     <when condition="${aspnet-session:Variable=myRequest} != 1" action="Ignore" />
  </filters>
</logger>

in this case I use the session, but you could also use ${aspnet-request-url}    - but that makes the config a bit more complicated


问:
Ajax fails when sending a data object to the NodeJs server
when pressing a button this code gets executed

```<code>function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}
</code>```

and the server is listening on this

```<code>app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});
</code>```

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

```<code>const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});
</code>```

my route

```<code>module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};
</code>```

and my client function

```<code>function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

And when executing the Ajax call the client still runs into .fail()

答:
Try this..

Client Side

```<code>function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit', // listen to a route
        'Content-Type': 'application/json',
        data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
    }).done(function () {
        console.log('hi')
    }).fail(function () {
        console.log("Error");
    });
}
</code>```

On server Side:

```<code>var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());

app.post('/questionnaire/submit', function (req, res) {
var data = req.body
    console.log(data);

    res.send(null); // Send nothing back
});
</code>```

You have to install body-parser library using following command.

npm install --save body-parser

It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question.
If you are not understanding anything plz comment below.

Body:
when pressing a button this code gets executed

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail()

Body:
Try this..

Client Side

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit', // listen to a route
        'Content-Type': 'application/json',
        data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
    }).done(function () {
        console.log('hi')
    }).fail(function () {
        console.log("Error");
    });
}

On server Side:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());

app.post('/questionnaire/submit', function (req, res) {
var data = req.body
    console.log(data);

    res.send(null); // Send nothing back
});

You have to install body-parser library using following command.

npm install --save body-parser

It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question.
If you are not understanding anything plz comment below.


问:
How to avoid saving report output version in cognos?
I am working on cognos and user wants that the output version of report is not saved with report.

I looked for options and found below screen that has radio button making it impossible to uncheck. Setting value to zero means unlimited number of output.

答:
I believe setting Duration to 0 days will stop output versions being saved.

If not, set it to 1 day and it will clear itself each night.


问:
IllegalStateException when trying to query a MongoDB domain class using Grails 2.3.7
I am working on a legacy project that uses Grails 2.3.7 (with Maven) and Java 7, and I have to add a connection to a MongoDB database while keeping the existing Hibernate ones.

I have added the following to my pom.xml file:

```<code><dependency>
    <groupId>org.grails.plugins</groupId>
    <artifactId>mongodb</artifactId>
    <type>zip</type>
    <version>3.0.2</version>
</dependency>
</code>```

And this to the BuildConfig.groovy file:

```<code>plugins {
    compile ':mongodb:3.0.2'
    compile 'org.grails.plugins:mongodb:3.0.2'
}
</code>```

(I have tried it both with and without the compile 'org.grails.plugins:mongodb:3.0.2' line)

On the DataSource.groovy file I have configured the db connection as follows:

```<code>grails {
    mongodb {
        host = "xxx.xxx.xxx.xxx"
        port = "27017"
        databaseName = "db"
        username = "user"
        password = "pass"
    }
}
</code>```

and the connection itself seems to be working, because if I change any value in there the Grails application does not even start.

I have then created a simple Domain class, Thingy.groovy:

```<code>class Thingy {

    String identifier
    String description

    static mapWith = "mongo"

    static constraints = {
    }
}
</code>```

And now, when I start the app, any call to methods of that class throws an IllegalStateException: "Method on class [Thingy] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.". However, if at the same place I call any methods of the old Domain classes that use the other datasource, they work like a charm.

Also, when starting the server I get another exception which I guess might be related, but I'm not sure what to do with it either: ERROR - Error configuring dynamic methods for plugin [mongodb:3.0.2]: org/grails/datastore/mapping/query/api/BuildableCriteria
java.lang.NoClassDefFoundError: org/grails/datastore/mapping/query/api/BuildableCriteria.

I have also tried using the MongoDB plugin 3.0.3, but with the same results.

答:
This answer https://stackoverflow.com/a/35710495/451420 gave me a clue. I had to update the grails-datastore-core and grails-datastore-gorm versions manually as well:

```<code><dependency>
    <groupId>org.grails</groupId>
    <artifactId>grails-datastore-gorm</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.grails</groupId>
    <artifactId>grails-datastore-core</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
</code>```

In case it helps anyone else, I found out which versions to use by looking at the <dependencies> inside the POM file of the mongodb plugin (https://repo.grails.org/grails/plugins/org/grails/plugins/mongodb/3.0.3/mongodb-3.0.3.pom)

Body:
I am working on a legacy project that uses Grails 2.3.7 (with Maven) and Java 7, and I have to add a connection to a MongoDB database while keeping the existing Hibernate ones.

I have added the following to my pom.xml file:

<dependency>
    <groupId>org.grails.plugins</groupId>
    <artifactId>mongodb</artifactId>
    <type>zip</type>
    <version>3.0.2</version>
</dependency>

And this to the BuildConfig.groovy file:

plugins {
    compile ':mongodb:3.0.2'
    compile 'org.grails.plugins:mongodb:3.0.2'
}

(I have tried it both with and without the compile 'org.grails.plugins:mongodb:3.0.2' line)

On the DataSource.groovy file I have configured the db connection as follows:

grails {
    mongodb {
        host = "xxx.xxx.xxx.xxx"
        port = "27017"
        databaseName = "db"
        username = "user"
        password = "pass"
    }
}

and the connection itself seems to be working, because if I change any value in there the Grails application does not even start.

I have then created a simple Domain class, Thingy.groovy:

class Thingy {

    String identifier
    String description

    static mapWith = "mongo"

    static constraints = {
    }
}

And now, when I start the app, any call to methods of that class throws an IllegalStateException: "Method on class [Thingy] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.". However, if at the same place I call any methods of the old Domain classes that use the other datasource, they work like a charm.

Also, when starting the server I get another exception which I guess might be related, but I'm not sure what to do with it either: ERROR - Error configuring dynamic methods for plugin [mongodb:3.0.2]: org/grails/datastore/mapping/query/api/BuildableCriteria
java.lang.NoClassDefFoundError: org/grails/datastore/mapping/query/api/BuildableCriteria.

I have also tried using the MongoDB plugin 3.0.3, but with the same results.

Body:
This answer https://stackoverflow.com/a/35710495/451420 gave me a clue. I had to update the grails-datastore-core and grails-datastore-gorm versions manually as well:

<dependency>
    <groupId>org.grails</groupId>
    <artifactId>grails-datastore-gorm</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.grails</groupId>
    <artifactId>grails-datastore-core</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>

In case it helps anyone else, I found out which versions to use by looking at the <dependencies> inside the POM file of the mongodb plugin (https://repo.grails.org/grails/plugins/org/grails/plugins/mongodb/3.0.3/mongodb-3.0.3.pom)


问:
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION when ran UDATE statement
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

```<code>update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
</code>```

I added BEGIN TRANSACTION statement, but it still won't work.

```<code>BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION
</code>```

答:
This error states that in SQL Server, you have given a Commit or Commit Transaction without specifying a Begin Transaction or the number of commit transactions is greater than the number of begin transactions. To avoid this make sure you check the existing transactions on the current session before committing.

So a normal Commit Transaction will be updated as below

```<code>IF @@TRANCOUNT>0
COMMIT TRANSACTION
</code>```

Body:
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto

I added BEGIN TRANSACTION statement, but it still won't work.

BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION

Body:
This error states that in SQL Server, you have given a Commit or Commit Transaction without specifying a Begin Transaction or the number of commit transactions is greater than the number of begin transactions. To avoid this make sure you check the existing transactions on the current session before committing.

So a normal Commit Transaction will be updated as below

IF @@TRANCOUNT>0
COMMIT TRANSACTION