问:
Ajax File Upload works with xampp but not on online server
I have 2 HTML pages. One with a form for add a post (in this case i have an input type file), and one with a form for update a post (in this case i haven't an input type file). Both forms have the button with same id to do an ajax call. The PHP file is the same for both the forms, and it insert or update tha data of a post. The js file gets the values of user's input and does the ajax call.

HTML (add post)

```<code><form id="form">
   <input id="titleID" type="text" value="" required />
   <input type="file" id="inputVideo" required />
   <input type="submit" id="submitData" value="SEND DATA" />
</form>
</code>```

HTML (update post. It's another page. So same id it's ok)

```<code><form id="form">
   <input id="titleID" type="text" value="SomeTitleValue" />
   <input type="hidden" id="idHidd" value="SomeIdValue" />
   <input type="submit" id="submitData" value="SEND DATA" />
</form>
</code>```

JS (get input values and do ajax call to php file)

```<code>$(document).ready(function() {
   $(document).on('submit', '#form', function(e) {
      e.preventDefault();

      // get values of inputs and create a formData object
      // if the value is undefined, append in formData a empty string; else append the value

      // Get id
      if ( $('#idHidd').val() != undefined ){
         var id= $('#idHidd').val();
         formData.append('id', id);
      } else {
         var id= ""
         formData.append('id', id);
      }

     // Get file video
     if ( $('#inputVideo')[0] != undefined ){
         var video= $('#inputVideo')[0].files[0]
         formData.append('video', video);
     } else {
         var video =""
         formData.append('video', video);
     }

     // Get title (always present)
     var title= $('#title').val();
     formData.append('title', title);

     // AJAX Call
     $.ajax({
        type: "POST",
        url: "urlToPHP",
        dataType: "JSON",
        processData: false,
        contentType: false,
        cache: false,
        data: formData,
        success: function(msg) {
                    alert(msg)
        }
      });
   });
});
</code>```

PHP

```<code>//include connect db

//Get tite and id
$id= $_POST['id'];
$title= $_POST['title'];

// if there isn't an id, i do an insert and get the video in $_FILES
if ($id == ""){
    $video= $_FILES['video'];

    // DO QUERY FOR INSERT NEW POST AND MOVES THE FILE ON SERVER
}

if ($id != ""){

    // DO QUERY FOR UPDATE A POST
}
</code>```

THE PROBLEM: in local with xampp, everything works. I can insert new post and i can do an update. On online server, it works only the update. When i do an insert, in the log_err i have the message that the indices 'id', 'video', and 'title' are undefined. Like if $_POST and $_FILES were empty. But in the console (with console.log), i can see that the formData object is good, and all the values are appended perfectly with all the indices. Infact, the update works, and the data are the same of an insert, except the file video. Perhaps it's because in the insert there is a input type 'file'? But with xampp it works.
I have also tried to disable mod_security from CPanel. But it doesn't work the same.
does anyone have any solution?

Ps: sorry if code it's not perfect, but i had to do a short version for a better comprension.

答:
Ok i solved my problem.

The problem was the size of the file. I had changed it on xampp , but not on the server.

I thought that a error regarding the size of a file was reported automatically,
without the need of a check. Instead, without a specific check about the size of file, i have only the error of the undefined indices

Body:
I have 2 HTML pages. One with a form for add a post (in this case i have an input type file), and one with a form for update a post (in this case i haven't an input type file). Both forms have the button with same id to do an ajax call. The PHP file is the same for both the forms, and it insert or update tha data of a post. The js file gets the values of user's input and does the ajax call.

HTML (add post)

<form id="form">
   <input id="titleID" type="text" value="" required />
   <input type="file" id="inputVideo" required />
   <input type="submit" id="submitData" value="SEND DATA" />
</form>

HTML (update post. It's another page. So same id it's ok)

<form id="form">
   <input id="titleID" type="text" value="SomeTitleValue" />
   <input type="hidden" id="idHidd" value="SomeIdValue" />
   <input type="submit" id="submitData" value="SEND DATA" />
</form>

JS (get input values and do ajax call to php file)

$(document).ready(function() {
   $(document).on('submit', '#form', function(e) {
      e.preventDefault();

      // get values of inputs and create a formData object
      // if the value is undefined, append in formData a empty string; else append the value

      // Get id
      if ( $('#idHidd').val() != undefined ){
         var id= $('#idHidd').val();
         formData.append('id', id);
      } else {
         var id= ""
         formData.append('id', id);
      }

     // Get file video
     if ( $('#inputVideo')[0] != undefined ){
         var video= $('#inputVideo')[0].files[0]
         formData.append('video', video);
     } else {
         var video =""
         formData.append('video', video);
     }

     // Get title (always present)
     var title= $('#title').val();
     formData.append('title', title);

     // AJAX Call
     $.ajax({
        type: "POST",
        url: "urlToPHP",
        dataType: "JSON",
        processData: false,
        contentType: false,
        cache: false,
        data: formData,
        success: function(msg) {
                    alert(msg)
        }
      });
   });
});

PHP

//include connect db

//Get tite and id
$id= $_POST['id'];
$title= $_POST['title'];

// if there isn't an id, i do an insert and get the video in $_FILES
if ($id == ""){
    $video= $_FILES['video'];

    // DO QUERY FOR INSERT NEW POST AND MOVES THE FILE ON SERVER
}

if ($id != ""){

    // DO QUERY FOR UPDATE A POST
}

THE PROBLEM: in local with xampp, everything works. I can insert new post and i can do an update. On online server, it works only the update. When i do an insert, in the log_err i have the message that the indices 'id', 'video', and 'title' are undefined. Like if $_POST and $_FILES were empty. But in the console (with console.log), i can see that the formData object is good, and all the values are appended perfectly with all the indices. Infact, the update works, and the data are the same of an insert, except the file video. Perhaps it's because in the insert there is a input type 'file'? But with xampp it works.
I have also tried to disable mod_security from CPanel. But it doesn't work the same.
does anyone have any solution?

Ps: sorry if code it's not perfect, but i had to do a short version for a better comprension.


来源: stackexchange

问:
Close and restart the current application in DELPHI
How can I do this one?

For some reason or selected by the user, “ask” the current application to restart it self.

答:
There is another way for closing-restarting the application:

Save a scheduled task to a short time after the application closes. This will have to be the VERY LAST thing your application does before exiting (no further data processing, saving, uploading or whatever)

eg.

get the system time first

set the scheduled task some time after this time (scheduled event will have to start your executable)

exit your application (closing the main form or application.terminate will do it)

When your program starts again, it should check for any such scheduled task and remove them. This must be the VERY FIRST action your application should do when starting. (cleanup)

check for any scheduled tasks created by your executable

remove them

AFAIK, The Delphi Jedi component set has a component you can do the task scheduling stuff with.

ContentLicense: CC BY-SA 3.0


问:
Column does not allow DBNull.Value and Remove does not help. Why?
I am getting the error:

Column 'Code' does not allow DBNull.Value

Here is my code:

```<code>public async Task UpdateDBWithXML(XmlReader reader, string hashKey, string hash)
        {
            var table = new DataTable();
            table.Columns.Add("Code");
            table.Columns.Add("ShortName");
            table.Columns.Add("Name");
            table.Columns.Add("LegalAddress");
            table.Columns.Add("Status");

            using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
            using (var sqlBulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, transaction.UnderlyingTransaction as SqlTransaction))
            {
                this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractors]");

                sqlBulk.DestinationTableName = "LegalContractors";

                string lastElement = null;
                DataRow lastRow = null;
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if(reader.Name == "RECORD")
                            {
                                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                                {
                                    table.Rows.Remove(lastRow);
                                }
                                if (table.Rows.Count > 10000)
                                {
                                    await sqlBulk.WriteToServerAsync(table);
                                    table.Rows.Clear();
                                }

                                lastRow = table.Rows.Add();
                            }
                            lastElement = reader.Name;
                            break;
                        case XmlNodeType.Text:
                            ProcessList(lastElement, reader.Value, lastRow);
                            break;
                    }
                }

                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                {
                    table.Rows.Remove(lastRow);
                }
                if (table.Rows.Count > 0)
                {
                    await sqlBulk.WriteToServerAsync(table);
                    table.Rows.Clear();
                }

                //update hash here

                transaction.Commit();
            }
        }

        private void ProcessList(string lastElement, string value, DataRow row)
        {
            switch (lastElement)
            {
                case "NAME":
                    row["Name"] = value;
                    break;

                case "SHORT_NAME":
                    row["ShortName"] = value;
                    break;

                case "EDRPOU":
                    row["Code"] = value;
                    break;

                case "ADDRESS":
                    row["LegalAddress"] = value;
                    break;

                case "STAN":
                    row["Status"] = value;
                    break;
            }
        }
</code>```

As you can see I am removing the DataRows with the empty 'Code'. Why may the error happen then? Should I use a different API for the deletion?

I tried the approach suggested in this question: use the lastRow["Code"] == DBNull.Value instead of the lastRow.IsNull("Code"). That did not help as well.

Here is the sample XML I am parsing:

```<code><?xml version="1.0" encoding="windows-1251"?>
<DATA FORMAT_VERSION="1.0">
    <RECORD>
        <NAME>МІЖНАРОДНА ГРОМАДСЬКА ОРГАНІЗАЦІЯ МІЖНАРОДНА АКАДЕМІЯ БІОЕНЕРГОТЕХНОЛОГІЙ</NAME>
        <SHORT_NAME>МАБЕТ</SHORT_NAME>
        <EDRPOU>00011601</EDRPOU>
        <ADDRESS>01001, м.Київ, Шевченківський район, ВУЛИЦЯ ПРОРІЗНА, будинок 8, офіс 426</ADDRESS>
        <BOSS>ТКАЧЕНКО ВОЛОДИМИР АНДРІЙОВИЧ</BOSS>
        <KVED>94.12 Діяльність професійних громадських організацій</KVED>
        <STAN>зареєстровано</STAN>
        <FOUNDERS>
            <FOUNDER>Члени організації, розмір внеску до статутного фонду - 0.00 грн.</FOUNDER>
        </FOUNDERS>
    </RECORD>
    <RECORD>
        <NAME>фоо</NAME>
        <SHORT_NAME>фоо короткое имя</SHORT_NAME>
        <EDRPOU></EDRPOU>
        <ADDRESS>фоо адрес</ADDRESS>
        <BOSS>фоо бос</BOSS>
        <KVED>фоо квед</KVED>
        <STAN>фоо состояние</STAN>
        <FOUNDERS>
            <FOUNDER>фоо организатор</FOUNDER>
        </FOUNDERS>
    </RECORD>
</DATA>
</code>```

答:
You can allow DBNull to your column code by creating a new DataColumn:

```<code>DataTable table = new DataTable();
DataColumn code = new DataColumn("code");
code.AllowDBNull = true;
table.Columns.Add(code);
</code>```

I hope that will help you out.

ContentLicense: CC BY-SA 4.0

Body:
I am getting the error:

Column 'Code' does not allow DBNull.Value

Here is my code:

public async Task UpdateDBWithXML(XmlReader reader, string hashKey, string hash)
        {
            var table = new DataTable();
            table.Columns.Add("Code");
            table.Columns.Add("ShortName");
            table.Columns.Add("Name");
            table.Columns.Add("LegalAddress");
            table.Columns.Add("Status");

            using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
            using (var sqlBulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, transaction.UnderlyingTransaction as SqlTransaction))
            {
                this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractors]");

                sqlBulk.DestinationTableName = "LegalContractors";

                string lastElement = null;
                DataRow lastRow = null;
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if(reader.Name == "RECORD")
                            {
                                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                                {
                                    table.Rows.Remove(lastRow);
                                }
                                if (table.Rows.Count > 10000)
                                {
                                    await sqlBulk.WriteToServerAsync(table);
                                    table.Rows.Clear();
                                }

                                lastRow = table.Rows.Add();
                            }
                            lastElement = reader.Name;
                            break;
                        case XmlNodeType.Text:
                            ProcessList(lastElement, reader.Value, lastRow);
                            break;
                    }
                }

                if (table.Rows.Count > 0 && lastRow.IsNull("Code"))
                {
                    table.Rows.Remove(lastRow);
                }
                if (table.Rows.Count > 0)
                {
                    await sqlBulk.WriteToServerAsync(table);
                    table.Rows.Clear();
                }

                //update hash here

                transaction.Commit();
            }
        }

        private void ProcessList(string lastElement, string value, DataRow row)
        {
            switch (lastElement)
            {
                case "NAME":
                    row["Name"] = value;
                    break;

                case "SHORT_NAME":
                    row["ShortName"] = value;
                    break;

                case "EDRPOU":
                    row["Code"] = value;
                    break;

                case "ADDRESS":
                    row["LegalAddress"] = value;
                    break;

                case "STAN":
                    row["Status"] = value;
                    break;
            }
        }

