问:
WPF Data binding: Changing items in the binded collection does not update binding source?
I have two classes:

```<code>public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}
</code>```

and

```<code>public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}
</code>```

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

```<code><Window.Resources>

    <!-- Window controller -->
    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...
</code>```

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}
</code>```

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}
</code>```

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

答:
Why do you create a new ObservableCollection<AccountDetail> each time the Phones property is retrieved? Typically the Person class would have a member field of type ObservableCollection<AccountDetail> that would just be returned in the getter for the Phones property, instead of creating a new one each time. You could populate this collection when an instance of Person is constructed, for example.

I don't know if this would fix your problem or not, but it seems like it should help.

Body:
I have two classes:

public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}

and

public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

<Window.Resources>

    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.


来源: stackexchange

问:
How to keep a particular value selected in select tag
Below is my drop down in JSP where in I have to show the year values and these year values are populated when the document is ready, for which I have written JavaScript code.

```<code><table align="center">
    <tr>
        <td>
            <b>Select Year ::</b>
        </td>
        <td>
            <select id='getYear' onchange="yearChanged(this.value);">

            </select>
        </td>
    </tr>
     </table>
</code>```

and the corresponding javascript code that populates the values in it is as follows

```<code>$(document).ready(function() {
    var d = new Date();
    var year = d.getFullYear();

    var select = document.getElementById("getYear");

    for(var i=0 ; i < 8; i++){

        var displayPast10Year = (parseInt(year)) - i;
        var option = document.createElement('option');
        option.text = option.value = displayPast10Year;
        select.add(option, 0);

     }

    select.valueOf(year);
    $("#getYear").val(year);
    yearChanged(year);

});
</code>```

My requirement is that the drop down (i.e select tag) shows the year value as 2016 when the document is ready. How do I do so?

答:
You're setting it to 2017 when you do $("#getYear").val(year);.
If you want it set to 2016, you can either remove that line and add

```<code>if (displayPast10Year === 2016) {
  option.selected = 'selected';
}
</code>```

in your for loop, or you can simply replace it with $("#getYear").val(2016).

Now if you need it to always be current year - 1, replace 2016 with year - 1 in either one of the above solutions.

ContentLicense: CC BY-SA 3.0

Body:
Below is my drop down in JSP where in I have to show the year values and these year values are populated when the document is ready, for which I have written JavaScript code.

            Select Year ::

            <select id='getYear' onchange="yearChanged(this.value);">

            </select>

and the corresponding javascript code that populates the values in it is as follows

$(document).ready(function() {
    var d = new Date();
    var year = d.getFullYear();

    var select = document.getElementById("getYear");

    for(var i=0 ; i < 8; i++){

        var displayPast10Year = (parseInt(year)) - i;
        var option = document.createElement('option');
        option.text = option.value = displayPast10Year;
        select.add(option, 0);

     }

    select.valueOf(year);
    $("#getYear").val(year);
    yearChanged(year);

});

My requirement is that the drop down (i.e select tag) shows the year value as 2016 when the document is ready. How do I do so?

Body:
You're setting it to 2017 when you do $("#getYear").val(year);.
If you want it set to 2016, you can either remove that line and add

if (displayPast10Year === 2016) {
  option.selected = 'selected';
}

in your for loop, or you can simply replace it with $("#getYear").val(2016).

Now if you need it to always be current year - 1, replace 2016 with year - 1 in either one of the above solutions.


问:
How to update array of object in reactjs
I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:

```<code>class App extends React.Component {
constructor() {
super();
this.state = {
  posts: [
    {
      'author': 'Adolf Hitler',
      'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
      'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Iosif Stalin',
      'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Napoleon Bonapard',
      'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Vladimir Putin',
      'img':'http://realnienovosti.com/images/148795554214.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    }
  ]
};
</code>```

And function that is responsible for changing the state:

```<code>showModal () {
 this.setState(do something)
 }
</code>```

答:
You can do it like that:

```<code>showModal () {
  var item = this.state.posts[0];
  item.modalStatus = true;
  this.setState({});
}
</code>```

After that - React will re-render your component according to new state object.

Body:
I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:

