问:
EWS reports SendItem as succeeding but message is still in Drafts folder
I'm using the EWS Managed API to send emails via exchange. When sending an item with attachments I first do a CreateItem and then a SendItem. Mostly this works fine but sometimes items are left in the Drafts folder, even though EWS reports the SendItem succeeds. How can I tell what's going on here?

The EWS messages I see from tracing are first CreateItem:

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013" />
    </soap:Header>
    <soap:Body>
      <m:CreateItem MessageDisposition="SaveOnly">
        <m:SavedItemFolderId>
          <t:DistinguishedFolderId Id="drafts">
            <t:Mailbox>
              <t:EmailAddress>amailbox@thedomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:SavedItemFolderId>

        ...

      </m:CreateItem>
    </soap:Body>
  </soap:Envelope>
</Trace>
</code>```

I get a Success response:

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
      <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1104" MinorBuildNumber="3" Version="V2_22" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <m:ResponseMessages>
          <m:CreateItemResponseMessage ResponseClass="Success">
            <m:ResponseCode>NoError</m:ResponseCode>
            <m:Items>
              <t:Message>
                <t:ItemId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAA=" ChangeKey="CQAAABYAAACJZGY3HQ5zQpbF9WoRXD0sAAA6JC4z" />
                <t:Attachments>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAGiKX5lgtuFLgfIBgyg4IwM=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQADkNd4D6H0NAgxCM7uH6MGo=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAKu2RdYFlBVIiLyPxshNCZQ=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAJ2C2tyz2iJHm8XC9LmSkcA=" />
                  </t:FileAttachment>
                </t:Attachments>
              </t:Message>
            </m:Items>
          </m:CreateItemResponseMessage>
        </m:ResponseMessages>
      </m:CreateItemResponse>
    </s:Body>
  </s:Envelope>
</Trace>
</code>```

I then ask to send it and move to SentItems:

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013" />
    </soap:Header>
    <soap:Body>
      <m:SendItem SaveItemToFolder="true">
        <m:ItemIds>
          <t:ItemId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAA=" ChangeKey="CQAAABYAAACJZGY3HQ5zQpbF9WoRXD0sAAA6JC4z" />
        </m:ItemIds>
        <m:SavedItemFolderId>
          <t:DistinguishedFolderId Id="sentitems">
            <t:Mailbox>
              <t:EmailAddress>amailbox@thedomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:SavedItemFolderId>
      </m:SendItem>
    </soap:Body>
  </soap:Envelope>
</Trace>
</code>```

And I get a Success NoError response:

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
      <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1104" MinorBuildNumber="3" Version="V2_22" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <m:SendItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <m:ResponseMessages>
          <m:SendItemResponseMessage ResponseClass="Success">
            <m:ResponseCode>NoError</m:ResponseCode>
          </m:SendItemResponseMessage>
        </m:ResponseMessages>
      </m:SendItemResponse>
    </s:Body>
  </s:Envelope>
</Trace>
</code>```

These are all traced by the same managed ThreadId so I'm pretty sure they all correspond to the same item.

I'm not using exchange impersonation. I'm authenticating with username & password auth with credentials for the mailbox that is sending the items.

EDIT (22 May):

I've added X-AnchorMailbox header to my requests and upgraded to EWS Managed API 2.2 (was using 2.1, although since the SOAP messages looked right I don't think this was an issue). The problem is still happening.

I added code to re-retrieve the item after sending, to check if it's still in Drafts folder. I do this through EmailMessage.Bind() with the Id of the item just sent from drafts. When I run against Exchange on Office 365 that always raises an exception because the item no longer exists, which is expected since the ItemId changes when the item moves folder. When I run against customer's Exchange server it finds the item by that Id. I then try to resend it and get a ServiceResponseException with message Access is denied. Check credentials and try again. If I try to resend a message against Office 365 I get a SendItemResponse with message The specified object was not found in the store., The process failed to get the correct properties. (SOAP message is SendItemResponse with ResponseCode ErrorItemNotFound.

I've raised a support request with Microsoft (which oddly hasn't been responded to in over 48 hours ... maybe there's some trick to raising support requests).

EDIT (24 May)

When repeating the tests I sometimes saw items that remain in Drafts BUT are also received by the recipient! When inspecting their Properties > Internet Headers via outlook they both have the same Message-ID. More indication that something is messed up on the Exchange side of things?

EDIT (30 May)

I heard from Microsoft support who explained a bit about how sending in exchange works and what they think is happening:

a No error response from EWS means that the message was
  successfully flagged for submissions (PR_MESSAGE_FLAGS >
  MSGFLAG_SUBMIT). When the submission flag is set, the Mail Submission
  service on Exchange notifies the Transport Service that there are
  messages awaiting to be picked up in the Drafts (Outbox if Outlook).
  If any client reads the message after it’s been flagged for submission
  but before it’s picked up by the Transport service, the MSGFLAG_SUBMIT
  flag is removed which leads to the message being stuck in the Drafts
  folder.

    In order to determine if this is the case, you can sign up for notifications using Streaming Notifications (and a tool the likes of
  EWSEditor or EwsStreaming) and check for any item Modified events and
  check for any PR_MESSAGE_FLAGS changes.

    As discussed, the message could have been accessed by any client or API before the transport service went to pick it up, such as OWA,
  Outlook, EWS Managed API, Outlook add-ins or any mobile apps.

So next task is twofold:

Identify if anything is reading my messages immediately after they've flagged to be sent, resetting the MSGFLAG_SUBMIT flag. If so, ask them to please stop.

Include a process to re-send items that I think have been sent that I later find in Drafts.

I didn't get any information about why I'd get an Access Denied when trying to resend, but perhaps that's consistent with something else modifying the item.

They didn't think there was any chance this is a problem in EWS, where EWS is incorrectly reporting success when actually the message hasn't been flagged to be sent. Which is reassuring.

EDIT (20 June):

Introducing a process to re-send items that are stuck in Drafts didn't work very well. It turns out that sometimes when items are left in Drafts they've actually been sent and received by the recipient, so re-sending them means the recipient gets a duplicate of the email. Or several, if the same problem happens again. Sometimes the item isn't sent but is still removed from Drafts and moved to Sent Items - again it's not possible for the sender to work out whether it's sent or not. Totally weird. I've asked another question here about specifically whether Exchange message sending is expected to be atomic and reliable.

Also posed on Exchange forums

答: I didn't solve this, except to ensure as far as possible that no other apps are interacting with the mailbox at the same time as advised by MS support. We changed permissions on the mailbox to stop some people who had access to the shared mailbox and would have had it available through outlook. This totally fixed the problem for the main customer who experienced the problem. BUT it's still totally weird to me that EWS/exchange can be so unreliable and I'd never choose to use it again given this sort of problem. It also doesn't explain the cases where a message was delivered but remained in the Drafts folder, meaning it's not possible to be sure of whether sending succeeded or failed. </p>

Body:
I'm using the EWS Managed API to send emails via exchange. When sending an item with attachments I first do a CreateItem and then a SendItem. Mostly this works fine but sometimes items are left in the Drafts folder, even though EWS reports the SendItem succeeds. How can I tell what's going on here?

The EWS messages I see from tracing are first CreateItem:

  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013" />
    </soap:Header>
    <soap:Body>
      <m:CreateItem MessageDisposition="SaveOnly">
        <m:SavedItemFolderId>
          <t:DistinguishedFolderId Id="drafts">
            <t:Mailbox>
              <t:EmailAddress>amailbox@thedomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:SavedItemFolderId>

        ...

      </m:CreateItem>
    </soap:Body>
  </soap:Envelope>
</Trace>

I get a Success response:

  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
      <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1104" MinorBuildNumber="3" Version="V2_22" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <m:ResponseMessages>
          <m:CreateItemResponseMessage ResponseClass="Success">
            <m:ResponseCode>NoError</m:ResponseCode>
            <m:Items>
              <t:Message>
                <t:ItemId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAA=" ChangeKey="CQAAABYAAACJZGY3HQ5zQpbF9WoRXD0sAAA6JC4z" />
                <t:Attachments>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAGiKX5lgtuFLgfIBgyg4IwM=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQADkNd4D6H0NAgxCM7uH6MGo=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAKu2RdYFlBVIiLyPxshNCZQ=" />
                  </t:FileAttachment>
                  <t:FileAttachment>
                    <t:AttachmentId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAABEgAQAJ2C2tyz2iJHm8XC9LmSkcA=" />
                  </t:FileAttachment>
                </t:Attachments>
              </t:Message>
            </m:Items>
          </m:CreateItemResponseMessage>
        </m:ResponseMessages>
      </m:CreateItemResponse>
    </s:Body>
  </s:Envelope>
</Trace>

I then ask to send it and move to SentItems:

  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013" />
    </soap:Header>
    <soap:Body>
      <m:SendItem SaveItemToFolder="true">
        <m:ItemIds>
          <t:ItemId Id="AAMkADExMmY0MTgzLWJmZmUtNDcxNi1iOTk0LWMzZTU3M2I3NjBkMwBGAAAAAABL/dBAdDByRbztYn12Cy/4BwCJZGY3HQ5zQpbF9WoRXD0sAAAAAAEPAACJZGY3HQ5zQpbF9WoRXD0sAAA6HNVuAAA=" ChangeKey="CQAAABYAAACJZGY3HQ5zQpbF9WoRXD0sAAA6JC4z" />
        </m:ItemIds>
        <m:SavedItemFolderId>
          <t:DistinguishedFolderId Id="sentitems">
            <t:Mailbox>
              <t:EmailAddress>amailbox@thedomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:SavedItemFolderId>
      </m:SendItem>
    </soap:Body>
  </soap:Envelope>
</Trace>

And I get a Success NoError response:

  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
      <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1104" MinorBuildNumber="3" Version="V2_22" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <m:SendItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <m:ResponseMessages>
          <m:SendItemResponseMessage ResponseClass="Success">
            <m:ResponseCode>NoError</m:ResponseCode>
          </m:SendItemResponseMessage>
        </m:ResponseMessages>
      </m:SendItemResponse>
    </s:Body>
  </s:Envelope>
</Trace>

These are all traced by the same managed ThreadId so I'm pretty sure they all correspond to the same item.

I'm not using exchange impersonation. I'm authenticating with username & password auth with credentials for the mailbox that is sending the items.

EDIT (22 May):

I've added X-AnchorMailbox header to my requests and upgraded to EWS Managed API 2.2 (was using 2.1, although since the SOAP messages looked right I don't think this was an issue). The problem is still happening.