As you can see I am removing the DataRows with the empty 'Code'. Why may the error happen then? Should I use a different API for the deletion?

I tried the approach suggested in this question: use the lastRow["Code"] == DBNull.Value instead of the lastRow.IsNull("Code"). That did not help as well.

Here is the sample XML I am parsing:

<?xml version="1.0" encoding="windows-1251"?>
<DATA FORMAT_VERSION="1.0">
    <RECORD>
        <NAME>МІЖНАРОДНА ГРОМАДСЬКА ОРГАНІЗАЦІЯ МІЖНАРОДНА АКАДЕМІЯ БІОЕНЕРГОТЕХНОЛОГІЙ</NAME>
        <SHORT_NAME>МАБЕТ</SHORT_NAME>
        <EDRPOU>00011601</EDRPOU>
        <ADDRESS>01001, м.Київ, Шевченківський район, ВУЛИЦЯ ПРОРІЗНА, будинок 8, офіс 426</ADDRESS>
        <BOSS>ТКАЧЕНКО ВОЛОДИМИР АНДРІЙОВИЧ</BOSS>
        <KVED>94.12 Діяльність професійних громадських організацій</KVED>
        <STAN>зареєстровано</STAN>
        <FOUNDERS>
            <FOUNDER>Члени організації, розмір внеску до статутного фонду - 0.00 грн.</FOUNDER>
        </FOUNDERS>
    </RECORD>
    <RECORD>
        <NAME>фоо</NAME>
        <SHORT_NAME>фоо короткое имя</SHORT_NAME>
        <EDRPOU></EDRPOU>
        <ADDRESS>фоо адрес</ADDRESS>
        <BOSS>фоо бос</BOSS>
        <KVED>фоо квед</KVED>
        <STAN>фоо состояние</STAN>
        <FOUNDERS>
            <FOUNDER>фоо организатор</FOUNDER>
        </FOUNDERS>
    </RECORD>
</DATA>

Body:
You can allow DBNull to your column code by creating a new DataColumn:

DataTable table = new DataTable();
DataColumn code = new DataColumn("code");
code.AllowDBNull = true;
table.Columns.Add(code);

I hope that will help you out.


问:
c# 8.0 switch expression return type and null value
I'm trying to understand how C# 8.0 switch expressions work and have got several questions.

Why is it not possible to use null value in the default case? The compiler throws Cannot convert null to 'int' because it is a non-nullable value type error.

Why is it trying to convert the null value to int whereas the function's return type is 'double?'?

Here is the function I'm playing with:

```<code>public static double? SwitchFunction(int x) =>
    x switch
    {
        1 => 1,
        _ => null
    };
</code>```

答:
I faced the same problem resulting in a different error message: "No best type was found for the switch expression".

```<code>var isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };
</code>```

I couldn't understand this error message until I read the answers here. The compiler cannot figure out what the type of isRequired should be. My intention was bool?. Changing the code to this makes the error message disappear:

```<code>var isRequired = someIntValue switch
    {
      0 => (bool?)null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };
</code>```

On the other hand, I could just tell the compiler what I want:

```<code>bool? isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };
</code>```

I read on GitHub that they intend to fix this in a future version.

Body:
I'm trying to understand how C# 8.0 switch expressions work and have got several questions.

Why is it not possible to use null value in the default case? The compiler throws Cannot convert null to 'int' because it is a non-nullable value type error.

Why is it trying to convert the null value to int whereas the function's return type is 'double?'?

Here is the function I'm playing with:

public static double? SwitchFunction(int x) =>
    x switch
    {
        1 => 1,
        _ => null
    };

Body:
I faced the same problem resulting in a different error message: "No best type was found for the switch expression".

var isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

I couldn't understand this error message until I read the answers here. The compiler cannot figure out what the type of isRequired should be. My intention was bool?. Changing the code to this makes the error message disappear:

var isRequired = someIntValue switch
    {
      0 => (bool?)null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

On the other hand, I could just tell the compiler what I want:

bool? isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

I read on GitHub that they intend to fix this in a future version.


问:
React React setState not updating on First attempt
I have to show conditionally a div on the same class components. But the state changes updates only from second click.

this is my code

```<code> constructor(props) {
    super(props);
    this.state = {
        openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
}
</code>```

setState

```<code>    handleOpenSignIn() {
       this.setState({ openSignIn: true });
    }
</code>```

and i have to show an element if 'openSignIn' is true

```<code><button className="nav-link px-4 border rounded-sm whiteBtn" onClick={() => this.handleOpenSignIn()}>Login</button>

{this.state.openSignIn &&
    <div>Show</div>
}
</code>```

The div showing only click two times on the button.
am very new in React js.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState({
      openSignIn: true
    });
  }

  render() {
    return (

        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn &&
Show
}

    );
  }
}

 ReactDOM.render(<App/>, document.getElementById('root'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" /></code>```

答:
```<code>
import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState(prevState => ({
      openSignIn: !prevState.openSignIn
    }));
  }

  render() {
    return (
      <div>
        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn && <div>Show</div>}
      </div>
    );
  }
}
</code>```

If you want to toggle instead of just show you can use the above code.
You should not change the boolean state as you are doing in your snippet.

Body:
I have to show conditionally a div on the same class components. But the state changes updates only from second click.

this is my code

 constructor(props) {
    super(props);
    this.state = {
        openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
}

setState

    handleOpenSignIn() {
       this.setState({ openSignIn: true });
    }

and i have to show an element if 'openSignIn' is true

<button className="nav-link px-4 border rounded-sm whiteBtn" onClick={() => this.handleOpenSignIn()}>Login</button>

{this.state.openSignIn &&

Show

}

The div showing only click two times on the button.
am very new in React js.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState({
      openSignIn: true
    });
  }

  render() {
    return (

        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn &&
Show
}

    );
  }
}

 ReactDOM.render(<App/>, document.getElementById('root'))

Body:
import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState(prevState => ({
      openSignIn: !prevState.openSignIn
    }));
  }

  render() {
    return (
      <div>
        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn && <div>Show</div>}
      </div>
    );
  }
}

If you want to toggle instead of just show you can use the above code.
You should not change the boolean state as you are doing in your snippet.


问:
Load data of infinite grid dynamically
I have created an infinite grid using Extjs 6.7. In which, records are getting loaded from the store proxy. How can it be done dynamically using Ajax calls?

Also, have to display the count of loaded records and total records.
Something like 5 of 100.

I have tried store.count() but it's returning total count so how to fetch loaded records.

store.getData().getCount() returns the count but it doesnt changes after 8-9 iterations, seems data is getting overridden in buffered store.