class App extends React.Component {
constructor() {
super();
this.state = {
  posts: [
    {
      'author': 'Adolf Hitler',
      'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
      'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Iosif Stalin',
      'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Napoleon Bonapard',
      'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Vladimir Putin',
      'img':'http://realnienovosti.com/images/148795554214.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    }
  ]
};

And function that is responsible for changing the state:

showModal () {
 this.setState(do something)
 }

Body:
You can do it like that:

showModal () {
  var item = this.state.posts[0];
  item.modalStatus = true;
  this.setState({});
}

After that - React will re-render your component according to new state object.


问:
How do you use Active Record Enum Radio Buttons in a form?
In my app, there is a comment section on articles. I'd like the user to have the ability to comment with 3 different options. To activate this, I am using an Active Record Enum.  Please note that the comment sections is nested under the articles.

```<code>resources :articles, only: [:index, :show] do
  resources :comments
end
</code>```

Migration:

```<code>class AddEnumToCommentModel < ActiveRecord::Migration
  def change
    add_column :comments, :post_as, :integer, default: 0
  end
end
</code>```

Comment model:

```<code>enum post_as: %w(username, oneliner, anonymous)
</code>```

I attempted to add this to the content view, but lost. I am guessing I also have to do something in my controller but not sure.

Attempted view :

```<code><%= form_for([@article, @comment]) do |f| %>
  <% if @comment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

      <ul>
      <% @comment.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <h3>Fill in your comment</h3>
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <div class="post_as">
    <h3> Choose how you want to post your comment :</h3>
    <%= f.input :content, post_as: ???, as: :radio %>
  </div>

  <br>

  <div class="actions">
    <%= f.submit %>
  </div>

  <br>
<% end %>
</code>```

答:
An addition to xxyyxx's answer, if you want the labels to be clickable as well:</p>

```<code><% Comment.post_as.keys.each do |post_as| %>
  <%= f.radio_button :post_as, post_as %>
  <%= f.label "#{:post_as}_#{post_as.parameterize.underscore}", post_as %>
<% end %>
</code>```

Body:
In my app, there is a comment section on articles. I'd like the user to have the ability to comment with 3 different options. To activate this, I am using an Active Record Enum.  Please note that the comment sections is nested under the articles.

resources :articles, only: [:index, :show] do
  resources :comments
end

Migration:

class AddEnumToCommentModel < ActiveRecord::Migration
  def change
    add_column :comments, :post_as, :integer, default: 0
  end
end

Comment model:

enum post_as: %w(username, oneliner, anonymous)

I attempted to add this to the content view, but lost. I am guessing I also have to do something in my controller but not sure.

Attempted view :

<%= form_for([@article, @comment]) do |f| %>
  <% if @comment.errors.any? %>

<%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:

      <% @comment.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

Fill in your comment

    <%= f.label :content %>

    <%= f.text_area :content %>

 Choose how you want to post your comment :

    <%= f.input :content, post_as: ???, as: :radio %>

    <%= f.submit %>

<% end %>

Body:
An addition to xxyyxx's answer, if you want the labels to be clickable as well:

<% Comment.post_as.keys.each do |post_as| %>
  <%= f.radio_button :post_as, post_as %>
  <%= f.label "#{:post_as}_#{post_as.parameterize.underscore}", post_as %>
<% end %>


问:
WSO2 identity server and spring security oauth InvalidRequestException: Possible CSRF detected
I'm developing a web application exposing a RESTful service using springboot, spring security as a POC to compare different identity provider products.

Here is the application code

@SpringBootApplication
@RestController
@EnableOAuth2Sso
@EnableZuulProxy
public class GatewayApplication extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

}
```

<p>And this is my cofig yaml file</p>

```security:
    oauth2:
        client:
            accessTokenUri: https://localhost:9443/oauth2/token
            clientAuthenticationScheme: header
            clientId: myClientId
            clientSecret: myClientSecret
            scope: openid
            userAuthorizationUri: https://localhost:9443/oauth2/authorize
            preEstablishedRedirectUri: http://localhost:8081/login
            useCurrentUri: false
        resource:
            userInfoUri: https://localhost:9443/oauth2/userinfo?schema=openid
        sso:
          login-path: /login

server:
    port: 8081
```

<p>I've configured the application as a client in the WSO2-IS to enable oauth2/openId Connect authentication.</p>

<p>The problem is that every time the application tries to obtain the access token I got this exception</p>

<pre class="lang-sh prettyprint-override"><code>org.springframework.security.authentication.BadCredentialsException: Could not obtain access token
    at org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter.attemptAuthentication(OAuth2ClientAuthenticationProcessingFilter.java:107)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.cloud.sleuth.instrument.web.TraceFilter.doFilter(TraceFilter.java:145)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.security.oauth2.common.exceptions.InvalidRequestException: Possible CSRF detected - state parameter was required but no state could be found
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.getParametersForTokenRequest(AuthorizationCodeAccessTokenProvider.java:255)
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:209)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter.attemptAuthentication(OAuth2ClientAuthenticationProcessingFilter.java:105)
    ... 63 common frames omitted
</code>```

I have debugged the authentication flow several times and localized the failure point and the problematic request..

This is the failure point in AuthorizationCodeAccessTokenProvider

```<code>Object preservedState = request.getPreservedState();
// Here preservedState is null but it should be a String with "http://localhost:8081/login"
        if (request.getStateKey() != null || stateMandatory) {

            if (preservedState == null) {
                throw new InvalidRequestException(
                        "Possible CSRF detected - state parameter was required but no state could be found");
            }
        }
</code>```

And this is the request

```<code>Received [GET /login?code=d3ee114c-b4b3-32d5-9633-73b8e01431b8&state=tv7Pc3&session_state=3ff781cd9ac5487405d521ad65b70ffbe42f12135d220feab382d39cf478650e.H_oNKR72M8o50w-t-l8kUw HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]
</code>```

I used this application to test Keycloak and I didn't have this issue. The same request using Keycloak looks like this.

```<code>Received [GET /login?state=5X67Q5&code=vwbYpX_n5SqVHDOI5KDOAmHNgbvwkRneT_i8k7t4v_o.9dc94ecc-aeb8-4f0c-8fa5-ab4d327ecdb0 HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/auth/realms/pocauthapplication/protocol/openid-connect/auth?client_id=zuul_proxy&redirect_uri=http://localhost:8081/login&response_type=code&state=5X67Q5
Cookie: JSESSIONID=0C5F8417267F3DDB8C84F107F6B831B9
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]
</code>```

I think the problem is in the missing Referer header that makes the application thinks that the request could be a forged request.

答:
I've found the reason why the referer header lost when oauth flow backs to my application from the IS.

The main reason is because the WSO2-IS uses https and my application uses plain http. So when the authentication flow chages it's context from https to http referer header is lost.

I proved to disable https on the WSO2-IS and it works.

Here is the request when it backs to my service with https disabled.

```<code>[GET /login?code=70041d7b-9f54-36f8-bf70-f663f73b5441&state=v1JocO&session_state=cf6fe250a8512d7a2100ab5cf1b62d68e070634aa3e5d704746a030a8674f398.p4OxMoMTuIWd-JiBa-x0pQ HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:9443/authenticationendpoint/login.do?client_id=42zjjBHYEwvKTwwtFScNG6P1NJ4a&commonAuthCallerPath=%2Foauth2%2Fauthorize&forceAuth=false&passiveAuth=false&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Flogin&response_type=code&scope=openid&state=v1JocO&tenantDomain=carbon.super&sessionDataKey=1b1ce4f8-b1ad-48d0-9814-e8db0dd84732&relyingParty=42zjjBHYEwvKTwwtFScNG6P1NJ4a&type=oidc&sp=zuul_proxy&isSaaSApp=false&authenticators=BasicAuthenticator:LOCAL
Cookie: JSESSIONID=C028E69ED0DB92DA06BDFCFA852C4ACB
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]
</code>```

Body:
I'm developing a web application exposing a RESTful service using springboot, spring security as a POC to compare different identity provider products.

Here is the application code

@SpringBootApplication
@RestController
@EnableOAuth2Sso
@EnableZuulProxy
public class GatewayApplication extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

}

And this is my cofig yaml file

security:
    oauth2:
        client:
            accessTokenUri: https://localhost:9443/oauth2/token
            clientAuthenticationScheme: header
            clientId: myClientId
            clientSecret: myClientSecret
            scope: openid
            userAuthorizationUri: https://localhost:9443/oauth2/authorize
            preEstablishedRedirectUri: http://localhost:8081/login
            useCurrentUri: false
        resource:
            userInfoUri: https://localhost:9443/oauth2/userinfo?schema=openid
        sso:
          login-path: /login

server:
    port: 8081

I've configured the application as a client in the WSO2-IS to enable oauth2/openId Connect authentication.

The problem is that every time the application tries to obtain the access token I got this exception

org.springframework.security.authentication.BadCredentialsException: Could not obtain access token
    at org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter.attemptAuthentication(OAuth2ClientAuthenticationProcessingFilter.java:107)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.cloud.sleuth.instrument.web.TraceFilter.doFilter(TraceFilter.java:145)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.security.oauth2.common.exceptions.InvalidRequestException: Possible CSRF detected - state parameter was required but no state could be found
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.getParametersForTokenRequest(AuthorizationCodeAccessTokenProvider.java:255)
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:209)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter.attemptAuthentication(OAuth2ClientAuthenticationProcessingFilter.java:105)
    ... 63 common frames omitted