I added code to re-retrieve the item after sending, to check if it's still in Drafts folder. I do this through EmailMessage.Bind() with the Id of the item just sent from drafts. When I run against Exchange on Office 365 that always raises an exception because the item no longer exists, which is expected since the ItemId changes when the item moves folder. When I run against customer's Exchange server it finds the item by that Id. I then try to resend it and get a ServiceResponseException with message Access is denied. Check credentials and try again. If I try to resend a message against Office 365 I get a SendItemResponse with message The specified object was not found in the store., The process failed to get the correct properties. (SOAP message is SendItemResponse with ResponseCode ErrorItemNotFound.

I've raised a support request with Microsoft (which oddly hasn't been responded to in over 48 hours ... maybe there's some trick to raising support requests).

EDIT (24 May)

When repeating the tests I sometimes saw items that remain in Drafts BUT are also received by the recipient! When inspecting their Properties > Internet Headers via outlook they both have the same Message-ID. More indication that something is messed up on the Exchange side of things?

EDIT (30 May)

I heard from Microsoft support who explained a bit about how sending in exchange works and what they think is happening:

a No error response from EWS means that the message was
  successfully flagged for submissions (PR_MESSAGE_FLAGS >
  MSGFLAG_SUBMIT). When the submission flag is set, the Mail Submission
  service on Exchange notifies the Transport Service that there are
  messages awaiting to be picked up in the Drafts (Outbox if Outlook).
  If any client reads the message after it’s been flagged for submission
  but before it’s picked up by the Transport service, the MSGFLAG_SUBMIT
  flag is removed which leads to the message being stuck in the Drafts
  folder.

    In order to determine if this is the case, you can sign up for notifications using Streaming Notifications (and a tool the likes of
  EWSEditor or EwsStreaming) and check for any item Modified events and
  check for any PR_MESSAGE_FLAGS changes.

    As discussed, the message could have been accessed by any client or API before the transport service went to pick it up, such as OWA,
  Outlook, EWS Managed API, Outlook add-ins or any mobile apps.

So next task is twofold:

Identify if anything is reading my messages immediately after they've flagged to be sent, resetting the MSGFLAG_SUBMIT flag. If so, ask them to please stop.

Include a process to re-send items that I think have been sent that I later find in Drafts.

I didn't get any information about why I'd get an Access Denied when trying to resend, but perhaps that's consistent with something else modifying the item.

They didn't think there was any chance this is a problem in EWS, where EWS is incorrectly reporting success when actually the message hasn't been flagged to be sent. Which is reassuring.

EDIT (20 June):

Introducing a process to re-send items that are stuck in Drafts didn't work very well. It turns out that sometimes when items are left in Drafts they've actually been sent and received by the recipient, so re-sending them means the recipient gets a duplicate of the email. Or several, if the same problem happens again. Sometimes the item isn't sent but is still removed from Drafts and moved to Sent Items - again it's not possible for the sender to work out whether it's sent or not. Totally weird. I've asked another question here about specifically whether Exchange message sending is expected to be atomic and reliable.

Also posed on Exchange forums


来源: stackexchange

问:
how to insert data in datagridview's particular row from database
In my datagridview (DGV) I have custom columns . In first column I have combo box . how can I display data in only that row on which the combo box value selected . for e.g. If I select value in combo box from 3rd row , corresponding data should display in 3rd row, not in 1st row and should not affect the other filled rows . if i select value from 6th row ,d data should be in 6th oe ..

I have no idea from  where to start .

Any suggestion .

thanks in advance ..

答: To insert database data from datagridview, you can set the Visible property of the Combo Box as False. The Combo box must not be visible when the form loads. The Combo Box will show up when the focus is on a Cell corresponding to the specific Column. </p>

ContentLicense: CC BY-SA 3.0


问:
Is passing a service reference to another service layer bad practice?
I've got a C# MVC application that I break up in the following way:
View -> Controller -> Service -> Repository

I use the thin controller practice with each view having a unique view model that's returned from the relevant service.

Quick Example:
View: /NewAppointment/Step1

Its controler would look like this:

```<code>public ActionResult Step1()
{
  return View(_appointmentService.Step1GetModel() );
}
</code>```

And the appointment service layer would look like this:

```<code>public Step1Model Step1GetModel()
{
  return new Step1Model();
}
</code>```

Thus I have several different service layers in use through out my application, each implementing a distinct interface.

My question comes in when I need to have one service layer interact with another service layer. In this case, is it better practice to pass an interface reference to the service call, or should I let the controller handle collecting all the data and then pass the relevant results back to the service?

Example:

Say I want to populate my view model with the customer's information by default. The two ways I see of doing this are:

Pass an customer interface reference to the appointment service, and then let the appointment service call the appropriate GetCustomer method in the customer service...

In Code:

```<code> private ICustomerService _customerService;
 private IAppointmentService _appointmentService;

 public ActionResult Step1()
 {
   var viewModel = _appointmentService.Step1GetModel( _customerService );
   return View(viewModel);
 }
</code>```

OR

Let the controller handle the logic of getting the customer, then pass that result to the appointment service.

In Code:

```<code>private ICustomerService _customerService;
private IAppointmentService _appointmentService;

public ActionResult Step1()
{
    var customer = _customerService.GetCustomer();
    var viewModel = _appointmentService.Step1GetModel( customer );
    return View(viewModel);
}
</code>```

I'm torn as to which would be better practice. The first keeps the controller nice and thin, but creates an inter-service dependency between the appointment service and the customer service. The second puts more logic into the controller, but keeps the services totally independent.

Anyone have thoughts as to which would be better practice?

Thanks~

答:
Thinking about his purely conceptually I don't think it makes sense for your services to know anything about your view models.  One of the main reasons to have a controller in the first place is to separate out your view logic from your business logic, but if your services are returning view specific data then they're inherently tied to your business logic.

Ideally I'd expect the method to look like this:

```<code>public ActionResult Step1()
{
    var customer = _customerService.GetCustomer();
    var appointment = _appointmentService.GetAppointmentFor(customer);

    var viewModel = new Step1ViewModel(customer, appointment);

    return View(viewModel);
}
</code>```

To answer your question more directly though, I think it's fine for your services to know about each other, they're part of the same conceptually layer.

Also, one more thing...

It sounds like you have a lot of parallel class hierarchies what with having services, repositories and controllers.  It might make more sense to use something like the unit of work pattern and a powerful ORM to do something like:

```<code>public MyController(IUnitOfWork unitOfWork)...

public ActionResult Step1()
{
    var customer = unitOfWork.Find<Customer>();
    var viewModel = new Step1ViewModel(customer.Appointment);
    return View(viewModel);
}
</code>```

After all, the value of your application is in the model, not in the services.

ContentLicense: CC BY-SA 2.5

Body:
I've got a C# MVC application that I break up in the following way:
View -> Controller -> Service -> Repository

I use the thin controller practice with each view having a unique view model that's returned from the relevant service.

Quick Example:
View: /NewAppointment/Step1

Its controler would look like this:

public ActionResult Step1()
{
  return View(_appointmentService.Step1GetModel() );
}

And the appointment service layer would look like this:

public Step1Model Step1GetModel()
{
  return new Step1Model();
}

Thus I have several different service layers in use through out my application, each implementing a distinct interface.

My question comes in when I need to have one service layer interact with another service layer. In this case, is it better practice to pass an interface reference to the service call, or should I let the controller handle collecting all the data and then pass the relevant results back to the service?

Example:

Say I want to populate my view model with the customer's information by default. The two ways I see of doing this are:

Pass an customer interface reference to the appointment service, and then let the appointment service call the appropriate GetCustomer method in the customer service...

In Code:

 private ICustomerService _customerService;
 private IAppointmentService _appointmentService;

 public ActionResult Step1()
 {
   var viewModel = _appointmentService.Step1GetModel( _customerService );
   return View(viewModel);
 }

OR

Let the controller handle the logic of getting the customer, then pass that result to the appointment service.

In Code:

private ICustomerService _customerService;
private IAppointmentService _appointmentService;

public ActionResult Step1()
{
    var customer = _customerService.GetCustomer();
    var viewModel = _appointmentService.Step1GetModel( customer );
    return View(viewModel);
}

I'm torn as to which would be better practice. The first keeps the controller nice and thin, but creates an inter-service dependency between the appointment service and the customer service. The second puts more logic into the controller, but keeps the services totally independent.

Anyone have thoughts as to which would be better practice?

Thanks~

Body:
Thinking about his purely conceptually I don't think it makes sense for your services to know anything about your view models.  One of the main reasons to have a controller in the first place is to separate out your view logic from your business logic, but if your services are returning view specific data then they're inherently tied to your business logic.

Ideally I'd expect the method to look like this:

public ActionResult Step1()
{
    var customer = _customerService.GetCustomer();
    var appointment = _appointmentService.GetAppointmentFor(customer);

    var viewModel = new Step1ViewModel(customer, appointment);

    return View(viewModel);
}

To answer your question more directly though, I think it's fine for your services to know about each other, they're part of the same conceptually layer.

Also, one more thing...

It sounds like you have a lot of parallel class hierarchies what with having services, repositories and controllers.  It might make more sense to use something like the unit of work pattern and a powerful ORM to do something like:

public MyController(IUnitOfWork unitOfWork)...

public ActionResult Step1()
{
    var customer = unitOfWork.Find<Customer>();
    var viewModel = new Step1ViewModel(customer.Appointment);
    return View(viewModel);
}

After all, the value of your application is in the model, not in the services.


问:
onclick attribute can't be selected in jquery and not visible in inspector, but working
I'm working on a magento project with a plugin changes the onclick attribute on the (document).ready(). I tried to access this attribute using jquery to update it after a user action but it returns undefined. And I've noticed that the onclick attribute is NOT visible in the inspector but visible in the page source accessed by view page sourceorCtrl + u.

in inspector the targeted button looks like

```<code><button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty">
    <span>Add to cart<span>
</button>
</code>```

in the page source view it looks like:

```<code><button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty"
        onclick="setLocation('http://mysite.local/eg_ar/checkout/cart/add/uenc/aHR0cDovL2hhaXJidXJzdGFyYWJpYS5sb2NhbC9lZ19hci8,/product/5/form_key/lqUtnptjQU7Cn7E1/qty/1/')">
    <span>Add to cart</span>
</button>
</code>```

this button is correctly accessed via the variable btn and when i use console.log(btn.attr("onclick")); it returns undefined but with attribute like id it returns the id correctly.

NOTE: the button is working very well. but I can't edit it.

Update:
as per @Saptal question I've to show more code. in the html part I've this block

```<code><div class="add-to-cart">
    <form id="product_addtocart_form_15">
            <span class="custom-counter">
            <input min="1" name="qty" id="qty" maxlength="2" value="1" title="qty" class="qty qty-updating" type="number"><div class="custom-counter-nav"><div class="custom-counter-button custom-counter-up">+</div><div class="custom-counter-button custom-counter-down">-</div></div>
        </span>
        <button type="button" id="addtocart_btn_15" title="Add to cart" class="button btn-cart btn-cart-with-qty"><span>Add to cart</span></button>

   </form>

</div>
</code>```

and in js I do that

```<code><script>
    jQuery('.qty-updating').each(function(){
        var qty = jQuery(this);

        qty.on('change', function(e){
            alert('here');
            var btn = qty.parent().siblings('.btn-cart');
            console.log(btn.attr("onclick"));
        });

    });
</script>
</code>```

thanks in advance

答: In your issue description you said you use a plugin which changes the onclick attribute. It seems that there is a JS code which actually deletes that attribute. Can you disable that plugin just to make sure the onclick attribute is NOT deleted?</p>

Body:
I'm working on a magento project with a plugin changes the onclick attribute on the (document).ready(). I tried to access this attribute using jquery to update it after a user action but it returns undefined. And I've noticed that the onclick attribute is NOT visible in the inspector but visible in the page source accessed by view page sourceorCtrl + u.

in inspector the targeted button looks like

<button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty">
    Add to cart
</button>

in the page source view it looks like:

<button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty"
        onclick="setLocation('http://mysite.local/eg_ar/checkout/cart/add/uenc/aHR0cDovL2hhaXJidXJzdGFyYWJpYS5sb2NhbC9lZ19hci8,/product/5/form_key/lqUtnptjQU7Cn7E1/qty/1/')">
    Add to cart
</button>

this button is correctly accessed via the variable btn and when i use console.log(btn.attr("onclick")); it returns undefined but with attribute like id it returns the id correctly.

NOTE: the button is working very well. but I can't edit it.

Update:
as per @Saptal question I've to show more code. in the html part I've this block

    <form id="product_addtocart_form_15">

            <input min="1" name="qty" id="qty" maxlength="2" value="1" title="qty" class="qty qty-updating" type="number">

+

-

        <button type="button" id="addtocart_btn_15" title="Add to cart" class="button btn-cart btn-cart-with-qty">Add to cart</button>

   </form>

and in js I do that

thanks in advance


问:
How to find the selector for webscraping in Java?
I am trying to scrape the statistics of a hockey game from a website. What I can to scrape exactly, is that if in the last games before that game the home team had won or had losen. So there is this website, and I am trying to get the information from the last column. I used the inspector in the developer tools and I guessed I should used the selector "span.winLoseIcon a". I think it is not the right selector to use here, because when I run the program the String title is empty.

Here is my code snippet:

```<code>  import org.jsoup.Jsoup;
 import org.jsoup.nodes.Document;
 import org.jsoup.nodes.Element;

public class HockeyScraper {

public static void main (String[] args) throws Exception {
    final Document page = Jsoup.connect("http://www.eredmenyek.com/merkozes/nBPiuHF3/#egymas-elleni;overall").get();

    for (Element games : page.select("span.winLoseIcon a")) {
        final String title = games.text();

        System.out.println(title);
    }

}
</code>```

}