```<code>Ext.application({
    name : 'Fiddle',

    launch : function() {
        var store = Ext.create('Ext.data.BufferedStore', {

            fields: [
                'firstName', 'lastName',
                {
                    name: 'id',
                    type: 'int'
                }],

            leadingBufferZone: 5,
            pageSize: 1,
            remoteSort: true,
            autoLoad: false,
            proxy: {
                type: 'ajax',
                url: 'https://llbzr8dkzl.execute-api.us-east-1.amazonaws.com/production/user',
                reader: {
                    rootProperty: 'users',
                    totalProperty: 'totalCount'
                }
            }
        });

        Ext.create('Ext.grid.Panel', {

            renderTo:Ext.getBody(),
            id: 'myGrid',
            title: 'Infinite Grid',
            width: 650,
            height: 500,
            store: store,
            scrollable: true,
            features: {
                ftype: 'grouping'
            },
            plugins: {
                gridfilters: true
            },

            columns: {
                defaults: {
                    filter: {
                        type: 'string'
                    }
                },
                items: [{
                    text: 'First Name',
                    width: 150,
                    dataIndex: 'firstName'
                }, {
                    text: 'Last Name',
                    width: 150,
                    dataIndex: 'lastName'
                }, {
                    text: 'Id',
                    width: 50,
                    dataIndex: 'id',
                    filter: {
                        type: 'number'
                    }
                } ]
            }
        });
    }
});
</code>```

Any hints or examples please. The fiddle is available here.

答:
You can get the number of records something like this:

```<code>store.getData().length
</code>```

but the problem is that previously downloaded data is deleted (~ 250 items in my example)

Don't understand why getCount return total count

fiddle

Title: Load data of infinite grid dynamically

Body:
I have created an infinite grid using Extjs 6.7. In which, records are getting loaded from the store proxy. How can it be done dynamically using Ajax calls?

Also, have to display the count of loaded records and total records.
Something like 5 of 100.

I have tried store.count() but it's returning total count so how to fetch loaded records.

store.getData().getCount() returns the count but it doesnt changes after 8-9 iterations, seems data is getting overridden in buffered store.

Ext.application({
    name : 'Fiddle',

    launch : function() {
        var store = Ext.create('Ext.data.BufferedStore', {

            fields: [
                'firstName', 'lastName',
                {
                    name: 'id',
                    type: 'int'
                }],

            leadingBufferZone: 5,
            pageSize: 1,
            remoteSort: true,
            autoLoad: false,
            proxy: {
                type: 'ajax',
                url: 'https://llbzr8dkzl.execute-api.us-east-1.amazonaws.com/production/user',
                reader: {
                    rootProperty: 'users',
                    totalProperty: 'totalCount'
                }
            }
        });

        Ext.create('Ext.grid.Panel', {

            renderTo:Ext.getBody(),
            id: 'myGrid',
            title: 'Infinite Grid',
            width: 650,
            height: 500,
            store: store,
            scrollable: true,
            features: {
                ftype: 'grouping'
            },
            plugins: {
                gridfilters: true
            },

            columns: {
                defaults: {
                    filter: {
                        type: 'string'
                    }
                },
                items: [{
                    text: 'First Name',
                    width: 150,
                    dataIndex: 'firstName'
                }, {
                    text: 'Last Name',
                    width: 150,
                    dataIndex: 'lastName'
                }, {
                    text: 'Id',
                    width: 50,
                    dataIndex: 'id',
                    filter: {
                        type: 'number'
                    }
                } ]
            }
        });
    }
});

Any hints or examples please. The fiddle is available here.

Body:
You can get the number of records something like this:

store.getData().length

but the problem is that previously downloaded data is deleted (~ 250 items in my example)

Don't understand why getCount return total count

fiddle


问:
While practicing streamBuilder , an Error appeared
i tried firestore

I wrapped the code in a streambuilder to give the Raised Button a doc

but I got the error

type 'MappedListIterable<DocumentSnapshot, Widget>' is not a subtype of type 'List'

I want the textformfield of the updatepage not to be blank, but to load the stored data.

How can I solve this?

I dont Know what should i do

This is the UPDATE page of the CRUD.

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Update extends StatefulWidget {
  @override
  _UpdateState createState() => _UpdateState();
}

class _UpdateState extends State<Update> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController _titleController = TextEditingController();
  TextEditingController _descController = TextEditingController();
  final db = Firestore.instance;
  DocumentSnapshot _currentDocument;

  _updateData() async {
    await db
        .collection('flutter_data2')
        .document(_currentDocument.documentID)
        .updateData({'title': _titleController.text});
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    return MaterialApp(
        home: Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
              title: Text('update'),
            ),
            body: _buildUpdate(context)));
  }

  // I wrapped the code in a streambuilder to give the RaisedButton a doc
  Widget _buildUpdate(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    //It consists of two textfields and raisedbuttons.
    return StreamBuilder<QuerySnapshot>(
      stream: db.collection('flutter_data2').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Column(
            children: snapshot.data.documents.map<Widget>((doc) {
              return Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(20.0),
                    child: Card(
                      elevation: 2.0,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16.0)),
                      child: Form(
                        key: _formKey,
                        child: Padding(
                          padding: EdgeInsets.only(left: 12, right: 12),
                          child: Column(
                            children: <Widget>[
                              TextFormField(
                                controller: _titleController,
                                decoration: InputDecoration(labelText: 'title'),
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'title empty';
                                  } else {
                                    return null;
                                  }
                                },
                              ),
                              TextFormField(
                                controller: _titleController,
                                decoration: InputDecoration(labelText: 'desc'),
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'desc empty';
                                  } else {
                                    return null;
                                  }
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15.0)),
                    child: Text('update'),
                    color: Colors.blue,
                    onPressed: () async {
                      if (_formKey.currentState.validate()) {
                        _updateData();
                        _titleController.text = doc.data[
                            'title']; //To write this code, I covered everything with a streambuilder.

                      }
                    },
                  ),
                ],
              );
            }),
          );
        } else {
          return SizedBox();
        }
      },
    );
  }
}

</code>```

答:
You have to add toList() after mapping the documents.

Another way to deal with this is to use collection for :

```<code>children: [
    for (final doc in snapshot.data.documents)
        Column(
            ...
        )
]
</code>```

Body:
i tried firestore

I wrapped the code in a streambuilder to give the Raised Button a doc

but I got the error

type 'MappedListIterable<DocumentSnapshot, Widget>' is not a subtype of type 'List'

I want the textformfield of the updatepage not to be blank, but to load the stored data.

How can I solve this?

I dont Know what should i do

This is the UPDATE page of the CRUD.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Update extends StatefulWidget {
  @override
  _UpdateState createState() => _UpdateState();
}

class _UpdateState extends State<Update> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController _titleController = TextEditingController();
  TextEditingController _descController = TextEditingController();
  final db = Firestore.instance;
  DocumentSnapshot _currentDocument;

  _updateData() async {
    await db
        .collection('flutter_data2')
        .document(_currentDocument.documentID)
        .updateData({'title': _titleController.text});
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    return MaterialApp(
        home: Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
              title: Text('update'),
            ),
            body: _buildUpdate(context)));
  }

  // I wrapped the code in a streambuilder to give the RaisedButton a doc
  Widget _buildUpdate(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    //It consists of two textfields and raisedbuttons.
    return StreamBuilder<QuerySnapshot>(
      stream: db.collection('flutter_data2').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Column(
            children: snapshot.data.documents.map<Widget>((doc) {
              return Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(20.0),
                    child: Card(
                      elevation: 2.0,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16.0)),
                      child: Form(
                        key: _formKey,
                        child: Padding(
                          padding: EdgeInsets.only(left: 12, right: 12),
                          child: Column(
                            children: <Widget>[
                              TextFormField(
                                controller: _titleController,
                                decoration: InputDecoration(labelText: 'title'),
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'title empty';
                                  } else {
                                    return null;
                                  }
                                },
                              ),
                              TextFormField(
                                controller: _titleController,
                                decoration: InputDecoration(labelText: 'desc'),
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'desc empty';
                                  } else {
                                    return null;
                                  }
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15.0)),
                    child: Text('update'),
                    color: Colors.blue,
                    onPressed: () async {
                      if (_formKey.currentState.validate()) {
                        _updateData();
                        _titleController.text = doc.data[
                            'title']; //To write this code, I covered everything with a streambuilder.

                      }
                    },
                  ),
                ],
              );
            }),
          );
        } else {
          return SizedBox();
        }
      },
    );
  }
}

Body:
You have to add toList() after mapping the documents.

Another way to deal with this is to use collection for :

children: [
    for (final doc in snapshot.data.documents)
        Column(
            ...
        )
]


问:
SQL change query issue
Executing the below query is giving me error.

I'm trying to re-name a column name.

```<code>alter table student change dateofbirth dob;
</code>```

the above query is giving error

incorrect syntax change

I'm using SQL Server 2016

答:
In SQL Server, you cannot use the alter table syntax to rename a column. You can use sp_rename instead:

```<code>EXEC sp_rename 'student .dateofbirth', 'dob', 'COLUMN';
</code>```

Title: SQL change query issue

Body:
Executing the below query is giving me error.

I'm trying to re-name a column name.

alter table student change dateofbirth dob;

the above query is giving error

incorrect syntax change

I'm using SQL Server 2016

Body:
In SQL Server, you cannot use the alter table syntax to rename a column. You can use sp_rename instead:

EXEC sp_rename 'student .dateofbirth', 'dob', 'COLUMN';


问:
Retrieving string from html on non-unique table
Here is the html I am trying to parse.

```<code><TD>Serial Number</TD><TD>AB12345678</TD>
</code>```

I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have ID numbers. The closest they have to unique identifiers is the data in the cell before the data I need.

```<code>serialNumber = re.search("Serial Number</td><td>\n(.*?)</td>", source)
</code>```

Source is simply the source code of the page grabbed using urllib. There is new line in the html between the second  and the serial number but I am unsure if that matters.

答:
In most of the cases it is better to work on html using an appropriate parser, but for some cases it is perfectly OK to use regular expressions for the job. I do not know enough about your task to judge if it is a good solution or if it is better to go with @Paul 's solution, but here I try to fix your regex:

```<code>serialNumber = re.search("Serial Number</td><td>(.*?)</td>", source, re.S | re.I )
</code>```

I removed the \n, because it is difficult in my opinion (\n,\r,\r\n, ...?), instead I used the option re.S (Dotall).

But be aware, now if there is a newline, it will be in your capturing group! i.e. you should strip whitespaces afterwards from your result.

Another problem of your regex is the  in your string but you search for . There for is the option re.I (IgnoreCase).

You can find more explanations about regex here on docs.python.org

Body:
Here is the html I am trying to parse.

Serial Number	AB12345678

I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have ID numbers. The closest they have to unique identifiers is the data in the cell before the data I need.

serialNumber = re.search("Serial Number	\n(.*?)	", source)

Source is simply the source code of the page grabbed using urllib. There is new line in the html between the second  and the serial number but I am unsure if that matters.

Body:
In most of the cases it is better to work on html using an appropriate parser, but for some cases it is perfectly OK to use regular expressions for the job. I do not know enough about your task to judge if it is a good solution or if it is better to go with @Paul 's solution, but here I try to fix your regex:

serialNumber = re.search("Serial Number</td><td>(.*?)</td>", source, re.S | re.I )

I removed the \n, because it is difficult in my opinion (\n,\r,\r\n, ...?), instead I used the option re.S (Dotall).

But be aware, now if there is a newline, it will be in your capturing group! i.e. you should strip whitespaces afterwards from your result.

Another problem of your regex is the <TD> in your string but you search for <td>. There for is the option re.I (IgnoreCase).

You can find more explanations about regex here on docs.python.org


问:
AWS Lambda Error: "Cannot find module '/var/task/index'"
Node.js Alexa Task Issue

I'm currently coding a Node.js Alexa Task via AWS Lambda, and I have been trying to code a function that receives information from the OpenWeather API and parses it into a variable called weather. The relevant code is as follows:

```<code>var request = require('request');
var weather = "";
function isBadWeather(location) {
      var endpoint = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&APPID=205283d9c9211b776d3580d5de5d6338";
      var body = "";
      request(endpoint, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                  body = JSON.parse(body);
                  weather = body.weather[0].id;
            }
      });
}