I have debugged the authentication flow several times and localized the failure point and the problematic request..

This is the failure point in AuthorizationCodeAccessTokenProvider

Object preservedState = request.getPreservedState();
// Here preservedState is null but it should be a String with "http://localhost:8081/login"
        if (request.getStateKey() != null || stateMandatory) {

            if (preservedState == null) {
                throw new InvalidRequestException(
                        "Possible CSRF detected - state parameter was required but no state could be found");
            }
        }

And this is the request

Received [GET /login?code=d3ee114c-b4b3-32d5-9633-73b8e01431b8&state=tv7Pc3&session_state=3ff781cd9ac5487405d521ad65b70ffbe42f12135d220feab382d39cf478650e.H_oNKR72M8o50w-t-l8kUw HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]

I used this application to test Keycloak and I didn't have this issue. The same request using Keycloak looks like this.

Received [GET /login?state=5X67Q5&code=vwbYpX_n5SqVHDOI5KDOAmHNgbvwkRneT_i8k7t4v_o.9dc94ecc-aeb8-4f0c-8fa5-ab4d327ecdb0 HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/auth/realms/pocauthapplication/protocol/openid-connect/auth?client_id=zuul_proxy&redirect_uri=http://localhost:8081/login&response_type=code&state=5X67Q5
Cookie: JSESSIONID=0C5F8417267F3DDB8C84F107F6B831B9
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]

I think the problem is in the missing Referer header that makes the application thinks that the request could be a forged request.

Body:
I've found the reason why the referer header lost when oauth flow backs to my application from the IS.

The main reason is because the WSO2-IS uses https and my application uses plain http. So when the authentication flow chages it's context from https to http referer header is lost.

I proved to disable https on the WSO2-IS and it works.

Here is the request when it backs to my service with https disabled.

[GET /login?code=70041d7b-9f54-36f8-bf70-f663f73b5441&state=v1JocO&session_state=cf6fe250a8512d7a2100ab5cf1b62d68e070634aa3e5d704746a030a8674f398.p4OxMoMTuIWd-JiBa-x0pQ HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:9443/authenticationendpoint/login.do?client_id=42zjjBHYEwvKTwwtFScNG6P1NJ4a&commonAuthCallerPath=%2Foauth2%2Fauthorize&forceAuth=false&passiveAuth=false&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Flogin&response_type=code&scope=openid&state=v1JocO&tenantDomain=carbon.super&sessionDataKey=1b1ce4f8-b1ad-48d0-9814-e8db0dd84732&relyingParty=42zjjBHYEwvKTwwtFScNG6P1NJ4a&type=oidc&sp=zuul_proxy&isSaaSApp=false&authenticators=BasicAuthenticator:LOCAL
Cookie: JSESSIONID=C028E69ED0DB92DA06BDFCFA852C4ACB
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1

]


问:
Stream closed after async
I have a ASP.NET core application that need to send a stream(the stream is posted by client) to Microsoft Cognitive Service to get the ID. And then send the same stream to azure blob for backup, the file name should be the ID received from Cognitive Service.