答:
I check the website, it's not loading data directly, it used JavaScript to load data, so you can't scrap directly by that url. I check that it using javascript to get data by sending get request to http://d.eredmenyek.com/x/feed/d_hh_nBPiuHF3_hu_1 with some header info which is mandatory.

You can use the below code that work for me to get all the title score etc

```<code>    final Document page = Jsoup
            .connect("http://d.eredmenyek.com/x/feed/d_hh_nBPiuHF3_hu_1")
            .cookie("_ga", "GA1.2.1639955025.1491211513")
            .referrer("http://d.eredmenyek.com/x/feed/proxy-local")
            .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
            .header("X-Fsign", "SW9D1eZo")
            .header("X-GeoIP", "1")
            .header("X-Requested-With", "XMLHttpRequest")
            .get();

    for (Element game : page.getElementsByClass("head_to_head").first().getElementsByTag("tr")) {
        System.out.println("----------------------------------------------------");
        System.out.println(game.text());

        Elements list = game.getElementsByClass("form-bg-last");
        if (!list.isEmpty()) {
            System.out.println("Title : " + list.first().attr("title"));
        }
    }
</code>```

Body:
I am trying to scrape the statistics of a hockey game from a website. What I can to scrape exactly, is that if in the last games before that game the home team had won or had losen. So there is this website, and I am trying to get the information from the last column. I used the inspector in the developer tools and I guessed I should used the selector "span.winLoseIcon a". I think it is not the right selector to use here, because when I run the program the String title is empty.