function testWeather()
{
      setTimeout(function() {
      if (weather >= 200 && weather < 800)
            weather = true;
      else
            weather = false;
      console.log(weather);
      generateResponse(buildSpeechletResponse(weather, true), {});
      }, 500);
}
</code>```

I ran this snippet countless times in Cloud9 and other IDEs, and it seems to be working flawlessly. However, when I zip it into a package and upload it to AWS Lambda, I get the following error:

```<code>{
    "errorMessage": "Cannot find module '/var/task/index'",
    "errorType": "Error",
    "stackTrace": [
        "Function.Module._load (module.js:276:25)",
        "Module.require (module.js:353:17)",
        "require (internal/module.js:12:17)"
    ]
}
</code>```

I installed module-js, request, and many other Node modules that should make this code run, but nothing seems to fix this issue. Here is my directory, just in case:

```<code>- planyr.zip
   - index.js
   - node_modules
   - package.json
</code>```

Does anyone know what the issue could be?

答: In my case this was caused by Node running out of memory. I fixed that by adding --memory-size 1500 to my aws lambda create-function ... command.

Body:
Node.js Alexa Task Issue

I'm currently coding a Node.js Alexa Task via AWS Lambda, and I have been trying to code a function that receives information from the OpenWeather API and parses it into a variable called weather. The relevant code is as follows:

var request = require('request');
var weather = "";
function isBadWeather(location) {
      var endpoint = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&APPID=205283d9c9211b776d3580d5de5d6338";
      var body = "";
      request(endpoint, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                  body = JSON.parse(body);
                  weather = body.weather[0].id;
            }
      });
}

function testWeather()
{
      setTimeout(function() {
      if (weather >= 200 && weather < 800)
            weather = true;
      else
            weather = false;
      console.log(weather);
      generateResponse(buildSpeechletResponse(weather, true), {});
      }, 500);
}

I ran this snippet countless times in Cloud9 and other IDEs, and it seems to be working flawlessly. However, when I zip it into a package and upload it to AWS Lambda, I get the following error:

{
    "errorMessage": "Cannot find module '/var/task/index'",
    "errorType": "Error",
    "stackTrace": [
        "Function.Module._load (module.js:276:25)",
        "Module.require (module.js:353:17)",
        "require (internal/module.js:12:17)"
    ]
}

I installed module-js, request, and many other Node modules that should make this code run, but nothing seems to fix this issue. Here is my directory, just in case:

- planyr.zip
   - index.js
   - node_modules
   - package.json

Does anyone know what the issue could be?


问:
How do I make truncate log script as dynamic SQL in SQL Server?
I am using the below script to truncate the log files of a database. But I have to execute the below script results in separate window due to this I am not able to schedule the jobs .

```<code>SET NOCOUNT ON

SELECT
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'
</code>```

Expected O/P is script has to run instead of copy pasting the above query results

答:
You can achieve this with Dynamic SQL, without using a cursor:

```<code>SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX) = ''

SELECT @SQL = @SQL +
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY);'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'

PRINT   (@SQL)
EXEC    (@SQL)
</code>```

Does the same thing...

Body:
I am using the below script to truncate the log files of a database. But I have to execute the below script results in separate window due to this I am not able to schedule the jobs .

SET NOCOUNT ON

SELECT
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'

Expected O/P is script has to run instead of copy pasting the above query results

Body:
You can achieve this with Dynamic SQL, without using a cursor:

SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX) = ''

SELECT @SQL = @SQL +
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY);'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'

PRINT   (@SQL)
EXEC    (@SQL)

Does the same thing...


问:
Is it possible to write a read-only property of an enumerator?
Suppose I have a class Seat with an enumerator of type SeatType with the enum values Window, Aisle, and Middle as follows:

```<code>public enum SeatType
{
Window,
Aisle,
Middle
}
</code>```

Is it possible to use an enumerator like a property? I was attempting to make a way to assign a seat object's SeatType usable based on reading another variable as follows, but I am unsure this is the right way to return a seat type SeatType based upon a given seat letter _seatLetter. I was attempting to make it so that if the _seatLetter instance variable of an object is a certain character then the object's enumerator is either Window, Aisle, or Middle.

```<code>public enum Type
{
  get
  {
    if (_seatLetter == 'A' or _seatLetter == 'F')
    {
      return SeatType.Window;
    }
    else if (_seatLetter == 'C' or _seatLetter == 'D')
    {
      return SeatType.Aisle;
    }
    else
    {
      return SeatType.Middle;
    }
  }
}
</code>```

答:
I don't understand your question, but if the name of the property is Type and the return type SeatType it's correct, but you must change a bit the declaration of the property:

```<code>public SeatType Type
{
    get
    {
        if (_seatLetter == 'A' || _seatLetter == 'F')
        {
            return SeatType.Window;
        }
        else if (_seatLetter == 'C' || _seatLetter == 'D')
        {
            return SeatType.Aisle;
        }
        else
        {
            return SeatType.Middle;
        }
    }
}
</code>```

or as switch:

```<code>public SeatType Type
{
    get
    {
        switch (_seatLetter)
        {
            case 'A':
            case 'F':
                return SeatType.Window;
            case 'C':
            case 'D':
                return SeatType.Aisle;
            default:
                return SeatType.Middle;
        }
    }
}
</code>```

Body:
Suppose I have a class Seat with an enumerator of type SeatType with the enum values Window, Aisle, and Middle as follows:

public enum SeatType
{
Window,
Aisle,
Middle
}

Is it possible to use an enumerator like a property? I was attempting to make a way to assign a seat object's SeatType usable based on reading another variable as follows, but I am unsure this is the right way to return a seat type SeatType based upon a given seat letter _seatLetter. I was attempting to make it so that if the _seatLetter instance variable of an object is a certain character then the object's enumerator is either Window, Aisle, or Middle.

public enum Type
{
  get
  {
    if (_seatLetter == 'A' or _seatLetter == 'F')
    {
      return SeatType.Window;
    }
    else if (_seatLetter == 'C' or _seatLetter == 'D')
    {
      return SeatType.Aisle;
    }
    else
    {
      return SeatType.Middle;
    }
  }
}

Body:
I don't understand your question, but if the name of the property is Type and the return type SeatType it's correct, but you must change a bit the declaration of the property:

public SeatType Type
{
    get
    {
        if (_seatLetter == 'A' || _seatLetter == 'F')
        {
            return SeatType.Window;
        }
        else if (_seatLetter == 'C' || _seatLetter == 'D')
        {
            return SeatType.Aisle;
        }
        else
        {
            return SeatType.Middle;
        }
    }
}

or as switch:

public SeatType Type
{
    get
    {
        switch (_seatLetter)
        {
            case 'A':
            case 'F':
                return SeatType.Window;
            case 'C':
            case 'D':
                return SeatType.Aisle;
            default:
                return SeatType.Middle;
        }
    }
}


答:
You need to use sp_rename to rename a column: Rename Columns (Database Engine).

For what you have, it appears you're after:

```<code>EXEC sys.sp_rename N'dbo.student.dateofbirth', N'dob', N'COLUMN';
</code>```

I'm not sure where that syntax you got is from. CHANGE is not a SQL Server keyword; perhaps you were looking at the wrong RDBMS' documentation.

Title: SQL change query issue

Body:
You need to use sp_rename to rename a column: Rename Columns (Database Engine).

For what you have, it appears you're after:

EXEC sys.sp_rename N'dbo.student.dateofbirth', N'dob', N'COLUMN';

I'm not sure where that syntax you got is from. CHANGE is not a SQL Server keyword; perhaps you were looking at the wrong RDBMS' documentation.


问:
Ilias SOAP Constructor error on login
I'm testing the Ilias Soap interface. And I have a problem with the login function.

<?php
include_once ("./nusoap/nusoap.php");
$client = new nusoap_client("https://localhost/ilias/webservice/soap/server.php?wsdl");
$client->soap_defencoding = 'UTF-8'; //that is a not working solution from stackoverflow

if ($err = $client->getError())
{
    echo '
Constructor error
```' . $err . '```';
}

$valid = $client->call('login',
        array('client' => "ILIAS",
            'password' => "pw",
            'username' => "root"));

if ($err = $client->getError())
{
    echo '
Constructor error
```' . $err . '```';
}

print_r($client);
?>
```