But it seems like the MemoryStream ms closed after used by faceServiceClient : an error accrued at the second "ms.Position = 0" statement saying "Cannot access a closed stream".

```<code>public static async Task CreatPerson(string _key, HttpRequest _req)
{
    var faceServiceClient = new FaceServiceClient(_key);
    using (MemoryStream ms = new MemoryStream())
    {
        _req.Body.CopyTo(ms);
        ms.Position = 0;
        var facesTask = faceServiceClient.AddFaceToFaceListAsync("himlens", ms);
        //init azure blob
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AZURE_STORE_CONN_STR);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("xxx");
        var faces = await facesTask;
        var blob = container.GetBlockBlobReference(faces.PersistedFaceId.ToString());

        ms.Position = 0;//Error Here
        await blob.UploadFromStreamAsync(ms);
    }
}
</code>```

I'm confused about it, can anybody help me solve this problem?

Thanks！

答:
ms.Position = 0;//Error Here

To easily fix it, you could create a new instance of MemoryStream and copy the value from ms. Then you could upload it to your blob storage. Code below is for your reference.

```<code>using (MemoryStream ms = new MemoryStream())
{
    _req.Body.CopyTo(ms);
    ms.Position = 0;
    //new code which I added
    MemoryStream ms2 = new MemoryStream();
    ms.CopyTo(ms2);
    ms.Position = 0;

    var facesTask = faceServiceClient.AddFaceToFaceListAsync("himlens", ms);
    //init azure blob
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AZURE_STORE_CONN_STR);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference("xxx");
    var faces = await facesTask;
    var blob = container.GetBlockBlobReference(faces.PersistedFaceId.ToString());
    //Code which I modified
    ms2.Position = 0;
    await blob.UploadFromStreamAsync(ms2);
}
</code>```

Title: Stream closed after async

Body:
I have a ASP.NET core application that need to send a stream(the stream is posted by client) to Microsoft Cognitive Service to get the ID. And then send the same stream to azure blob for backup, the file name should be the ID received from Cognitive Service.

But it seems like the MemoryStream ms closed after used by faceServiceClient : an error accrued at the second "ms.Position = 0" statement saying "Cannot access a closed stream".

public static async Task CreatPerson(string _key, HttpRequest _req)
{
    var faceServiceClient = new FaceServiceClient(_key);
    using (MemoryStream ms = new MemoryStream())
    {
        _req.Body.CopyTo(ms);
        ms.Position = 0;
        var facesTask = faceServiceClient.AddFaceToFaceListAsync("himlens", ms);
        //init azure blob
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AZURE_STORE_CONN_STR);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("xxx");
        var faces = await facesTask;
        var blob = container.GetBlockBlobReference(faces.PersistedFaceId.ToString());

        ms.Position = 0;//Error Here
        await blob.UploadFromStreamAsync(ms);
    }
}

I'm confused about it, can anybody help me solve this problem?

Thanks！

Body:
ms.Position = 0;//Error Here

To easily fix it, you could create a new instance of MemoryStream and copy the value from ms. Then you could upload it to your blob storage. Code below is for your reference.

using (MemoryStream ms = new MemoryStream())
{
    _req.Body.CopyTo(ms);
    ms.Position = 0;
    //new code which I added
    MemoryStream ms2 = new MemoryStream();
    ms.CopyTo(ms2);
    ms.Position = 0;

    var facesTask = faceServiceClient.AddFaceToFaceListAsync("himlens", ms);
    //init azure blob
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AZURE_STORE_CONN_STR);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference("xxx");
    var faces = await facesTask;
    var blob = container.GetBlockBlobReference(faces.PersistedFaceId.ToString());
    //Code which I modified
    ms2.Position = 0;
    await blob.UploadFromStreamAsync(ms2);
}


问:
How do different languages handle the "dangling else"?
I often see the dangling else handled as:

```<code>if (x > 0)
  if (y > 0)
    print "hello"
else
  print "world"
</code>```

the parser or interpreter will actually match the else with the closest if statement, which is the "if (y > 0)".

Does any language have the pitfall of actually matching the else with the outer if or the farthest if?  (except the obvious Python)

答:
COBOL, prior to the introduction of the END-IF, rules that the ELSE belongs to the nearest IF.

To else some other than the previous, one has to balance the IFs with the same number of ELSEs. Because there must be an imperative a NEXT SENTENCE clause must be added. As any other case[1] in COBOL the choice of solution seems to the most verbose imaginable.

[1]: EVALUATE WHEN OTHERWISE

ContentLicense: CC BY-SA 2.5

Body:
I often see the dangling else handled as:

if (x > 0)
  if (y > 0)
    print "hello"
else
  print "world"

the parser or interpreter will actually match the else with the closest if statement, which is the "if (y > 0)".

Does any language have the pitfall of actually matching the else with the outer if or the farthest if?  (except the obvious Python)


问:
mongorestore from MongoDB to DocumentDB
I am trying to run mongorestore.exe from a DB dump files of collections into DocumentDB database. I have experience with MongoDB and Azure but not much with DocumentDB.

I am getting an error

error parsing command line options: unknown option "ssl"

if I use the command from this tutorial.

I have locally installed MongoDB Community Server, "Windows Server 2008 R2 64-bit and later, with SSL support x64" of the latest stable version - 3.2.4.
It looks like the the --ssl command might not be available since the version 3 (link).

However SSL is enforced by DocumentDB.

Any idea how to migrate an existing database from MongoDB to DocumentDB?The DB is quite large (~GB), hence mongoimport would take too long, we need to user mongorestore, I believe.

Updated, command example:

```<code>mongorestore.exe --host myhost123.documents.azure.com:10250 -u myhost123 -p somepassword== --db myhost123  --ssl --sslAllowInvalidCertificates
</code>```

gives me this error:

error parsing command line options: unknown option "ssl"

If I remove the two ssl options (--ssl --sslAllowInvalidCertificates) I get back an error which kind of makes sense as SSL is enforced on Azure DocumentDB:

Failed: error connecting to db server: no reachable servers

答:
According to your description, I installed MongoDB Community Server Windows Server 2008 R2 64-bit and later, with SSL support x64 -3.4.3 and followed this official tutorial about importing data to API for MongoDB with mongorestore. After some trials, I could restore my local file generated by mongodump to my Azure DocumentDB (MongoDB API) as follows:

Failed: error connecting to db server: no reachable servers

I also encountered this error, and found that it was caused by IP Access Control,
 my current IP is not included as the allowed list of client IP addresses. You could find more details about DocumentDB firewall here.

Title: mongorestore from MongoDB to DocumentDB

Body:
I am trying to run mongorestore.exe from a DB dump files of collections into DocumentDB database. I have experience with MongoDB and Azure but not much with DocumentDB.

I am getting an error

error parsing command line options: unknown option "ssl"

if I use the command from this tutorial.

I have locally installed MongoDB Community Server, "Windows Server 2008 R2 64-bit and later, with SSL support x64" of the latest stable version - 3.2.4.
It looks like the the --ssl command might not be available since the version 3 (link).

However SSL is enforced by DocumentDB.

Any idea how to migrate an existing database from MongoDB to DocumentDB?The DB is quite large (~GB), hence mongoimport would take too long, we need to user mongorestore, I believe.

Updated, command example:

mongorestore.exe --host myhost123.documents.azure.com:10250 -u myhost123 -p somepassword== --db myhost123  --ssl --sslAllowInvalidCertificates

gives me this error:

error parsing command line options: unknown option "ssl"

If I remove the two ssl options (--ssl --sslAllowInvalidCertificates) I get back an error which kind of makes sense as SSL is enforced on Azure DocumentDB:

Failed: error connecting to db server: no reachable servers


问:
writing a Rake task for renaming a field name in a table in a Rails application
I am very new to rails application. I need to change the column name of a table ..
SO i browsed thru some sites and as thy mentioned i thought of writing migration file ..

```<code>  class RenameNameToFirstnameInUsers < ActiveRecord::Migration
    def self.up
      rename_column 'users', 'name', 'first_name'
    end

    def self.down
        rename_column 'users', 'first_name', 'name'
    end
 end
</code>```

How to save this file and where ??

applicationname/db/migrate/

In what name i can save this ??
As far now i have seen many files there but all those have prefix of some big_number

And after saving this , how do i test it in my local??

答:
the easiest way to do this is:

Rails3

rails generate migration RenameNameToFirstnameInUsers

Rails2

script/generate migration RenameNameToFirstnameInUsers

And then edit the created migration file, and migrate your db as normal.

Body:
I am very new to rails application. I need to change the column name of a table ..
SO i browsed thru some sites and as thy mentioned i thought of writing migration file ..

  class RenameNameToFirstnameInUsers < ActiveRecord::Migration
    def self.up
      rename_column 'users', 'name', 'first_name'
    end

    def self.down
        rename_column 'users', 'first_name', 'name'
    end
 end

How to save this file and where ??

applicationname/db/migrate/

In what name i can save this ??
As far now i have seen many files there but all those have prefix of some big_number

And after saving this , how do i test it in my local??


问:
Zigbee simulation in OMNeT++ using INET 3.0 (without MiXiM)
I am trying to build a Zigbee (802.15.4) network simulation in OMNeT++ using INET 3.0 framework (MiXiM was deprecated and replaced by this version ).
The problem is that unlike 802.11, the Zigbee is not fully standardize by its Alliance, so the modules in the framework are not complete nor ready for use.

I searched for an example that uses Zigbee all over the web but found none that uses INET 3.0, I found some that uses the old MiXiM. The INET 3.0 was released a few months ago.

I also tried to build my own Zigbee node but was not very lucky.

Can anyone please guide me to an example of Zigbee simulation in OMNeT++ under the INET 3.0 framework, or at least a node structure?

I forgot to mention that I am a novice to OMNeT++ and to INET.

答:
Within an updated inet 3.x append in the file inet/examples/wireless/nic/omnetpp.ini the following config section:

```<code>[Config IEEE802154]
network = TestNic
extends = AbstractAPSKScalarRadio
*.host[*].wlan[*].typename = "Ieee802154NarrowbandNic"
</code>```

The configured simulation represents a simple narrow-band CSMA/CA based IEEE 802.15.4 network which is related to ZigBee networks.

Then you have to run the configured simulation:

Right-click on the edited omnetpp.ini

Select Run as, then OMNeT++ Simulation

Change to new config IEEE802154

Finally, press ok

Body:
Within an updated inet 3.x append in the file inet/examples/wireless/nic/omnetpp.ini the following config section:

[Config IEEE802154]
network = TestNic
extends = AbstractAPSKScalarRadio
*.host[*].wlan[*].typename = "Ieee802154NarrowbandNic"

The configured simulation represents a simple narrow-band CSMA/CA based IEEE 802.15.4 network which is related to ZigBee networks.

Then you have to run the configured simulation:

Right-click on the edited omnetpp.ini

Select Run as, then OMNeT++ Simulation

Change to new config IEEE802154

Finally, press ok


问:
Correct mysql syntax to change a column with collation
This line of code was generated automatically by phpmyadmin (perhaps an old version running on my company's website, but I don't want to deal with that right now):