Here is my code snippet:

  import org.jsoup.Jsoup;
 import org.jsoup.nodes.Document;
 import org.jsoup.nodes.Element;

public class HockeyScraper {

public static void main (String[] args) throws Exception {
    final Document page = Jsoup.connect("http://www.eredmenyek.com/merkozes/nBPiuHF3/#egymas-elleni;overall").get();

    for (Element games : page.select("span.winLoseIcon a")) {
        final String title = games.text();

        System.out.println(title);
    }

}

}

Body:
I check the website, it's not loading data directly, it used JavaScript to load data, so you can't scrap directly by that url. I check that it using javascript to get data by sending get request to http://d.eredmenyek.com/x/feed/d_hh_nBPiuHF3_hu_1 with some header info which is mandatory.

You can use the below code that work for me to get all the title score etc

    final Document page = Jsoup
            .connect("http://d.eredmenyek.com/x/feed/d_hh_nBPiuHF3_hu_1")
            .cookie("_ga", "GA1.2.1639955025.1491211513")
            .referrer("http://d.eredmenyek.com/x/feed/proxy-local")
            .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
            .header("X-Fsign", "SW9D1eZo")
            .header("X-GeoIP", "1")
            .header("X-Requested-With", "XMLHttpRequest")
            .get();

    for (Element game : page.getElementsByClass("head_to_head").first().getElementsByTag("tr")) {
        System.out.println("----------------------------------------------------");
        System.out.println(game.text());

        Elements list = game.getElementsByClass("form-bg-last");
        if (!list.isEmpty()) {
            System.out.println("Title : " + list.first().attr("title"));
        }
    }


问:
How do I know when a copy job is done?
I'm using

```<code>File.Copy(source, dest);
</code>```

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?

答: Isn't File.Copy a blocking method?  It should wait on that line until the copy of the file is complete then continue execution.</p>

Title: How do I know when a copy job is done?

Body:
I'm using

File.Copy(source, dest);

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?


问:
How to get the total sum
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

```<code>enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}
</code>```

答:
You need a variable which stores the sum of the power. You just have to add the value of the current gun to it in the loop:</p>

```<code>   public void getTotalPower()
    {
       int totalPower = 0;
       for (BigGun oneGun : gun)
       {
           totalPower += oneGun.getNumberPower();
       }
       System.out.println(totalPower);
    }
</code>```

Title: How to get the total sum

Body:
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}

Body:
You need a variable which stores the sum of the power. You just have to add the value of the current gun to it in the loop:

   public void getTotalPower()
    {
       int totalPower = 0;
       for (BigGun oneGun : gun)
       {
           totalPower += oneGun.getNumberPower();
       }
       System.out.println(totalPower);
    }


问:
How to make function work once per image
I have 5 images with the same function in a javascript field and I want to know how to be able to use the function once per image </p>

<p>my current code </p>

```<code>function move()
{
    // move to the first now
    document.getElementsByTagName('div')[0].insertBefore
    (this, document.getElementsByTagName('div')[0].firstChild)
}

img1.onclick=move
img2.onclick=move
img3.onclick=move
img4.onclick=move
img5.onclick=move
</code>```

答:
If the environment supports the 3rd parameter in addEventLister, that could is definitely better to use. However, if you need to work with legacy code (because you're working in an intranet, and/or you can't add a build step), you can have something like that:

```<code>var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.onclick = function() { move.call(this); this.onclick = null; }
}
</code>```

This will works mostly everywhere, even where addEventListener is not supported at all.
But I wouldn't recommend this if you have the proper support of addEventListener and at least ES6; I just add this answer for the record. If you have at least addEventListener (older IE doesn't, they've attachEvent) you could at least have:

```<code>var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.addEventListener("click", function listener() {
    this.removeEventListener("click", listener, false);
    move.call(this);
  }, false); // in some browser the `useCapture` is still not optional
}
</code>```

If forEach is supported, the loop can be replaced with that.

Body:
I have 5 images with the same function in a javascript field and I want to know how to be able to use the function once per image

my current code

function move()
{
    // move to the first now
    document.getElementsByTagName('div')[0].insertBefore
    (this, document.getElementsByTagName('div')[0].firstChild)
}

img1.onclick=move
img2.onclick=move
img3.onclick=move
img4.onclick=move
img5.onclick=move

Body:
If the environment supports the 3rd parameter in addEventLister, that could is definitely better to use. However, if you need to work with legacy code (because you're working in an intranet, and/or you can't add a build step), you can have something like that:

var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.onclick = function() { move.call(this); this.onclick = null; }
}

This will works mostly everywhere, even where addEventListener is not supported at all.
But I wouldn't recommend this if you have the proper support of addEventListener and at least ES6; I just add this answer for the record. If you have at least addEventListener (older IE doesn't, they've attachEvent) you could at least have:

var imgs = [img1, img2, img3, img4, img5];

for (var img, i = 0; img = imgs[i++];) {
  img.addEventListener("click", function listener() {
    this.removeEventListener("click", listener, false);
    move.call(this);
  }, false); // in some browser the `useCapture` is still not optional
}

If forEach is supported, the loop can be replaced with that.


问:
Why does is_array() return false?
I have this SimpleXML object:

```<code>object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}
</code>```

Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?