<p>I get this error:</p>

<blockquote>
  <p>Constructor error
  SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : Extra content at the end of the document</p>
</blockquote>

<p>And here is the printed object:</p>

<pre class="lang-none prettyprint-override"><code>nusoap_client Object (
    [username] =>
    [password] =>
    [authtype] =>
    [certRequest] => Array ( )
    [requestHeaders] =>
    [responseHeaders] =>
    [responseHeader] =>
    [document] => WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [endpoint] => https://localhost/ilias/webservice/soap/server.php?wsdl
    [forceEndpoint] =>
    [proxyhost] =>
    [proxyport] =>
    [proxyusername] =>
    [proxypassword] =>
    [portName] =>
    [xml_encoding] => UTF-8
    [http_encoding] =>
    [timeout] => 0
    [response_timeout] => 30
    [endpointType] => soap
    [persistentConnection] =>
    [defaultRpcParams] =>
    [request] => POST /ilias/webservice/soap/server.php?wsdl HTTP/1.0 Host: localhost User-Agent: NuSOAP/0.9.5 (1.123) Content-Type: text/xml; charset=UTF-8 SOAPAction: "" Content-Length: 591 ILIASpwroot
    [response] => HTTP/1.1 500 Internal Service Error Date: Thu, 20 Jul 2017 07:33:55 GMT Server: Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31 X-Powered-By: PHP/5.6.31 Content-Length: 462 Connection: close Content-Type: text/xml; charset=utf-8 WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [responseData] => WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [cookies] => Array ( )
    [decode_utf8] => 1
    [operations] => Array ( )
    [curl_options] => Array ( )
    [bindingType] => [use_curl] =>
    [fault] => 1
    [faultcode] => WSDL [faultstring] => SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [faultdetail] =>
    [title] => NuSOAP
    [version] => 0.9.5
    [revision] => $Revision: 1.123 $
    [error_str] => WSDL: SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [debug_str] => 2017-07-20 09:33:55.728354 nusoap_client: ctor wsdl= timeout=0 response_timeout=30 endpoint=string(55) "https://localhost/ilias/webservice/soap/server.php?wsdl" 2017-07-20 09:33:55.728407 nusoap_client: instantiate SOAP with endpoint at https://localhost/ilias/webservice/soap/server.php?wsdl 2017-07-20 09:33:55.728430 nusoap_client: call: operation=login, namespace=http://tempuri.org, soapAction=, rpcParams=, style=rpc, use=encoded, endpointType=soap params=array(3) { ["client"]=> string(5) "ILIAS" ["password"]=> string(2) "pw" ["username"]=> string(4) "root" } headers=bool(false) 2017-07-20 09:33:55.728456 nusoap_client: serializing param array for operation login 2017-07-20 09:33:55.728467 nusoap_client: in serialize_val: name=client, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(5) "ILIAS" attributes=bool(false) 2017-07-20 09:33:55.728484 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728498 nusoap_client: serialize_val returning ILIAS 2017-07-20 09:33:55.728507 nusoap_client: in serialize_val: name=password, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(2) "pw" attributes=bool(false) 2017-07-20 09:33:55.728518 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728528 nusoap_client: serialize_val returning pw 2017-07-20 09:33:55.728536 nusoap_client: in serialize_val: name=username, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(4) "root" attributes=bool(false) 2017-07-20 09:33:55.728546 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728555 nusoap_client: serialize_val returning root 2017-07-20 09:33:55.728563 nusoap_client: wrapping RPC request with encoded method element 2017-07-20 09:33:55.728574 nusoap_client: In serializeEnvelope length=199 body (max 1000 characters)=ILIASpwroot style=rpc use=encoded encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ 2017-07-20 09:33:55.728583 nusoap_client: headers: bool(false) 2017-07-20 09:33:55.728590 nusoap_client: namespaces: array(0) { } 2017-07-20 09:33:55.728607 nusoap_client: endpoint=https://localhost/ilias/webservice/soap/server.php?wsdl, soapAction=, namespace=http://tempuri.org, style=rpc, use=encoded, encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ 2017-07-20 09:33:55.728614 nusoap_client: SOAP message length=591 contents (max 1000 bytes)=ILIASpwroot 2017-07-20 09:33:55.728633 nusoap_client: transporting via HTTP 2017-07-20 09:33:55.728745 nusoap_client: sending message, length=591 2017-07-20 09:33:55.728648 soap_transport_http: ctor url=https://localhost/ilias/webservice/soap/server.php?wsdl use_curl= curl_options: array(0) { } 2017-07-20 09:33:55.728665 soap_transport_http: parsed URL scheme = https 2017-07-20 09:33:55.728673 soap_transport_http: parsed URL host = localhost 2017-07-20 09:33:55.728679 soap_transport_http: parsed URL path = /ilias/webservice/soap/server.php 2017-07-20 09:33:55.728685 soap_transport_http: parsed URL query = wsdl 2017-07-20 09:33:55.728703 soap_transport_http: set header Host: localhost 2017-07-20 09:33:55.728720 soap_transport_http: set header User-Agent: NuSOAP/0.9.5 (1.123) 2017-07-20 09:33:55.728729 soap_transport_http: set header Content-Type: text/xml; charset=UTF-8 2017-07-20 09:33:55.728737 soap_transport_http: set header SOAPAction: "" 2017-07-20 09:33:55.728758 soap_transport_http: entered send() with data of length: 591 2017-07-20 09:33:55.728769 soap_transport_http: connect connection_timeout 0, response_timeout 30, scheme https, host localhost, port 443 2017-07-20 09:33:55.728782 soap_transport_http: connect using cURL 2017-07-20 09:33:55.728817 soap_transport_http: setCurlOption option=10002, value= string(59) "https://localhost:443/ilias/webservice/soap/server.php?wsdl" 2017-07-20 09:33:55.728833 soap_transport_http: setCurlOption option=52, value= int(1) 2017-07-20 09:33:55.728842 soap_transport_http: setCurlOption option=42, value= int(1) 2017-07-20 09:33:55.728851 soap_transport_http: setCurlOption option=19913, value= int(1) 2017-07-20 09:33:55.728859 soap_transport_http: setCurlOption option=13, value= int(30) 2017-07-20 09:33:55.728868 soap_transport_http: set cURL SSL verify options 2017-07-20 09:33:55.728874 soap_transport_http: setCurlOption option=64, value= int(0) 2017-07-20 09:33:55.728883 soap_transport_http: setCurlOption option=81, value= int(0) 2017-07-20 09:33:55.728892 soap_transport_http: cURL connection set up 2017-07-20 09:33:55.728903 soap_transport_http: set header Content-Length: 591 2017-07-20 09:33:55.728910 soap_transport_http: HTTP request: POST /ilias/webservice/soap/server.php?wsdl HTTP/1.0 2017-07-20 09:33:55.728918 soap_transport_http: HTTP header: Host: localhost 2017-07-20 09:33:55.728925 soap_transport_http: HTTP header: User-Agent: NuSOAP/0.9.5 (1.123) 2017-07-20 09:33:55.728931 soap_transport_http: HTTP header: Content-Type: text/xml; charset=UTF-8 2017-07-20 09:33:55.728938 soap_transport_http: HTTP header: SOAPAction: "" 2017-07-20 09:33:55.728946 soap_transport_http: HTTP header: Content-Length: 591 2017-07-20 09:33:55.728957 soap_transport_http: Skip cURL header Host: localhost 2017-07-20 09:33:55.728966 soap_transport_http: Skip cURL header Content-Length: 591 2017-07-20 09:33:55.728972 soap_transport_http: setCurlOption option=10023, value= array(3) { [0]=> string(32) "User-Agent: NuSOAP/0.9.5 (1.123)" [1]=> string(37) "Content-Type: text/xml; charset=UTF-8" [2]=> string(14) "SOAPAction: """ } 2017-07-20 09:33:55.728985 soap_transport_http: set cURL HTTP headers 2017-07-20 09:33:55.728992 soap_transport_http: setCurlOption option=47, value= int(1) 2017-07-20 09:33:55.729001 soap_transport_http: setCurlOption option=10015, value= string(591) "ILIASpwroot" 2017-07-20 09:33:55.729012 soap_transport_http: set cURL POST data 2017-07-20 09:33:55.729019 soap_transport_http: set cURL payload 2017-07-20 09:33:55.729028 soap_transport_http: send and receive with cURL 2017-07-20 09:33:55.774636 soap_transport_http: No cURL error, closing cURL 2017-07-20 09:33:55.774734 soap_transport_http: found proper separation of headers and document 2017-07-20 09:33:55.774754 soap_transport_http: cleaned data, stringlen: 462 2017-07-20 09:33:55.774797 soap_transport_http: No Content-Encoding header 2017-07-20 09:33:55.774811 soap_transport_http: end of send() 2017-07-20 09:33:55.774846 nusoap_client: got response, length=462 type=text/xml; charset=utf-8 2017-07-20 09:33:55.774863 nusoap_client: Entering parseResponse() for data of length 462 headers: array(6) { ["date"]=> string(29) "Thu, 20 Jul 2017 07:33:55 GMT" ["server"]=> string(47) "Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31" ["x-powered-by"]=> string(10) "PHP/5.6.31" ["content-length"]=> string(3) "462" ["connection"]=> string(5) "close" ["content-type"]=> string(23) "text/xml; charset=utf-8" } 2017-07-20 09:33:55.774900 nusoap_client: Got response encoding: utf-8 2017-07-20 09:33:55.774922 nusoap_client: Use encoding: UTF-8 when creating nusoap_parser 2017-07-20 09:33:55.774962 nusoap_parser: Charset from HTTP Content-Type matches encoding from XML declaration 2017-07-20 09:33:55.774978 nusoap_parser: Entering nusoap_parser(), length=462, encoding=UTF-8 2017-07-20 09:33:55.775096 nusoap_parser: found root struct Fault, pos 2 2017-07-20 09:33:55.775182 nusoap_parser: in buildVal() for Fault(pos 2) of type struct 2017-07-20 09:33:55.775196 nusoap_parser: in buildVal, there are children 2017-07-20 09:33:55.775218 nusoap_parser: in buildVal, adding Java Vector or generic compound type Fault 2017-07-20 09:33:55.775246 nusoap_parser: in buildVal, return: array(2) { ["faultcode"]=> &string(4) "WSDL" ["faultstring"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } 2017-07-20 09:33:55.775288 nusoap_parser: in nusoap_parser ctor, message: array(5) { [0]=> array(9) { ["pos"]=> int(0) ["children"]=> string(2) "|1" ["cdata"]=> string(0) "" ["depth"]=> int(0) ["parent"]=> string(0) "" ["status"]=> string(8) "envelope" ["name"]=> string(8) "Envelope" ["attrs"]=> array(1) { ["xmlns:SOAP-ENV"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } [1]=> array(9) { ["pos"]=> int(1) ["children"]=> string(2) "|2" ["cdata"]=> string(0) "" ["depth"]=> int(1) ["parent"]=> int(0) ["status"]=> string(4) "body" ["name"]=> string(4) "Body" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } [2]=> array(11) { ["pos"]=> int(2) ["children"]=> string(4) "|3|4" ["cdata"]=> string(0) "" ["depth"]=> int(2) ["parent"]=> int(1) ["type"]=> string(6) "struct" ["status"]=> string(6) "method" ["name"]=> string(5) "Fault" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> array(2) { ["faultcode"]=> &string(4) "WSDL" ["faultstring"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } } [3]=> array(10) { ["pos"]=> int(3) ["children"]=> string(0) "" ["cdata"]=> string(4) "WSDL" ["depth"]=> int(3) ["parent"]=> int(2) ["status"]=> string(6) "method" ["name"]=> string(9) "faultcode" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> &string(4) "WSDL" } [4]=> array(10) { ["pos"]=> int(4) ["children"]=> string(0) "" ["cdata"]=> string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " ["depth"]=> int(3) ["parent"]=> int(2) ["status"]=> string(6) "method" ["name"]=> string(11) "faultstring" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } } 2017-07-20 09:33:55.775361 nusoap_parser: parsed successfully, found root struct: 2 of name Fault 2017-07-20 09:33:55.775413 nusoap_client: sent message successfully and got a(n) array return=array(2) { ["faultcode"]=> string(4) "WSDL" ["faultstring"]=> string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } 2017-07-20 09:33:55.775437 nusoap_client: got fault 2017-07-20 09:33:55.775452 nusoap_client: faultcode = WSDL
2017-07-20 09:33:55.775463 nusoap_client: faultstring = SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [charencoding] => 1
    [debugLevel] => 9
    [XMLSchemaVersion] => http://www.w3.org/2001/XMLSchema
    [soap_defencoding] => UTF-8
    [namespaces] => Array (
        [SOAP-ENV] => http://schemas.xmlsoap.org/soap/envelope/ [xsd] => http://www.w3.org/2001/XMLSchema
        [xsi] => http://www.w3.org/2001/XMLSchema-instance [SOAP-ENC] => http://schemas.xmlsoap.org/soap/encoding/ )
        [usedNamespaces] => Array ( )
        [typemap] => Array ( [http://www.w3.org/2001/XMLSchema] => Array (
            [string] => string
            [boolean] => boolean
            [float] => double
            [double] => double
            [decimal] => double
            [duration] =>
            [dateTime] => string
            [time] => string
            [date] => string
            [gYearMonth] =>
            [gYear] =>
            [gMonthDay] =>
            [gDay] =>
            [gMonth] =>
            [hexBinary] => string
            [base64Binary] => string
            [anyType] => string
            [anySimpleType] => string
            [normalizedString] => string
            [token] => string
            [language] =>
            [NMTOKEN] =>
            [NMTOKENS] =>
            [Name] =>
            [NCName] =>
            [ID] =>
            [IDREF] =>
            [IDREFS] =>
            [ENTITY] =>
            [ENTITIES] =>
            [integer] => integer
            [nonPositiveInteger] => integer
            [negativeInteger] => integer
            [long] => integer
            [int] => integer
            [short] => integer
            [byte] => integer
            [nonNegativeInteger] => integer
            [unsignedLong] =>
            [unsignedInt] =>
            [unsignedShort] =>
            [unsignedByte] =>
            [positiveInteger] =>
        )
        [http://www.w3.org/2000/10/XMLSchema] => Array (
            [i4] =>
            [int] => integer
            [boolean] => boolean
            [string] => string
            [double] => double
            [float] => double
            [dateTime] => string
            [timeInstant] => string
            [base64Binary] => string
            [base64] => string
            [ur-type] => array
        )
        [http://www.w3.org/1999/XMLSchema] => Array (
            [i4] =>
            [int] => integer
            [boolean] => boolean
            [string] => string
            [double] => double
            [float] => double
            [dateTime] => string
            [timeInstant] => string
            [base64Binary] => string
            [base64] => string
            [ur-type] => array
        )
        [http://soapinterop.org/xsd] => Array (
            [SOAPStruct] => struct
        )
        [http://schemas.xmlsoap.org/soap/encoding/] => Array ( [base64] => string [array] => array [Array] => array )
        [http://xml.apache.org/xml-soap] => Array ( [0] => Map ) )
        [xmlEntities] => Array (
            [quot] => "
            [amp] => &
            [lt] => <
            [gt] => >
            [apos] => '
        )
        [operation] => login
        [opData] => Array ( )
        [return] => Array (
            [faultcode] => WSDL
            [faultstring] => SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
        )
    )
</code>```

Any ideas?

答:
Here you can try code below, works for me on ILIAS 5.3.8 with nusoap-0.9.5 library, iirc the one in the project didnt work for me either.</p>

```<code>require_once("./nusoap-0.9.5/lib/nusoap.php");

$wsdlUrl = "http://yourilias/webservice/soap/server.php?wsdl";
$soapClient = new nusoap_client($wsdlUrl, true);
$login["client"] = 'client1';
$login["username"]  = "root";
$login["password"] = "rootPass";
$sessionId = $soapClient->call("login", $login); // call other soap requests using the sessiondId/sid

echo var_dump(lookupUser("John Doe"));

function lookupUser($login)
{
    global $soapClient, $sessionId;
    $user = $soapClient->call("lookupUser", array($sessionId, $login));
    if ($user != 0) {
        return $user;
    }
    return 0;
}
</code>```

Title: Ilias SOAP Constructor error on login

Body:
I'm testing the Ilias Soap interface. And I have a problem with the login function.

<?php
include_once ("./nusoap/nusoap.php");
$client = new nusoap_client("https://localhost/ilias/webservice/soap/server.php?wsdl");
$client->soap_defencoding = 'UTF-8'; //that is a not working solution from stackoverflow

if ($err = $client->getError())
{
    echo '
Constructor error

' . $err . '
';
}

$valid = $client->call('login',
        array('client' => "ILIAS",
            'password' => "pw",
            'username' => "root"));

if ($err = $client->getError())
{
    echo '
Constructor error

' . $err . '
';
}

print_r($client);
?>

I get this error:

Constructor error
  SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : Extra content at the end of the document

And here is the printed object:

nusoap_client Object (
    [username] =>
    [password] =>
    [authtype] =>
    [certRequest] => Array ( )
    [requestHeaders] =>
    [responseHeaders] =>
    [responseHeader] =>
    [document] => WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [endpoint] => https://localhost/ilias/webservice/soap/server.php?wsdl
    [forceEndpoint] =>
    [proxyhost] =>
    [proxyport] =>
    [proxyusername] =>
    [proxypassword] =>
    [portName] =>
    [xml_encoding] => UTF-8
    [http_encoding] =>
    [timeout] => 0
    [response_timeout] => 30
    [endpointType] => soap
    [persistentConnection] =>
    [defaultRpcParams] =>
    [request] => POST /ilias/webservice/soap/server.php?wsdl HTTP/1.0 Host: localhost User-Agent: NuSOAP/0.9.5 (1.123) Content-Type: text/xml; charset=UTF-8 SOAPAction: "" Content-Length: 591 ILIASpwroot
    [response] => HTTP/1.1 500 Internal Service Error Date: Thu, 20 Jul 2017 07:33:55 GMT Server: Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31 X-Powered-By: PHP/5.6.31 Content-Length: 462 Connection: close Content-Type: text/xml; charset=utf-8 WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [responseData] => WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [cookies] => Array ( )
    [decode_utf8] => 1
    [operations] => Array ( )
    [curl_options] => Array ( )
    [bindingType] => [use_curl] =>
    [fault] => 1
    [faultcode] => WSDL [faultstring] => SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [faultdetail] =>
    [title] => NuSOAP
    [version] => 0.9.5
    [revision] => $Revision: 1.123 $
    [error_str] => WSDL: SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [debug_str] => 2017-07-20 09:33:55.728354 nusoap_client: ctor wsdl= timeout=0 response_timeout=30 endpoint=string(55) "https://localhost/ilias/webservice/soap/server.php?wsdl" 2017-07-20 09:33:55.728407 nusoap_client: instantiate SOAP with endpoint at https://localhost/ilias/webservice/soap/server.php?wsdl 2017-07-20 09:33:55.728430 nusoap_client: call: operation=login, namespace=http://tempuri.org, soapAction=, rpcParams=, style=rpc, use=encoded, endpointType=soap params=array(3) { ["client"]=> string(5) "ILIAS" ["password"]=> string(2) "pw" ["username"]=> string(4) "root" } headers=bool(false) 2017-07-20 09:33:55.728456 nusoap_client: serializing param array for operation login 2017-07-20 09:33:55.728467 nusoap_client: in serialize_val: name=client, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(5) "ILIAS" attributes=bool(false) 2017-07-20 09:33:55.728484 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728498 nusoap_client: serialize_val returning ILIAS 2017-07-20 09:33:55.728507 nusoap_client: in serialize_val: name=password, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(2) "pw" attributes=bool(false) 2017-07-20 09:33:55.728518 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728528 nusoap_client: serialize_val returning pw 2017-07-20 09:33:55.728536 nusoap_client: in serialize_val: name=username, type=, name_ns=, type_ns=, use=encoded, soapval= value=string(4) "root" attributes=bool(false) 2017-07-20 09:33:55.728546 nusoap_client: serialize_val: serialize string 2017-07-20 09:33:55.728555 nusoap_client: serialize_val returning root 2017-07-20 09:33:55.728563 nusoap_client: wrapping RPC request with encoded method element 2017-07-20 09:33:55.728574 nusoap_client: In serializeEnvelope length=199 body (max 1000 characters)=ILIASpwroot style=rpc use=encoded encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ 2017-07-20 09:33:55.728583 nusoap_client: headers: bool(false) 2017-07-20 09:33:55.728590 nusoap_client: namespaces: array(0) { } 2017-07-20 09:33:55.728607 nusoap_client: endpoint=https://localhost/ilias/webservice/soap/server.php?wsdl, soapAction=, namespace=http://tempuri.org, style=rpc, use=encoded, encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ 2017-07-20 09:33:55.728614 nusoap_client: SOAP message length=591 contents (max 1000 bytes)=ILIASpwroot 2017-07-20 09:33:55.728633 nusoap_client: transporting via HTTP 2017-07-20 09:33:55.728745 nusoap_client: sending message, length=591 2017-07-20 09:33:55.728648 soap_transport_http: ctor url=https://localhost/ilias/webservice/soap/server.php?wsdl use_curl= curl_options: array(0) { } 2017-07-20 09:33:55.728665 soap_transport_http: parsed URL scheme = https 2017-07-20 09:33:55.728673 soap_transport_http: parsed URL host = localhost 2017-07-20 09:33:55.728679 soap_transport_http: parsed URL path = /ilias/webservice/soap/server.php 2017-07-20 09:33:55.728685 soap_transport_http: parsed URL query = wsdl 2017-07-20 09:33:55.728703 soap_transport_http: set header Host: localhost 2017-07-20 09:33:55.728720 soap_transport_http: set header User-Agent: NuSOAP/0.9.5 (1.123) 2017-07-20 09:33:55.728729 soap_transport_http: set header Content-Type: text/xml; charset=UTF-8 2017-07-20 09:33:55.728737 soap_transport_http: set header SOAPAction: "" 2017-07-20 09:33:55.728758 soap_transport_http: entered send() with data of length: 591 2017-07-20 09:33:55.728769 soap_transport_http: connect connection_timeout 0, response_timeout 30, scheme https, host localhost, port 443 2017-07-20 09:33:55.728782 soap_transport_http: connect using cURL 2017-07-20 09:33:55.728817 soap_transport_http: setCurlOption option=10002, value= string(59) "https://localhost:443/ilias/webservice/soap/server.php?wsdl" 2017-07-20 09:33:55.728833 soap_transport_http: setCurlOption option=52, value= int(1) 2017-07-20 09:33:55.728842 soap_transport_http: setCurlOption option=42, value= int(1) 2017-07-20 09:33:55.728851 soap_transport_http: setCurlOption option=19913, value= int(1) 2017-07-20 09:33:55.728859 soap_transport_http: setCurlOption option=13, value= int(30) 2017-07-20 09:33:55.728868 soap_transport_http: set cURL SSL verify options 2017-07-20 09:33:55.728874 soap_transport_http: setCurlOption option=64, value= int(0) 2017-07-20 09:33:55.728883 soap_transport_http: setCurlOption option=81, value= int(0) 2017-07-20 09:33:55.728892 soap_transport_http: cURL connection set up 2017-07-20 09:33:55.728903 soap_transport_http: set header Content-Length: 591 2017-07-20 09:33:55.728910 soap_transport_http: HTTP request: POST /ilias/webservice/soap/server.php?wsdl HTTP/1.0 2017-07-20 09:33:55.728918 soap_transport_http: HTTP header: Host: localhost 2017-07-20 09:33:55.728925 soap_transport_http: HTTP header: User-Agent: NuSOAP/0.9.5 (1.123) 2017-07-20 09:33:55.728931 soap_transport_http: HTTP header: Content-Type: text/xml; charset=UTF-8 2017-07-20 09:33:55.728938 soap_transport_http: HTTP header: SOAPAction: "" 2017-07-20 09:33:55.728946 soap_transport_http: HTTP header: Content-Length: 591 2017-07-20 09:33:55.728957 soap_transport_http: Skip cURL header Host: localhost 2017-07-20 09:33:55.728966 soap_transport_http: Skip cURL header Content-Length: 591 2017-07-20 09:33:55.728972 soap_transport_http: setCurlOption option=10023, value= array(3) { [0]=> string(32) "User-Agent: NuSOAP/0.9.5 (1.123)" [1]=> string(37) "Content-Type: text/xml; charset=UTF-8" [2]=> string(14) "SOAPAction: """ } 2017-07-20 09:33:55.728985 soap_transport_http: set cURL HTTP headers 2017-07-20 09:33:55.728992 soap_transport_http: setCurlOption option=47, value= int(1) 2017-07-20 09:33:55.729001 soap_transport_http: setCurlOption option=10015, value= string(591) "ILIASpwroot" 2017-07-20 09:33:55.729012 soap_transport_http: set cURL POST data 2017-07-20 09:33:55.729019 soap_transport_http: set cURL payload 2017-07-20 09:33:55.729028 soap_transport_http: send and receive with cURL 2017-07-20 09:33:55.774636 soap_transport_http: No cURL error, closing cURL 2017-07-20 09:33:55.774734 soap_transport_http: found proper separation of headers and document 2017-07-20 09:33:55.774754 soap_transport_http: cleaned data, stringlen: 462 2017-07-20 09:33:55.774797 soap_transport_http: No Content-Encoding header 2017-07-20 09:33:55.774811 soap_transport_http: end of send() 2017-07-20 09:33:55.774846 nusoap_client: got response, length=462 type=text/xml; charset=utf-8 2017-07-20 09:33:55.774863 nusoap_client: Entering parseResponse() for data of length 462 headers: array(6) { ["date"]=> string(29) "Thu, 20 Jul 2017 07:33:55 GMT" ["server"]=> string(47) "Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31" ["x-powered-by"]=> string(10) "PHP/5.6.31" ["content-length"]=> string(3) "462" ["connection"]=> string(5) "close" ["content-type"]=> string(23) "text/xml; charset=utf-8" } 2017-07-20 09:33:55.774900 nusoap_client: Got response encoding: utf-8 2017-07-20 09:33:55.774922 nusoap_client: Use encoding: UTF-8 when creating nusoap_parser 2017-07-20 09:33:55.774962 nusoap_parser: Charset from HTTP Content-Type matches encoding from XML declaration 2017-07-20 09:33:55.774978 nusoap_parser: Entering nusoap_parser(), length=462, encoding=UTF-8 2017-07-20 09:33:55.775096 nusoap_parser: found root struct Fault, pos 2 2017-07-20 09:33:55.775182 nusoap_parser: in buildVal() for Fault(pos 2) of type struct 2017-07-20 09:33:55.775196 nusoap_parser: in buildVal, there are children 2017-07-20 09:33:55.775218 nusoap_parser: in buildVal, adding Java Vector or generic compound type Fault 2017-07-20 09:33:55.775246 nusoap_parser: in buildVal, return: array(2) { ["faultcode"]=> &string(4) "WSDL" ["faultstring"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } 2017-07-20 09:33:55.775288 nusoap_parser: in nusoap_parser ctor, message: array(5) { [0]=> array(9) { ["pos"]=> int(0) ["children"]=> string(2) "|1" ["cdata"]=> string(0) "" ["depth"]=> int(0) ["parent"]=> string(0) "" ["status"]=> string(8) "envelope" ["name"]=> string(8) "Envelope" ["attrs"]=> array(1) { ["xmlns:SOAP-ENV"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } [1]=> array(9) { ["pos"]=> int(1) ["children"]=> string(2) "|2" ["cdata"]=> string(0) "" ["depth"]=> int(1) ["parent"]=> int(0) ["status"]=> string(4) "body" ["name"]=> string(4) "Body" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" } [2]=> array(11) { ["pos"]=> int(2) ["children"]=> string(4) "|3|4" ["cdata"]=> string(0) "" ["depth"]=> int(2) ["parent"]=> int(1) ["type"]=> string(6) "struct" ["status"]=> string(6) "method" ["name"]=> string(5) "Fault" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> array(2) { ["faultcode"]=> &string(4) "WSDL" ["faultstring"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } } [3]=> array(10) { ["pos"]=> int(3) ["children"]=> string(0) "" ["cdata"]=> string(4) "WSDL" ["depth"]=> int(3) ["parent"]=> int(2) ["status"]=> string(6) "method" ["name"]=> string(9) "faultcode" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> &string(4) "WSDL" } [4]=> array(10) { ["pos"]=> int(4) ["children"]=> string(0) "" ["cdata"]=> string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " ["depth"]=> int(3) ["parent"]=> int(2) ["status"]=> string(6) "method" ["name"]=> string(11) "faultstring" ["attrs"]=> array(0) { } ["namespace"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/" ["result"]=> &string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } } 2017-07-20 09:33:55.775361 nusoap_parser: parsed successfully, found root struct: 2 of name Fault 2017-07-20 09:33:55.775413 nusoap_client: sent message successfully and got a(n) array return=array(2) { ["faultcode"]=> string(4) "WSDL" ["faultstring"]=> string(206) "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl" " } 2017-07-20 09:33:55.775437 nusoap_client: got fault 2017-07-20 09:33:55.775452 nusoap_client: faultcode = WSDL
2017-07-20 09:33:55.775463 nusoap_client: faultstring = SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
    [charencoding] => 1
    [debugLevel] => 9
    [XMLSchemaVersion] => http://www.w3.org/2001/XMLSchema
    [soap_defencoding] => UTF-8
    [namespaces] => Array (
        [SOAP-ENV] => http://schemas.xmlsoap.org/soap/envelope/ [xsd] => http://www.w3.org/2001/XMLSchema
        [xsi] => http://www.w3.org/2001/XMLSchema-instance [SOAP-ENC] => http://schemas.xmlsoap.org/soap/encoding/ )
        [usedNamespaces] => Array ( )
        [typemap] => Array ( [http://www.w3.org/2001/XMLSchema] => Array (
            [string] => string
            [boolean] => boolean
            [float] => double
            [double] => double
            [decimal] => double
            [duration] =>
            [dateTime] => string
            [time] => string
            [date] => string
            [gYearMonth] =>
            [gYear] =>
            [gMonthDay] =>
            [gDay] =>
            [gMonth] =>
            [hexBinary] => string
            [base64Binary] => string
            [anyType] => string
            [anySimpleType] => string
            [normalizedString] => string
            [token] => string
            [language] =>
            [NMTOKEN] =>
            [NMTOKENS] =>
            [Name] =>
            [NCName] =>
            [ID] =>
            [IDREF] =>
            [IDREFS] =>
            [ENTITY] =>
            [ENTITIES] =>
            [integer] => integer
            [nonPositiveInteger] => integer
            [negativeInteger] => integer
            [long] => integer
            [int] => integer
            [short] => integer
            [byte] => integer
            [nonNegativeInteger] => integer
            [unsignedLong] =>
            [unsignedInt] =>
            [unsignedShort] =>
            [unsignedByte] =>
            [positiveInteger] =>
        )
        [http://www.w3.org/2000/10/XMLSchema] => Array (
            [i4] =>
            [int] => integer
            [boolean] => boolean
            [string] => string
            [double] => double
            [float] => double
            [dateTime] => string
            [timeInstant] => string
            [base64Binary] => string
            [base64] => string
            [ur-type] => array
        )
        [http://www.w3.org/1999/XMLSchema] => Array (
            [i4] =>
            [int] => integer
            [boolean] => boolean
            [string] => string
            [double] => double
            [float] => double
            [dateTime] => string
            [timeInstant] => string
            [base64Binary] => string
            [base64] => string
            [ur-type] => array
        )
        [http://soapinterop.org/xsd] => Array (
            [SOAPStruct] => struct
        )
        [http://schemas.xmlsoap.org/soap/encoding/] => Array ( [base64] => string [array] => array [Array] => array )
        [http://xml.apache.org/xml-soap] => Array ( [0] => Map ) )
        [xmlEntities] => Array (
            [quot] => "
            [amp] => &
            [lt] => <
            [gt] => >
            [apos] => '
        )
        [operation] => login
        [opData] => Array ( )
        [return] => Array (
            [faultcode] => WSDL
            [faultstring] => SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl' : failed to load external entity "https://localhost/ilias/webservice/soap/nusoapserver.php?wsdl"
        )
    )

Any ideas?

Body:
Here you can try code below, works for me on ILIAS 5.3.8 with nusoap-0.9.5 library, iirc the one in the project didnt work for me either.

require_once("./nusoap-0.9.5/lib/nusoap.php");

$wsdlUrl = "http://yourilias/webservice/soap/server.php?wsdl";
$soapClient = new nusoap_client($wsdlUrl, true);
$login["client"] = 'client1';
$login["username"]  = "root";
$login["password"] = "rootPass";
$sessionId = $soapClient->call("login", $login); // call other soap requests using the sessiondId/sid

echo var_dump(lookupUser("John Doe"));

function lookupUser($login)
{
    global $soapClient, $sessionId;
    $user = $soapClient->call("lookupUser", array($sessionId, $login));
    if ($user != 0) {
        return $user;
    }
    return 0;
}


问:
How to toggle between values in a nested object
I have a React hook I call useToggles that I use for various checkboxes and radio buttons in my app. So far I have been able to get away with something like the following:

```<code>const useToggles = (initialValues = {}) => {
  const [toggleValues, setToggleValues] = useState(initialValues);

  const handleToggle = e => {
    const name = e.currentTarget.attributes.name.value;
    const value = toggleValues[e.currentTarget.attributes.name.value];

    setToggleValues(values => ({ ...values, [name]: !value }));
  };

  return {
    toggleValues,
    setToggleValues,
    handleToggle,
  };
};

export default useToggles;
</code>```

An example checkbox component:

```<code><CheckBox
   checked={toggleValues.gluten || false}
   label="Gluten"
   onChange={handleToggle}
   name="gluten"
 />
</code>```

So although my "toggleValues" object starts off as {}, any time a checkbox is checked, it populates the object. So we might have:

```<code>{
  gluten: true,
  soy: false
}
</code>```

Because there's only one layer to this object, spreading out the values and using [name]: !value to flip the Boolean value will work.

However, this falls apart when there is the need for more organization. On another page, I have several groups of checkboxes, the values of which I will need to group together to populate individual database fields. To handle this, I've added a layer of organization to the checkboxes:

```<code> <CheckBox
      checked={toggleValues.dietType.paleo || ''}
      label="Paleo"
      onChange={handleToggle}
      name="dietType.paleo"
    />
</code>```

We have used this method of organization elsewhere in our app in order to group data, and have parsed the string with dot-object. Example from useFormValues():  dot.str(e.target.name, value, tmp);

This method does not work with useToggles because we rely on previously existing data in the toggleValues object. Using dot-object consistently creates new layers of the object every time you click the checkbox. But I haven't found a way of using [name] to select a second or third level of an object.

To visualize this, what I need to be able to do is take this object and flip the value of paleo to true based on the function receiving the name "dietType.paleo":

```<code>{
    dietType: {
      paleo: true;
    },
    intolerances: {}
  }
</code>```

答:
You can use currying and pass the checkbox group name as parameter to handleToggle:

```<code>const handleToggle = sub => e => {
  const name = e.currentTarget.attributes.name.value;
  if (!sub) setToggleValues({ ...toggleValues, [name]: !toggleValues[name] });
  else {
    const newSub = { ...toggleValues[sub], [name]: !toggleValues[sub][name] };
    setToggleValues({ ...toggleValues, [sub]: newSub });
  }
};
</code>```

Now use onChange={handleToggle()} for the top level and onChange={handleToggle("dietType")} for the paleo checkbox.

Edit:

Another way is to check if the name has a period in it and branch accordingly:

```<code>const handleToggle = e => {
  const name = e.currentTarget.attributes.name.value;
  if (!~name.indexOf("."))
    setToggleValues({ ...toggleValues, [name]: !toggleValues[name] });
  else {
    const [sub, prop] = name.split(".");
    const newSub = { ...toggleValues[sub], [prop]: !toggleValues[sub][prop] };
    setToggleValues({ ...toggleValues, [sub]: newSub });
  }
};
</code>```

This way you can keep your existing JSX 1:1.

Body:
I have a React hook I call useToggles that I use for various checkboxes and radio buttons in my app. So far I have been able to get away with something like the following:

const useToggles = (initialValues = {}) => {
  const [toggleValues, setToggleValues] = useState(initialValues);

  const handleToggle = e => {
    const name = e.currentTarget.attributes.name.value;
    const value = toggleValues[e.currentTarget.attributes.name.value];

    setToggleValues(values => ({ ...values, [name]: !value }));
  };

  return {
    toggleValues,
    setToggleValues,
    handleToggle,
  };
};

export default useToggles;

An example checkbox component:

<CheckBox
   checked={toggleValues.gluten || false}
   label="Gluten"
   onChange={handleToggle}
   name="gluten"
 />

So although my "toggleValues" object starts off as {}, any time a checkbox is checked, it populates the object. So we might have:

{
  gluten: true,
  soy: false
}

Because there's only one layer to this object, spreading out the values and using [name]: !value to flip the Boolean value will work.

However, this falls apart when there is the need for more organization. On another page, I have several groups of checkboxes, the values of which I will need to group together to populate individual database fields. To handle this, I've added a layer of organization to the checkboxes:

 <CheckBox
      checked={toggleValues.dietType.paleo || ''}
      label="Paleo"
      onChange={handleToggle}
      name="dietType.paleo"
    />

We have used this method of organization elsewhere in our app in order to group data, and have parsed the string with dot-object. Example from useFormValues():  dot.str(e.target.name, value, tmp);

This method does not work with useToggles because we rely on previously existing data in the toggleValues object. Using dot-object consistently creates new layers of the object every time you click the checkbox. But I haven't found a way of using [name] to select a second or third level of an object.

To visualize this, what I need to be able to do is take this object and flip the value of paleo to true based on the function receiving the name "dietType.paleo":

{
    dietType: {
      paleo: true;
    },
    intolerances: {}
  }

Body:
You can use currying and pass the checkbox group name as parameter to handleToggle:

const handleToggle = sub => e => {
  const name = e.currentTarget.attributes.name.value;
  if (!sub) setToggleValues({ ...toggleValues, [name]: !toggleValues[name] });
  else {
    const newSub = { ...toggleValues[sub], [name]: !toggleValues[sub][name] };
    setToggleValues({ ...toggleValues, [sub]: newSub });
  }
};

Now use onChange={handleToggle()} for the top level and onChange={handleToggle("dietType")} for the paleo checkbox.

Edit:

Another way is to check if the name has a period in it and branch accordingly:

const handleToggle = e => {
  const name = e.currentTarget.attributes.name.value;
  if (!~name.indexOf("."))
    setToggleValues({ ...toggleValues, [name]: !toggleValues[name] });
  else {
    const [sub, prop] = name.split(".");
    const newSub = { ...toggleValues[sub], [prop]: !toggleValues[sub][prop] };
    setToggleValues({ ...toggleValues, [sub]: newSub });
  }
};

This way you can keep your existing JSX 1:1.