```<code>ALTER TABLE `lc_error_logs` CHANGE `OneDetailedMessage` `OneDetailedMessage` VARCHAR(5000) CHARSET=latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL;
</code>```

When attempt to execute that SQL, get error message via phpmyadmin:

Query error:
   #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MYSQL server version for the right syntax to user near '=latin1 COLLATE  latin1_swedish_ci NULL DEFAULT NULL' at line 1.

I don't see what is wrong with the query, and would like to know what is wrong.

Notes:

All I did was change the VARCHAR length.

Works fine if I delete the column, then recreate it with these same settings. Is just something wrong with that ALTER TABLE syntax.

I can change INT columns in the same table (e.g. INT to SMALLINT), without any problems. Something about the COLLATE?  But that is the collate we use throughout this DB.

mysql version:  "5.5.47-0ubuntu0.14.04.1"

It doesn't matter what values I use for VARCHAR length. It doesn't matter what I attempt to change (e.g. changing column name has the same error.) And I've had this problem before on other tables. I've never been able to successfully alter a VARCHAR in this DB, if I specify collation. (Even though this is the default collation for this DB, generated automatically when I do not specify collation.)

答:
```<code>ALTER TABLE `lc_error_logs` CHANGE `OneDetailedMessage` `OneDetailedMessage` VARCHAR(5000) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL;
</code>```

try CHARACTER SET instead of CHARSET=

Body:
This line of code was generated automatically by phpmyadmin (perhaps an old version running on my company's website, but I don't want to deal with that right now):

ALTER TABLE `lc_error_logs` CHANGE `OneDetailedMessage` `OneDetailedMessage` VARCHAR(5000) CHARSET=latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL;

When attempt to execute that SQL, get error message via phpmyadmin:

Query error:
   #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MYSQL server version for the right syntax to user near '=latin1 COLLATE  latin1_swedish_ci NULL DEFAULT NULL' at line 1.

I don't see what is wrong with the query, and would like to know what is wrong.

Notes:

All I did was change the VARCHAR length.

Works fine if I delete the column, then recreate it with these same settings. Is just something wrong with that ALTER TABLE syntax.

I can change INT columns in the same table (e.g. INT to SMALLINT), without any problems. Something about the COLLATE?  But that is the collate we use throughout this DB.

mysql version:  "5.5.47-0ubuntu0.14.04.1"

It doesn't matter what values I use for VARCHAR length. It doesn't matter what I attempt to change (e.g. changing column name has the same error.) And I've had this problem before on other tables. I've never been able to successfully alter a VARCHAR in this DB, if I specify collation. (Even though this is the default collation for this DB, generated automatically when I do not specify collation.)

Body:
ALTER TABLE `lc_error_logs` CHANGE `OneDetailedMessage` `OneDetailedMessage` VARCHAR(5000) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL;

try CHARACTER SET instead of CHARSET=


问:
VARCHAR SQL contains numbers how to get 2 decimals after comma
I'm having some trouble getting the price to show correct on my website. Currently i have a row VerkoopPP40 which is a VARCHAR input. In this row there is a price e.g. 89,5 or just 9. When I try to get these values it does some unexpected things.

**** Update ****

I've just tried this code:

```<code><?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{

    if ($format) {
        $format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
        # Find decimal separator
        # The decimal separator is the one that is the last and does not occur more than once
        if ($letters = str_replace(' ', '', $number)) { # Replace spaces
            if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
                if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
                    $lastletter = substr($letters, -1); # Returns last char
                    if (substr_count($letters, $lastletter) == 1) {
                        if (strpos($oldDecimalSeparator, $lastletter)  !== false)
                            $oldDecimalSep = $lastletter;
                        else
                            return $number;
                    }
                }
            }
        }
        $number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
        if ($oldDecimalSep)
            $number = str_replace($oldDecimalSep, '.', $number); # Format to float
        if ($multiplier != 1)
            $number = $number * $multiplier;
        # Convert float to new format
        $number = number_format($number,
            $format['numOfDecimals'],
            $format['decimalSeparator'],
            $format['thousandSeparator']
        );
    }
    return $number;
}
</code>```

This returns: 9,00 and 895,00 so the comma is in a different place right now. It's something I guess... Anyone got an idea to move the comma and remove a 0.

**** End Update ****

And echo-ed it like this:

```<code><td><p>vanaf " . formatNumber($number, [
    'numOfDecimals' => 2,
    'decimalSeparator' => ',',
    'thousandSeparator' => ' '
], ',.') . " p.p. <small>Excl btw</small></p></td>
</code>```

If I just echo the VerkoopPP40 row it returns: €89,5 or €9.

So I googled around some and found this:

```<code>$var = $row["VerkoopPP40"];
$var = ltrim($var, '0');
$foo = $var;
$prijzen = number_format($foo, 2, ',', '');
</code>```

This turns the . into a ,. But also returns €9,00 for the row that has 9 in it. But the strange thing is the row that has 89.5 in it now just returns €89,00. So somewhere in the code it rounds the numbers down.

Does anyone know how to get the price to show just €9,00 and €89,50 respectively.

I tried the following codes as well:

```<code>SELECT ROUND(VerkoopPP40,2) AS RoundedPrice
</code>```

As database query. That didn't work.

```<code>$prijzen = CAST($prijzen as decimal(2,2));
</code>```

Also didn't work. Any more ideas?

答:
you should use number_format but in the right way let me explain it to you
you tried this with 89.5

```<code>$prijzen = number_format($foo, 2, ',', '');
</code>```

but this is written for 89,5 not for 89.5