Also, I am unable to cast it as an array using (array) $object->record. I get this error:

Warning:  It is not yet possible to
  assign complex types to properties

答:
It's not an array. The var_dump output is misleading. Consider:

```<code><?php
$string = <<<XML
<?xml version='1.0'?>
<foo>
 <bar>a</bar>
 <bar>b</bar>
</foo>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
var_dump($xml->bar);
?>
</code>```

Output:

```<code>object(SimpleXMLElement)#1 (1) {
  ["bar"]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
}

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(1) "a"
}
</code>```

As you can see by the second var_dump, it is actually a SimpleXMLElement.

Title: Why does is_array() return false?

Body:
I have this SimpleXML object:

object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}

Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?

Also, I am unable to cast it as an array using (array) $object->record. I get this error:

Warning:  It is not yet possible to
  assign complex types to properties

Body:
It's not an array. The var_dump output is misleading. Consider:

<?php
$string = <<<XML
<?xml version='1.0'?>
<foo>
 <bar>a</bar>
 <bar>b</bar>
</foo>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
var_dump($xml->bar);
?>

Output:

object(SimpleXMLElement)#1 (1) {
  ["bar"]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
}

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(1) "a"
}

As you can see by the second var_dump, it is actually a SimpleXMLElement.


问:
Can I setup VirtualHost with same Domain name and same Port
AS topic, does my I idea come to true

I need to define the DocumentRoot, ErrorLog and RedirectMatch for my symfony

答:
Seemingly you want to define more than one vhost using same port and domain-name combination?! If they differ by IP that's possible, if not, well, it's not.

But I don't assume that you have several IPs reserved for one name?! In most cases you also shouldn't! Vhost is the way to go here, BUT

```<code>domain1+port1 != domain2+port2
</code>```

So either the port or the name has to be different.

Body:
Seemingly you want to define more than one vhost using same port and domain-name combination?! If they differ by IP that's possible, if not, well, it's not.

But I don't assume that you have several IPs reserved for one name?! In most cases you also shouldn't! Vhost is the way to go here, BUT

domain1+port1 != domain2+port2

So either the port or the name has to be different.


问:
Extract only pattern matched text
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

```<code>use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*
</code>```

Is my regular expression incorrect?

答:
If you want to print 1234, you need to change your regex and print the 2nd match:</p>

```<code>use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d{4})/;

print $2;
</code>```

Title: Extract only pattern matched text

Body:
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*

Is my regular expression incorrect?

Body:
If you want to print 1234, you need to change your regex and print the 2nd match:

use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d{4})/;

print $2;


问:
How to distribute ios app with development provisional
My team is migrating in to a new Testing flow.

With two parts.

testing the app on test servers.

testing the app on production servers.

For testing the on production we are using TestFlight/Fabric Beta

My problem is with distributing the app with test servers and development provisionals (for dev push certificates)

Is there a way to distribute the test app without having the phone on location? (are testers are in a different country)

Thanks

答:
Try this virtual testing online, you need to upload your ipa file

https://portal.kobiton.com/devices?survey=true

1.Device token will not generate.

2.I am not aware of location upadation


答:
Yes, you can distribute your app for testing without having the phone in your office.

Provided your ipa file has  UDID of device (iPhone/iPad) which is added in apple member center and chosen in the Development Provisional certificate

EDIT :
StackOverflow thread to generate a ipa file from Xcode.

Title: How to distribute ios app with development provisional

Body:
My team is migrating in to a new Testing flow.

With two parts.

testing the app on test servers.

testing the app on production servers.

For testing the on production we are using TestFlight/Fabric Beta

My problem is with distributing the app with test servers and development provisionals (for dev push certificates)

Is there a way to distribute the test app without having the phone on location? (are testers are in a different country)

Thanks


问:
Unsupported Java encoding for writing wsdl file
when deploying the following webservice

```<code>@WebService(serviceName = "TestService")
@SOAPBinding(use = Use.LITERAL, style = Style.DOCUMENT, parameterStyle= SOAPBinding.ParameterStyle.WRAPPED)
public class KekeDummyWebservice implements kekeService {...
</code>```

on one of my servers I do get the following error:

```<code>javax.wsdl.WSDLException: WSDLException:faultCode=CONFIGURATION_ERROR: Unsupported Java encoding for writing wsdl   file: 'ISO8859_15'.
</code>```

I don't know where the 'ISO8859_15' encoding comes from. The wildfly prints out

```<code>-Dfile.encoding=ISO-8859-15
</code>```

while starting. Another point is that during wildfly start the warning

```<code> [jacorb.codeset] (MSC service thread 1-7) Warning - unknown codeset (ISO8859_15) - defaulting to ISO-8859-1
</code>```

can be seen.

Thanks

答:
I had similar issue on our system, with following error in the log during deployment on Wildlfy10:

Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=CONFIGURATION_ERROR: Unsupported Java encoding for writing wsdl file: 'Cp1252'

Finally it was solved by resaving of xsd/wsld in utf-8 and setting targetNamespace in WS implementaion accordingly to what was defined in xsd/wsld. This aproach is not fully applicable on your case, but maybe it helps.

Body:
when deploying the following webservice

@WebService(serviceName = "TestService")
@SOAPBinding(use = Use.LITERAL, style = Style.DOCUMENT, parameterStyle= SOAPBinding.ParameterStyle.WRAPPED)
public class KekeDummyWebservice implements kekeService {...

on one of my servers I do get the following error:

javax.wsdl.WSDLException: WSDLException:faultCode=CONFIGURATION_ERROR: Unsupported Java encoding for writing wsdl   file: 'ISO8859_15'.

I don't know where the 'ISO8859_15' encoding comes from. The wildfly prints out

-Dfile.encoding=ISO-8859-15

while starting. Another point is that during wildfly start the warning