```<code>//this will work for you

    $var = $row["VerkoopPP40"];
    echo 'raw output from database is :'.$var;
    $var = $var / 10;
    echo 'after this step the number is :'.$var;
    $var = number_format($var, 2, '.', '');
    echo 'after this step the number is :'.$var;
</code>```

number_format(the input number, decimal places, 'the divider between whole numbers and decimals', '')

Body:
I'm having some trouble getting the price to show correct on my website. Currently i have a row VerkoopPP40 which is a VARCHAR input. In this row there is a price e.g. 89,5 or just 9. When I try to get these values it does some unexpected things.

**** Update ****

I've just tried this code:

<?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{

    if ($format) {
        $format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
        # Find decimal separator
        # The decimal separator is the one that is the last and does not occur more than once
        if ($letters = str_replace(' ', '', $number)) { # Replace spaces
            if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
                if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
                    $lastletter = substr($letters, -1); # Returns last char
                    if (substr_count($letters, $lastletter) == 1) {
                        if (strpos($oldDecimalSeparator, $lastletter)  !== false)
                            $oldDecimalSep = $lastletter;
                        else
                            return $number;
                    }
                }
            }
        }
        $number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
        if ($oldDecimalSep)
            $number = str_replace($oldDecimalSep, '.', $number); # Format to float
        if ($multiplier != 1)
            $number = $number * $multiplier;
        # Convert float to new format
        $number = number_format($number,
            $format['numOfDecimals'],
            $format['decimalSeparator'],
            $format['thousandSeparator']
        );
    }
    return $number;
}

This returns: 9,00 and 895,00 so the comma is in a different place right now. It's something I guess... Anyone got an idea to move the comma and remove a 0.

**** End Update ****

And echo-ed it like this:

vanaf " . formatNumber($number, [
    'numOfDecimals' => 2,
    'decimalSeparator' => ',',
    'thousandSeparator' => ' '
], ',.') . " p.p. Excl btw

If I just echo the VerkoopPP40 row it returns: €89,5 or €9.

So I googled around some and found this:

$var = $row["VerkoopPP40"];
$var = ltrim($var, '0');
$foo = $var;
$prijzen = number_format($foo, 2, ',', '');

This turns the . into a ,. But also returns €9,00 for the row that has 9 in it. But the strange thing is the row that has 89.5 in it now just returns €89,00. So somewhere in the code it rounds the numbers down.

Does anyone know how to get the price to show just €9,00 and €89,50 respectively.

I tried the following codes as well:

SELECT ROUND(VerkoopPP40,2) AS RoundedPrice

As database query. That didn't work.

$prijzen = CAST($prijzen as decimal(2,2));

Also didn't work. Any more ideas?

Body:
you should use number_format but in the right way let me explain it to you
you tried this with 89.5

$prijzen = number_format($foo, 2, ',', '');

but this is written for 89,5 not for 89.5

//this will work for you

    $var = $row["VerkoopPP40"];
    echo 'raw output from database is :'.$var;
    $var = $var / 10;
    echo 'after this step the number is :'.$var;
    $var = number_format($var, 2, '.', '');
    echo 'after this step the number is :'.$var;

number_format(the input number, decimal places, 'the divider between whole numbers and decimals', '')


问:
Restore a single document library from full backup?
Is there a way to restore a single document library and/or site from a full backup?
I need to restore a single file actually, but find that our vendor had set us up with only a full backup and an incremental backup strategy that backs up the entire farm.</p>

答: The only way i think you can restore your single file is to restore the full backup on some test server. The best practice to be followed while handling document is not taken care in your case hence that seems to be only solution </p>


问:
Angular2 Observable not get called if there is access to result attribute
I have an HTTP service like this to retrieve a user list:

```<code>@Injectable()
export class UserService {
    private _dataStore: {
         users: User[]
    };
    private _users: BehaviorSubject<User[]> = new BehaviorSubject<User[]>();
    public usersObservable: Observable<User[]> = this._users.asObservable();

    ...

    public list(): void {
    this
        .http
        .get('/users')
        .subscribe((res) => {
            this._dataStore.users = res.json() as User[];
            this._users.next(Object.assign({}, this._dataStore).users);
        });
    }
}
</code>```

Then in my component:

```<code>export class UsersComponent {
    public users: User[] = [];
    private usersObservable: Observable<User[]>;

    constructor(private userService: UserService) {
        this.usersObservable = this.userService.usersObservable;
    }

    public listUsers(): void {
        this.usersObservable.subscribe(data => {
            this.users = data;
            console.log(this.users.length); // <- this line cause the mysterious bug,
            // a replace with console.log(this.users) makes the app works correctly
        }));
        this.userService.list();
    }
}
</code>```

And the view of this component is just a table with rows like

```<code><tr *ngFor='let user of users'>
........ <!-- Display data here -->
</tr>
</code>```

The problem is, if I call any function that access to the attributes of data or this.users, the observable won't get called. If I just console.log(this.users) or console.log(data), everything went fine.

Do you have any idea where the problem is ?
Thank you in advance.

答:
echonax is right, not sure why someone Downvoted it.