 [jacorb.codeset] (MSC service thread 1-7) Warning - unknown codeset (ISO8859_15) - defaulting to ISO-8859-1

can be seen.

Thanks


问:
how to find xpath of a dropdown list items in chrome browser in selenium webdriver
I am using chrome browser for selenium webdriver automated testing
By using google developer tools , it is easy to find simple xpath but I can't able to find out the drop down list item path in that , in firefox it is working , but in chrome it is not

I am sticking one image

Help me to find out the path of

答:
```<code>Select dropdown = new Select(driver.findElement(By.id("oe-fiels-input-62")));
dropdown.selectByText("[A1090] iMac");
</code>```


问:
$cordovaSocialSharing share on ios
I'm using ngcordova plugin social sharing: all worked fine on android, but on ios the title (subject) doesn't appear.     </p>

```<code>function shareEventDetail() {
    $ionicPlatform.ready(
        function () {
          $cordovaSocialSharing
            .share(null, title, null, urlEvent) // Share via native share sheet
            .then(function (result) {
                 // Success!
            }, function (err) {
                 // An error occured.
            });
        });
}
</code>```

<p>html : </p>

```<code><button class="button" ng-click="shareEventDetail()"></button>
</code>```

答:
i think it's the behaviour depend on which phone you use.
so just you can play it dirty , you can append all the data you want in message field (first parameter)</p>

Title: $cordovaSocialSharing share on ios

Body:
I'm using ngcordova plugin social sharing: all worked fine on android, but on ios the title (subject) doesn't appear.

function shareEventDetail() {
    $ionicPlatform.ready(
        function () {
          $cordovaSocialSharing
            .share(null, title, null, urlEvent) // Share via native share sheet
            .then(function (result) {
                 // Success!
            }, function (err) {
                 // An error occured.
            });
        });
}

html :

<button class="button" ng-click="shareEventDetail()"></button>


问:
Authentication in mongodb python
I am trying to connect to a mongodb database using authentication. My code for doing so is the following:

```<code>from pymongo import MongoClient
import urllib
client = MongoClient()
client = MongoClient('ip', port)
client.prod_db.authenticate('username', 'pass',  source='source_database')
</code>```

However I am receiving the following error in the authentication line:

pymongo.errors.OperationFailure: Authentication failed.

Am I doing the whole authentication thing wrongly?

EDIT: Also tried to use the following schema:

```<code>client = MongoClient('mongodb://user:pass@ip:port/')
</code>```

And I received the same mistake.

答:
There are many reasons that may cause the Authentication to fail.

First check that you allow your ip for bindip. Use 0.0.0.0 to allow all clients to access the MongoServer.

Pass mechanism also in the authenticate() as an argument.

Something like this works for me :

```<code>client = MongoClient('127.0.0.1', 27017)
client.admin.authenticate('username', 'pass', mechanism = 'SCRAM-SHA-1', source='source_database')
db_name = client[db]
col_name = col_name
col = db_name[col_name]
</code>```

Title: Authentication in mongodb python

Body:
I am trying to connect to a mongodb database using authentication. My code for doing so is the following:

from pymongo import MongoClient
import urllib
client = MongoClient()
client = MongoClient('ip', port)
client.prod_db.authenticate('username', 'pass',  source='source_database')

However I am receiving the following error in the authentication line:

pymongo.errors.OperationFailure: Authentication failed.

Am I doing the whole authentication thing wrongly?

EDIT: Also tried to use the following schema:

client = MongoClient('mongodb://user:pass@ip:port/')

And I received the same mistake.

Body:
There are many reasons that may cause the Authentication to fail.

First check that you allow your ip for bindip. Use 0.0.0.0 to allow all clients to access the MongoServer.

Pass mechanism also in the authenticate() as an argument.

Something like this works for me :

client = MongoClient('127.0.0.1', 27017)
client.admin.authenticate('username', 'pass', mechanism = 'SCRAM-SHA-1', source='source_database')
db_name = client[db]
col_name = col_name
col = db_name[col_name]


问:
Entity Framework - Azure Table Storage Provider - Enum Support
I am actually using the Azure Storage Table provider for EF (EntityFramework.AzureTableStorage 7.0.0-beta1).

I've ended up how to configure the DbContext:

```<code>public class Subscription
{
    public string Environment { get; set; }

    public string Name { get; set; }

    ...
    ...
}

public class EF7Context : DbContext
{
    public DbSet<Subscription> Subscriptions { get; set; }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseAzureTableStorage("MyconnectionString");
    }

    protected override void OnModelCreating(Microsoft.Data.Entity.Metadata.ModelBuilder modelBuilder)
    {
        // Configure the Azure Table Storage
        modelBuilder.Entity<Subscription>()
            .ForAzureTableStorage() // Data are stored in an Azure Table Storage.
            .Table("SubscriptionDev") // Name of the Table in the Azure Storage Account
            .PartitionAndRowKey(s => s.Environment, s => s.Name); // Map the partition and the row key
    }
}
</code>```

But Now I would like to add an enum as part of the Subscription model.
I've found a workaround to do this:

I've got an enum :

```<code>public enum QueuePriority
{
    High,
    Low
}
</code>```

I've added these properties to the Subscription class:

```<code>public int PriorityId { get; set; }

public QueuePriority Priority
{
    get { return (QueuePriority)PriorityId; }
    set { PriorityId = (int)value; }
}
</code>```

And Declare the Priority property as shadow in EF configuration so that I'm not going to have the PriorityId and the Priority stored both in the Azure Table :

```<code>protected override void OnModelCreating(Microsoft.Data.Entity.Metadata.ModelBuilder modelBuilder)
{
    ...

    // We are not mapping the Enum in the database only the IDs.
    modelBuilder.Entity<Subscription>().Property(s => s.Priority).Shadow();
}
</code>```

So I am wondering if there is a better way to accomplish this and/or If next versions of EF.AzureTableStorage is going to support Enum ?

Thanks

答:
Azure Table Storage SDK version > 8.0.0 already supports enums and many other simple and complex property types so you do not really need to use an extra framework just for that purpose.

You can simply flatten your POCO object using TableEntity.Flatten method:
https://msdn.microsoft.com/en-us/library/azure/mt775435.aspx

Write the flattened dictionary to table storage. When you read just pass the dictionary of EntityProperties to TableEntity.ConvertBack method:
https://msdn.microsoft.com/en-us/library/azure/mt775435.aspx

and it will recompose your original object including its Enum and other types of properties.

Your entity classes do not need to inherit from TableEntity class or implement ITableEntity interface, they can be just POCO objects with simple properties OR they may have nested complex properties of their own with many layers of object graph. Flatten and ConvertBack methods support both.

Body:
I am actually using the Azure Storage Table provider for EF (EntityFramework.AzureTableStorage 7.0.0-beta1).

I've ended up how to configure the DbContext:

public class Subscription
{
    public string Environment { get; set; }

    public string Name { get; set; }

    ...
    ...
}

public class EF7Context : DbContext
{
    public DbSet<Subscription> Subscriptions { get; set; }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseAzureTableStorage("MyconnectionString");
    }

    protected override void OnModelCreating(Microsoft.Data.Entity.Metadata.ModelBuilder modelBuilder)
    {
        // Configure the Azure Table Storage
        modelBuilder.Entity<Subscription>()
            .ForAzureTableStorage() // Data are stored in an Azure Table Storage.
            .Table("SubscriptionDev") // Name of the Table in the Azure Storage Account
            .PartitionAndRowKey(s => s.Environment, s => s.Name); // Map the partition and the row key
    }
}

But Now I would like to add an enum as part of the Subscription model.
I've found a workaround to do this:

I've got an enum :

public enum QueuePriority
{
    High,
    Low
}

I've added these properties to the Subscription class:

public int PriorityId { get; set; }

public QueuePriority Priority
{
    get { return (QueuePriority)PriorityId; }
    set { PriorityId = (int)value; }
}

And Declare the Priority property as shadow in EF configuration so that I'm not going to have the PriorityId and the Priority stored both in the Azure Table :

protected override void OnModelCreating(Microsoft.Data.Entity.Metadata.ModelBuilder modelBuilder)
{
    ...

    // We are not mapping the Enum in the database only the IDs.
    modelBuilder.Entity<Subscription>().Property(s => s.Priority).Shadow();
}

So I am wondering if there is a better way to accomplish this and/or If next versions of EF.AzureTableStorage is going to support Enum ?

Thanks


问:
React-Redux-Form Could not find form for "user" in the store
I'm getting this exception:

```<code> Uncaught Error: Unable to create Form component. Could not find form for "user" in the store.
</code>```

Here's my reducers.js

```<code>function initialUserState(state = {email: '', password: ''}) {
    return state;
}

const crmApp = combineReducers({
    auth,
    user: initialUserState
});

export default crmApp;
</code>```

And here's index.js

```<code>let store = createStore(reducers);
console.log(store.getState());

ReactDOM.render(
    <Provider store={ store }>
        <App />
    </Provider>,
    document.getElementById('root')
);
</code>```

Console output show that store contains "user" object:
Object {auth: Object, user: Object}

```<code>auth:
  Object
     isAuthenticated:false
     isFetching: false
  Object
    user:
      Object
        email:""
        password:""
</code>```

The user is basically model for login form.

Does someone have ideas how to fix that? Probably i'm putting the user model wrong in redux store?

Thanks in advance.:)

答:
You need to add redux-form to your reducer as detailed here. You shoudl end up with something like this.

```<code>import { reducer as formReducer } from 'redux-form'

const crmApp = combineReducers({
    auth,
    user: initialUserState,
    form: formReducer
});
</code>```

You also need to make sure you have attached the form correctly at the component level. You didn't post any code for your component though.

Body:
I'm getting this exception:

 Uncaught Error: Unable to create Form component. Could not find form for "user" in the store.

Here's my reducers.js

function initialUserState(state = {email: '', password: ''}) {
    return state;
}

const crmApp = combineReducers({
    auth,
    user: initialUserState
});

export default crmApp;

And here's index.js

let store = createStore(reducers);
console.log(store.getState());

ReactDOM.render(
    <Provider store={ store }>
        <App />
    </Provider>,
    document.getElementById('root')
);

Console output show that store contains "user" object:
Object {auth: Object, user: Object}

auth:
  Object
     isAuthenticated:false
     isFetching: false
  Object
    user:
      Object
        email:""
        password:""

The user is basically model for login form.

Does someone have ideas how to fix that? Probably i'm putting the user model wrong in redux store?

Thanks in advance.:)

Body:
You need to add redux-form to your reducer as detailed here. You shoudl end up with something like this.

import { reducer as formReducer } from 'redux-form'

const crmApp = combineReducers({
    auth,
    user: initialUserState,
    form: formReducer
});

You also need to make sure you have attached the form correctly at the component level. You didn't post any code for your component though.


问:
Using dict to run function and collecting data from function and put it in a variable
I am trying to change a script so it fits my needs.

The script is used to Control Husqarna Automower, and they just changed there API. With the old API and the old script i had it working. I am now trying to get the new script working as my old.

I am using Python 2.7, this is the part were i am lost.

This part of the code is Printing out the information when running it from commandpromt

```<code>mow = API()

mow.login("mail@mail.com", "Password")

mow.status()

print(mow.status())
</code>```

I the get this result in the print

```<code>{u'storedTimestamp': 1491209355746L, u'lastLocations': [{u'latitude': 57.57327166666666, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047653333333333}, {u'latitude': 57.57335833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.57335166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047656666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57335166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04766}, {u'latitude': 57.573301666666666, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04767}, {u'latitude': 57.57333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047643333333333}, {u'latitude': 57.57331333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047635}, {u'latitude': 57.57328833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047595}, {u'latitude': 57.573303333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047585}, {u'latitude': 57.573323333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047551666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047535}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.573328333333336, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047673333333334}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047685}, {u'latitude': 57.573296666666664, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04769}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047696666666667}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047705}, {u'latitude': 57.573321666666665, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57330666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047608333333333}, {u'latitude': 57.57334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047611666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047608333333333}, {u'latitude': 57.57333333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.5733, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047588333333334}, {u'latitude': 57.57330666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.0476}, {u'latitude': 57.573328333333336, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047613333333333}, {u'latitude': 57.573343333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047635}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047653333333333}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047693333333333}, {u'latitude': 57.573325, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047583333333334}, {u'latitude': 57.573298333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047556666666667}, {u'latitude': 57.573325, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047563333333333}, {u'latitude': 57.573315, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047615}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047646666666667}, {u'latitude': 57.57333666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047678333333334}, {u'latitude': 57.57333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047598333333333}, {u'latitude': 57.57333333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047586666666668}, {u'latitude': 57.573341666666664, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047573333333334}, {u'latitude': 57.573295, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047615}, {u'latitude': 57.57326666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047636666666667}, {u'latitude': 57.57326666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.573343333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047796666666667}, {u'latitude': 57.57329166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04763}, {u'latitude': 57.573303333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047616666666666}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047631666666666}, {u'latitude': 57.57326333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}], u'operatingMode': u'AUTO', u'showAsDisconnected': False, u'valueFound': True, u'lastErrorCode': 0, u'lastErrorCodeTimestamp': 0, u'nextStartTimestamp': 1491350400, u'batteryPercent': 100, u'connected': True, u'mowerStatus': u'PARKED_TIMER', u'nextStartSource': u'WEEK_TIMER', u'cachedSettingsUUID': u'070b3f55-ca32-4b09-8af5-2ed49365f643'}
</code>```

My goal is to get some of the data in to variables, so i changed that part to this

```<code>mow = API()

mow.login("martin@gusten.com", "mypassword")

dic_info = dict(mow.status()['mowerInfo'])
battery = dic_info.get('batteryPercent')

print battery
</code>```

But this doesent seems to work,
when i run the script it prints

```<code>'mowerInfo'
</code>```

And after that some errors generated by the script, so it seems like the mow.status never get runs?

Anyone see were I went wrong?

答: The information you're looking for is inside the main dictionary inmow.status(). So instead of doing dic_info = dict(mow.status()['mowerInfo']), change it to dic_info = mow.status(), and your code should work.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to change a script so it fits my needs.

The script is used to Control Husqarna Automower, and they just changed there API. With the old API and the old script i had it working. I am now trying to get the new script working as my old.

I am using Python 2.7, this is the part were i am lost.

This part of the code is Printing out the information when running it from commandpromt

mow = API()

mow.login("mail@mail.com", "Password")

mow.status()

print(mow.status())

I the get this result in the print

{u'storedTimestamp': 1491209355746L, u'lastLocations': [{u'latitude': 57.57327166666666, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047653333333333}, {u'latitude': 57.57335833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.57335166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047656666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57335166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04766}, {u'latitude': 57.573301666666666, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04767}, {u'latitude': 57.57333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047643333333333}, {u'latitude': 57.57331333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047635}, {u'latitude': 57.57328833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047595}, {u'latitude': 57.573303333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047585}, {u'latitude': 57.573323333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047551666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047535}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.573328333333336, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047673333333334}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047685}, {u'latitude': 57.573296666666664, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04769}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047696666666667}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047705}, {u'latitude': 57.573321666666665, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.57330666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047608333333333}, {u'latitude': 57.57334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047611666666667}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047608333333333}, {u'latitude': 57.57333333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047621666666666}, {u'latitude': 57.5733, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047588333333334}, {u'latitude': 57.57330666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.0476}, {u'latitude': 57.573328333333336, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047613333333333}, {u'latitude': 57.573343333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047641666666667}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047635}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047653333333333}, {u'latitude': 57.57330833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047693333333333}, {u'latitude': 57.573325, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047583333333334}, {u'latitude': 57.573298333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047556666666667}, {u'latitude': 57.573325, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047563333333333}, {u'latitude': 57.573315, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047615}, {u'latitude': 57.57332, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047646666666667}, {u'latitude': 57.57333666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047678333333334}, {u'latitude': 57.57333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047598333333333}, {u'latitude': 57.57333333333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047586666666668}, {u'latitude': 57.573341666666664, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047573333333334}, {u'latitude': 57.573295, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047615}, {u'latitude': 57.57326666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047636666666667}, {u'latitude': 57.57326666666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.573343333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047796666666667}, {u'latitude': 57.57329166666667, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.04763}, {u'latitude': 57.573303333333335, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047616666666666}, {u'latitude': 57.57331833333333, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}, {u'latitude': 57.57331, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047631666666666}, {u'latitude': 57.57326333333334, u'gpsStatus': u'USING_GPS_MAP', u'longitude': 12.047618333333334}], u'operatingMode': u'AUTO', u'showAsDisconnected': False, u'valueFound': True, u'lastErrorCode': 0, u'lastErrorCodeTimestamp': 0, u'nextStartTimestamp': 1491350400, u'batteryPercent': 100, u'connected': True, u'mowerStatus': u'PARKED_TIMER', u'nextStartSource': u'WEEK_TIMER', u'cachedSettingsUUID': u'070b3f55-ca32-4b09-8af5-2ed49365f643'}

My goal is to get some of the data in to variables, so i changed that part to this

mow = API()

mow.login("martin@gusten.com", "mypassword")

dic_info = dict(mow.status()['mowerInfo'])
battery = dic_info.get('batteryPercent')

print battery

But this doesent seems to work,
when i run the script it prints

'mowerInfo'

And after that some errors generated by the script, so it seems like the mow.status never get runs?

Anyone see were I went wrong?


问:
Error on amazon SES: SendEmail operation: Illegal addres
I'm trying to send email through AWS SES, but I'm receiving this error:

```<code>botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the SendEmail operation: Illegal address
</code>```

I already verified the email I'm sending to and from.
This is my code:

```<code>import boto3

client = boto3.client(
    'ses',
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY
)

response = client.send_email(
    Destination={
        'ToAddresses': [
            'xxx@xxx.com',
        ],
    },
    Message={
        'Body': {
            'Html': {
                'Charset': 'UTF-8',
                'Data': 'This message body contains HTML formatting. It can, for example, contain links like this one: <a class="ulink" href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide" target="_blank">Amazon SES Developer Guide</a>.',
            },
            'Text': {
                'Charset': 'UTF-8',
                'Data': 'This is the message body in text format.',
            },
        },
        'Subject': {
            'Charset': 'UTF-8',
            'Data': 'Test email',
        },
    },
    ReplyToAddresses=[
    ],
    ReturnPath='',
    ReturnPathArn='',
    Source='xxx@xxx.com',
    SourceArn='',
)
</code>```

How can I fix this?

答:
Try to remove the following:

```<code>    ReplyToAddresses=[],
    ReturnPath='',
    ReturnPathArn='',
    SourceArn='',
</code>```

Apparently they can't be empty!

Body:
I'm trying to send email through AWS SES, but I'm receiving this error:

botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the SendEmail operation: Illegal address

I already verified the email I'm sending to and from.
This is my code:

import boto3

client = boto3.client(
    'ses',
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY
)

response = client.send_email(
    Destination={
        'ToAddresses': [
            'xxx@xxx.com',
        ],
    },
    Message={
        'Body': {
            'Html': {
                'Charset': 'UTF-8',
                'Data': 'This message body contains HTML formatting. It can, for example, contain links like this one: Amazon SES Developer Guide.',
            },
            'Text': {
                'Charset': 'UTF-8',
                'Data': 'This is the message body in text format.',
            },
        },
        'Subject': {
            'Charset': 'UTF-8',
            'Data': 'Test email',
        },
    },
    ReplyToAddresses=[
    ],
    ReturnPath='',
    ReturnPathArn='',
    Source='xxx@xxx.com',
    SourceArn='',
)

How can I fix this?

Body:
Try to remove the following:

    ReplyToAddresses=[],
    ReturnPath='',
    ReturnPathArn='',
    SourceArn='',

Apparently they can't be empty!


答:
Please parse string to integer using wrapper class and return the Integer value Integer.parseInt(StringValue)
i.e </p>

```<code>public Integer getTotalPower(ArrayList<BigGun> gun)
{
   int sum=0;
   for (BigGun oneGun : gun)
   {
        sum=sum+Integer.parseInt(oneGun.getNumberPower());
       System.out.println(oneGun.getNumberPower());
   }
return sum;
}
</code>```

Title: How to get the total sum

Body:
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}

Body:
Please parse string to integer using wrapper class and return the Integer value Integer.parseInt(StringValue)
i.e

public Integer getTotalPower(ArrayList<BigGun> gun)
{
   int sum=0;
   for (BigGun oneGun : gun)
   {
        sum=sum+Integer.parseInt(oneGun.getNumberPower());
       System.out.println(oneGun.getNumberPower());
   }
return sum;
}


问:
PHP Mail adding BCC
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

```<code>$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
</code>```

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons

答:
// Additional headers

```<code>$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';
</code>```

// Mail it

```<code>mail($to, $subject, $message, implode("\r\n", $headers));
</code>```

link

Title: PHP Mail adding BCC

Body:
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons

Body:
// Additional headers

$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';

// Mail it

mail($to, $subject, $message, implode("\r\n", $headers));

link


问:
Get data from two tables in codeigniter
i am trying to execute query to get data from table 1 and apply where clause on table 2
this is a sample query to execute on Code-igniter

```<code> SELECT * FROM table1,table2 WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40
</code>```

this query execute in database but not execute in code-igniter

i am trying this code in model

```<code> $this->db->limit($limit, $start);
        $this->db->where('hide', 0);
        $this->db->where('reject', 0);
        $this->db->where('disable', 0);
        $this->db->where('private', 0);
        $this->db->where('table2.wepay_account_id !=',"");
        $this->db->from('table1','table2');
        $this->db->order_by('table1', 'DESC');
        $query = $this->db->get();
        $a=$this->db->last_query();
        print_r($a);
        exit;
</code>```

but i am facing this error

```<code>Error Number: 1054

Unknown column 'table2.wepay_account_id' in 'where clause'

SELECT * FROM (`table1`) WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40
</code>```

答:
replace

```<code>$this->db->from('table1','table2');
</code>```

with

```<code>$this->db->from('table1');
$this->db->join('table2','true');
</code>```

This will be equillent to your simple mysql query.

Title: Get data from two tables in codeigniter

Body:
i am trying to execute query to get data from table 1 and apply where clause on table 2
this is a sample query to execute on Code-igniter

 SELECT * FROM table1,table2 WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40

this query execute in database but not execute in code-igniter

i am trying this code in model

 $this->db->limit($limit, $start);
        $this->db->where('hide', 0);
        $this->db->where('reject', 0);
        $this->db->where('disable', 0);
        $this->db->where('private', 0);
        $this->db->where('table2.wepay_account_id !=',"");
        $this->db->from('table1','table2');
        $this->db->order_by('table1', 'DESC');
        $query = $this->db->get();
        $a=$this->db->last_query();
        print_r($a);
        exit;

but i am facing this error

Error Number: 1054

Unknown column 'table2.wepay_account_id' in 'where clause'

SELECT * FROM (`table1`) WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40

Body:
replace

$this->db->from('table1','table2');

with

$this->db->from('table1');
$this->db->join('table2','true');

This will be equillent to your simple mysql query.


问:
Android checkboxes, how to implement if statement.
I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.

But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.

e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".

```<code>package com.example.vic.cdmes_;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class results extends AppCompatActivity {
private Button displayResult;

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

}

private void viewResults() {
    final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
    final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
    final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
    final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
    final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
    final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
    final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
    final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
    final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
    final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
    final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
    final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
    final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
    final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
    final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
    final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
    final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
    final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
    final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
    final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
    final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");

    displayResult = (Button)findViewById(R.id.displayResults);
    displayResult.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(results.this,.toString(),
              //      Toast.LENGTH_SHORT).show();
            if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
            {
                //if the number of checkboxes exceeds
            }
            else
                if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
                {
                    //display the person might be having a widened bronchus
                }
                else
                if (alb1&&alb2&&alb3&&cs1&&cs2)
                {
                    //display the person might be having a alb disease
                }
                else
                if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
                {
                    //display the person might be having a airborne disease
                }

        }
    });
}
</code>```

}

thanks for the help in advance.

答:
Set Default Boolean value.  Like This</p>

```<code> final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);
</code>```

Body:
I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.

But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.

e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".

package com.example.vic.cdmes_;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class results extends AppCompatActivity {
private Button displayResult;

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

}

private void viewResults() {
    final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
    final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
    final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
    final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
    final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
    final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
    final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
    final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
    final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
    final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
    final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
    final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
    final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
    final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
    final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
    final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
    final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
    final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
    final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
    final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
    final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");

    displayResult = (Button)findViewById(R.id.displayResults);
    displayResult.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(results.this,.toString(),
              //      Toast.LENGTH_SHORT).show();
            if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
            {
                //if the number of checkboxes exceeds
            }
            else
                if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
                {
                    //display the person might be having a widened bronchus
                }
                else
                if (alb1&&alb2&&alb3&&cs1&&cs2)
                {
                    //display the person might be having a alb disease
                }
                else
                if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
                {
                    //display the person might be having a airborne disease
                }

        }
    });
}

}

thanks for the help in advance.

Body:
Set Default Boolean value.  Like This

 final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);