Just to clarify a bit: When you set up a BehaviorSubject, you have to set a default value, that will be yielded as soon as someone subscribes to it.
If you look on your code, you are subscribing to the subject (this.usersObservable.subscribe(...) Before even sending the call (this.userService.list();), so there's no way the BehaviorSubject will contain the value you want. If you replace that BehaviorSubject for a ReplaySubject it may solve your problem.

Now the "bug" you mention is a side effect of this and the nature of the debugger. When you console.log(this.users.length), the console just prints a number as a result, i.e. 0. When this.users is populated, this number on the debugger won't change, because it's just a number.
However, console.log(this.users) prints a reference to this object, so it can be explored (those little arrows to see the contents), so when it gets populated, that's immediately after, you can see those changes in the debugger.
Try to console.log(JSON.stringify(this.users)) and you will see how by the time it logs the object it will be an empty array (because as it's a string, it doesn't update when the object updates)

Also, avoid using Subjects. Your solution can be probably improved by publish()ing the source. Take a look on this post for more insight: http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx

Body:
I have an HTTP service like this to retrieve a user list:

@Injectable()
export class UserService {
    private _dataStore: {
         users: User[]
    };
    private _users: BehaviorSubject<User[]> = new BehaviorSubject<User[]>();
    public usersObservable: Observable<User[]> = this._users.asObservable();

    ...

    public list(): void {
    this
        .http
        .get('/users')
        .subscribe((res) => {
            this._dataStore.users = res.json() as User[];
            this._users.next(Object.assign({}, this._dataStore).users);
        });
    }
}

Then in my component:

export class UsersComponent {
    public users: User[] = [];
    private usersObservable: Observable<User[]>;

    constructor(private userService: UserService) {
        this.usersObservable = this.userService.usersObservable;
    }

    public listUsers(): void {
        this.usersObservable.subscribe(data => {
            this.users = data;
            console.log(this.users.length); // <- this line cause the mysterious bug,
            // a replace with console.log(this.users) makes the app works correctly
        }));
        this.userService.list();
    }
}

And the view of this component is just a table with rows like

........

The problem is, if I call any function that access to the attributes of data or this.users, the observable won't get called. If I just console.log(this.users) or console.log(data), everything went fine.

Do you have any idea where the problem is ?
Thank you in advance.


问:
How can I fix AMP Stylesheet error in my blogger site?
I am using Blogger for my following website:

http://ssc.bdresult.info/

After integrating AMP I tested my website and got few AMP errors.

Invalid CSS stylesheet

The attribute 'href' in tag 'link rel=stylesheet for fonts' is set to the invalid value 'https://www.blogger.com/dyn-css/authorization.css?targetBlogID=2053857296326564086&zx=0affe301-5faf-4dbf-bc73-928ca14db607'.

答:
You can use only whitelisted font:

Font providers can be whitelisted if they support CSS-only
  integrations and serve over HTTPS. The following origins are currently
  allowed for font serving via link tags:

Typography.com: cloud.typography.com Fonts.com:
  fast.fonts.net Google Fonts: fonts.googleapis.com Font
  Awesome: maxcdn.bootstrapcdn.com

AMP Specification


问:
JSON to XML class conversions
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

```<code>var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);
</code>```

Class.cs

```<code>public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}
</code>```

答:
json text and object structure seems to be invalid. you can try some like  this..

object structure

```<code>public class jClass
{
    public jTopThree[] count { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}
</code>```

serialization

```<code>        var serializer = new JavaScriptSerializer();
        var json1 = "{count:[{first:1,second:2,third:3},{first:11,second:22,third:33},{first:111,second:222,third:333}]}";
        var obj = serializer.Deserialize<jClass>(json1);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(jClass));
        string xmlString;
        using (System.IO.StringWriter sww = new System.IO.StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xmlSerializer.Serialize(writer, obj);
                xmlString = sww.ToString();
            }
        }
</code>```

Title: JSON to XML class conversions

Body:
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);

Class.cs

public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}

Body:
json text and object structure seems to be invalid. you can try some like  this..

object structure

public class jClass
{
    public jTopThree[] count { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}

serialization

        var serializer = new JavaScriptSerializer();
        var json1 = "{count:[{first:1,second:2,third:3},{first:11,second:22,third:33},{first:111,second:222,third:333}]}";
        var obj = serializer.Deserialize<jClass>(json1);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(jClass));
        string xmlString;
        using (System.IO.StringWriter sww = new System.IO.StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xmlSerializer.Serialize(writer, obj);
                xmlString = sww.ToString();
            }
        }


问:
Break statement misplaced in while-loop
I'd like to create a script that asks for the item you want from a list (array), check if the item is on stock, displays the inventory if your type "list" and quit the program (while loop) if you type "quit"

while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');
  search = search.toLowerCase;
}
if (search = 'quit') {
  break; // if the client types quit, they exit the store, loop ends
} else if search == 'list'{
  write('
We currently have ' + inventory.join(', ') + ' in stock.
');
} else if (inventory.indexOf(search) > - 1) {
  write('
Yes, we have ' + search + ' in our stock.
');
} else {
  write('
Sorry, we don\'t have ' + search + ' in our stock
');
}```

The break statement is out of the loop but I don't really see where it should go ...

Any thoughts?

答:
Just put the entire "if" construct inside the "while" loop!

I.e., move the "}" from line 4 to the end of your code.

The "break" will then relate to the "while" construct.

Title: Break statement misplaced in while-loop

Body:
I'd like to create a script that asks for the item you want from a list (array), check if the item is on stock, displays the inventory if your type "list" and quit the program (while loop) if you type "quit"

while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');
  search = search.toLowerCase;
}
if (search = 'quit') {
  break; // if the client types quit, they exit the store, loop ends
} else if search == 'list'{
  write('
We currently have ' + inventory.join(', ') + ' in stock.
');
} else if (inventory.indexOf(search) > - 1) {
  write('
Yes, we have ' + search + ' in our stock.
');
} else {
  write('
Sorry, we don\'t have ' + search + ' in our stock
');
}

The break statement is out of the loop but I don't really see where it should go ...

Any thoughts?