问:
How to insert jQuery code? Uncaught ReferenceError: $ is not defined in view razor code
I have the following Asp.Net MVC 4 razor code at the end of the file.

```<code>....
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<script type="text/javascript">
    $('#Address_State').val('MA');
</script>
////// End of file
</code>```

However, it generated the following html code. And it raises error at the line $('#Address_State').val('MA');. The error message is Uncaught ReferenceError: $ is not defined. How to insert jQuery code in the razor file?

```<code>.....
<script type="text/javascript">
    $('#Address_State').val('MA'); // Uncaught ReferenceError: $ is not defined
</script>
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>© 2013 - Paperspeed</p>
                </div>
            </div>
        </footer>

        <script src="/Scripts/jquery-1.9.1.js"></script>

    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

    </body>
</html>
</code>```

Update:

The following is the last four lines of _Layout.cshtml.

```<code>        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>
</code>```

答:
As @Dmitri K mentions, there's NO need to move anything around.

Just put your script that needs to be called after page load inside

$(document).ready(function () {} like so:

```<code>@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            // Items that NEED to be set after the page is loaded.
            $('#Address_State').val('MA');
            $('.some-div-class').on('click', 'button', function (event)
            {
               // Binding click event to all buttons in 'some-div-class'
               // Do something on those clicks
               event.preventDefault();
               someFunction();
            }
            // And so on.
        });

        //Items that DON'T NEED to be called on page load can be put outside document.ready. For eg:
        function someFunction() { // Some logic }
    </script>
}
</code>```

Body:
I have the following Asp.Net MVC 4 razor code at the end of the file.

....
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

////// End of file

However, it generated the following html code. And it raises error at the line $('#Address_State').val('MA');. The error message is Uncaught ReferenceError: $ is not defined. How to insert jQuery code in the razor file?

.....

© 2013 - Paperspeed

Update:

The following is the last four lines of _Layout.cshtml.

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)

Body:
As @Dmitri K mentions, there's NO need to move anything around.

Just put your script that needs to be called after page load inside

$(document).ready(function () {} like so:

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            // Items that NEED to be set after the page is loaded.
            $('#Address_State').val('MA');
            $('.some-div-class').on('click', 'button', function (event)
            {
               // Binding click event to all buttons in 'some-div-class'
               // Do something on those clicks
               event.preventDefault();
               someFunction();
            }
            // And so on.
        });

        //Items that DON'T NEED to be called on page load can be put outside document.ready. For eg:
        function someFunction() { // Some logic }
    </script>
}


来源: stackexchange

问:
Coroutines - unit testing viewModelScope.launch methods
I am writing unit tests for my viewModel, but having trouble executing the tests. The runBlocking { ... } block doesn't actually wait for the code inside to finish, which is surprising to me.

The test fails because result is null. Why doesn't runBlocking { ... } run the launch block inside the ViewModel in blocking fashion?

I know if I convert it to a async method that returns a Deferred object, then I can get the object by calling await(), or I can return a Job and call join(). But, I'd like to do this by leaving my ViewModel methods as void functions, is there a way to do this?

```<code>// MyViewModel.kt

class MyViewModel(application: Application) : AndroidViewModel(application) {

    val logic = Logic()
    val myLiveData = MutableLiveData<Result>()

    fun doSomething() {
        viewModelScope.launch(MyDispatchers.Background) {
            System.out.println("Calling work")
            val result = logic.doWork()
            System.out.println("Got result")
            myLiveData.postValue(result)
            System.out.println("Posted result")
        }
    }

    private class Logic {
        suspend fun doWork(): Result? {
          return suspendCoroutine { cont ->
              Network.getResultAsync(object : Callback<Result> {
                      override fun onSuccess(result: Result) {
                          cont.resume(result)
                      }

                     override fun onError(error: Throwable) {
                          cont.resumeWithException(error)
                      }
                  })
          }
    }
}
</code>```

```<code>// MyViewModelTest.kt

@RunWith(RobolectricTestRunner::class)
class MyViewModelTest {

    lateinit var viewModel: MyViewModel

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @Before
    fun init() {
        viewModel = MyViewModel(ApplicationProvider.getApplicationContext())
    }

    @Test
    fun testSomething() {
        runBlocking {
            System.out.println("Called doSomething")
            viewModel.doSomething()
        }
        System.out.println("Getting result value")
        val result = viewModel.myLiveData.value
        System.out.println("Result value : $result")
        assertNotNull(result) // Fails here
    }
}

</code>```

答:
I did use the mockk framework that helps to mock the viewModelScope instance like below

https://mockk.io/

```<code>viewModel = mockk<MyViewModel>(relaxed = true)
every { viewModel.viewModelScope}.returns(CoroutineScope(Dispatchers.Main))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing unit tests for my viewModel, but having trouble executing the tests. The runBlocking { ... } block doesn't actually wait for the code inside to finish, which is surprising to me.

The test fails because result is null. Why doesn't runBlocking { ... } run the launch block inside the ViewModel in blocking fashion?

I know if I convert it to a async method that returns a Deferred object, then I can get the object by calling await(), or I can return a Job and call join(). But, I'd like to do this by leaving my ViewModel methods as void functions, is there a way to do this?

// MyViewModel.kt

class MyViewModel(application: Application) : AndroidViewModel(application) {

    val logic = Logic()
    val myLiveData = MutableLiveData<Result>()

    fun doSomething() {
        viewModelScope.launch(MyDispatchers.Background) {
            System.out.println("Calling work")
            val result = logic.doWork()
            System.out.println("Got result")
            myLiveData.postValue(result)
            System.out.println("Posted result")
        }
    }

    private class Logic {
        suspend fun doWork(): Result? {
          return suspendCoroutine { cont ->
              Network.getResultAsync(object : Callback<Result> {
                      override fun onSuccess(result: Result) {
                          cont.resume(result)
                      }

                     override fun onError(error: Throwable) {
                          cont.resumeWithException(error)
                      }
                  })
          }
    }
}

// MyViewModelTest.kt

@RunWith(RobolectricTestRunner::class)
class MyViewModelTest {

    lateinit var viewModel: MyViewModel

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @Before
    fun init() {
        viewModel = MyViewModel(ApplicationProvider.getApplicationContext())
    }

    @Test
    fun testSomething() {
        runBlocking {
            System.out.println("Called doSomething")
            viewModel.doSomething()
        }
        System.out.println("Getting result value")
        val result = viewModel.myLiveData.value
        System.out.println("Result value : $result")
        assertNotNull(result) // Fails here
    }
}

Body:
I did use the mockk framework that helps to mock the viewModelScope instance like below

https://mockk.io/

viewModel = mockk<MyViewModel>(relaxed = true)
every { viewModel.viewModelScope}.returns(CoroutineScope(Dispatchers.Main))


问:
OpenXML C# Excel SharedStringItem Inserting new line
I'm using OpenXML to create a formatted block of text with Excel. The requirement is to use predefined styles (set by an admin) to format a block of text. I've managed to accomplish everything by using the SharedStringItem and the Run class. However I'm having trouble figuring out how to preserving the carriage returns "\r\n".

The following code is not producing the run on a new line

```<code>private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = Environment.NewLine };
      sharedString.Append(newRun);
}

private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = "\r\n" };
      sharedString.Append(newRun);
}
</code>```

When the above methods are used I can see the SharedStringItem.InnerText is using the new lines however appear to be lost in the markup.

<x:t>Our corporate and commercial litigation

Have I just stumbled upon a limitation of the SharedStringItem or am I missing something?

答:
In order to preserve the new line in the mark up you need to set the following property in the Text class.

```<code>Text { Space = SpaceProcessingModeValues.Preserve }
</code>```

I used the Open XML SDK Productivity Tool (definitely recommended and can be found here https://github.com/OfficeDev/Open-XML-SDK/releases/tag/v2.5 ) to help me solve this issue.

Body:
I'm using OpenXML to create a formatted block of text with Excel. The requirement is to use predefined styles (set by an admin) to format a block of text. I've managed to accomplish everything by using the SharedStringItem and the Run class. However I'm having trouble figuring out how to preserving the carriage returns "\r\n".

The following code is not producing the run on a new line

private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = Environment.NewLine };
      sharedString.Append(newRun);
}

private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = "\r\n" };
      sharedString.Append(newRun);
}

When the above methods are used I can see the SharedStringItem.InnerText is using the new lines however appear to be lost in the markup.

<x:t>Our corporate and commercial litigation

Have I just stumbled upon a limitation of the SharedStringItem or am I missing something?

Body:
In order to preserve the new line in the mark up you need to set the following property in the Text class.

Text { Space = SpaceProcessingModeValues.Preserve }

I used the Open XML SDK Productivity Tool (definitely recommended and can be found here https://github.com/OfficeDev/Open-XML-SDK/releases/tag/v2.5 ) to help me solve this issue.


问:
EF Core ToArray analog
Most of you know that ToList(), ToArray() use a lot of memory because they recreate the array after N element. I need to get all rows from table and I wrote smth like this

```<code>ToArray(_dbContext.MyTable.Count(), _dbContext.MyTable.Select(x => ...})

T[] ToArray<T>(int arraySize, IEnumerable<T> list)
    {
      var result = new T[arraySize];
      byte tempIndex = 0;
      foreach (var item in list)
      {
        result[tempIndex] = item;
        tempIndex++;
      }
      return result;
    }
</code>```

This code uses about 10% less memory than simple

```<code>_dbContext.MyTable.Select(x => ...}).ToList() \ ToArray()
</code>```

Does EF have something similar to my code?

答:
You are using less memory, but for sure, this operation will take more time running if the table is big and/or your database is non local.

You are performing two queries in the database, something like:

```<code>select count(*) from MyTable
</code>```

```<code>select * from MyTable
</code>```

EF uses a single query to achieve the same functionality. I think 10% memory is a very small price to pay for the better performance. Because of that, EF does not have this behavior.

Title: EF Core ToArray analog

Body:
Most of you know that ToList(), ToArray() use a lot of memory because they recreate the array after N element. I need to get all rows from table and I wrote smth like this

ToArray(_dbContext.MyTable.Count(), _dbContext.MyTable.Select(x => ...})

T[] ToArray<T>(int arraySize, IEnumerable<T> list)
    {
      var result = new T[arraySize];
      byte tempIndex = 0;
      foreach (var item in list)
      {
        result[tempIndex] = item;
        tempIndex++;
      }
      return result;
    }

This code uses about 10% less memory than simple

_dbContext.MyTable.Select(x => ...}).ToList() \ ToArray()

Does EF have something similar to my code?

Body:
You are using less memory, but for sure, this operation will take more time running if the table is big and/or your database is non local.

You are performing two queries in the database, something like:

select count(*) from MyTable

select * from MyTable

EF uses a single query to achieve the same functionality. I think 10% memory is a very small price to pay for the better performance. Because of that, EF does not have this behavior.


问:
Generate code and test coverage report separately without running coverage run twice
I am running coverage,py tool to get code coverage. Using command,

```<code>
     COVERAGE_FILE=.coverage_dir coverage run -a --omit */tests/* ./manage.py test --settings=dir.tests.settings_unittest

</code>```

I can view reports using, coverage report --data-file=.coverage_dir

This gives me coverage report of python source files. If I don't omit tests, I will get coverage report for both source and test files.

I want to have separate tests and code coverage report. If it is possible that I have to run the command only once.

So that in the end I can just run

```<code>coverage report --data-file=.coverage_dir
coverage report --data-file=.coverage_test
</code>```

to view the reports and get html reports.

答:
You can use the --include option on the report command.  Use coverage run once without the --omit option, then:

```<code>coverage report --include='tests/*'
coverage report --include='the_product/*'
</code>```

Body:
I am running coverage,py tool to get code coverage. Using command,

     COVERAGE_FILE=.coverage_dir coverage run -a --omit */tests/* ./manage.py test --settings=dir.tests.settings_unittest

I can view reports using, coverage report --data-file=.coverage_dir

This gives me coverage report of python source files. If I don't omit tests, I will get coverage report for both source and test files.

I want to have separate tests and code coverage report. If it is possible that I have to run the command only once.

So that in the end I can just run

coverage report --data-file=.coverage_dir
coverage report --data-file=.coverage_test

to view the reports and get html reports.

Body:
You can use the --include option on the report command.  Use coverage run once without the --omit option, then:

coverage report --include='tests/*'
coverage report --include='the_product/*'


问:
HASKELL -- function to loop over a do block?
I have a do block and want to loop over it few times.</p>

答:
There are various ways you can go about doing this.</p>
```<code>import Control.Monad

foo :: IO ()
foo = putStrLn "Hello there!"

main :: IO ()
main = do
   let someList = [1,4,9]

   forM_ someList $ \_ -> foo  -- Iterate over all values in the list
                               -- (ignoring the actual value)

   mapM_ (const foo) someList  -- Another way to write the same thing

   replicateM_ (length someList) foo  -- Repeat a constant number of times

   let go 0 = return ()   -- Small helper function
       go n = do          -- defining the loop
         foo
         go $ n-1
   go $ length someList
</code>```

Body:
There are various ways you can go about doing this.

import Control.Monad

foo :: IO ()
foo = putStrLn "Hello there!"

main :: IO ()
main = do
   let someList = [1,4,9]

   forM_ someList $ \_ -> foo  -- Iterate over all values in the list
                               -- (ignoring the actual value)

   mapM_ (const foo) someList  -- Another way to write the same thing

   replicateM_ (length someList) foo  -- Repeat a constant number of times

   let go 0 = return ()   -- Small helper function
       go n = do          -- defining the loop
         foo
         go $ n-1
   go $ length someList


问:
iterate through results of one table as input into another
Hope you could please help me. I have looked at a few questions on here that are similar in nature, but I have not been able to find what I am looking for, so hopefully this isn't a duplicate question.

I am trying to build a process whereby customers get billed for the number of business days they were renting a product.

I have one table which shows the start date and the end date for a particular rental.

And my organisation provides a Calendar service where if you feed it the start date, end date and calendar, it will return the number of business days.

My problem is that the start dates and end dates from the first table need to be passed as arguments in the query for the second table and I am struggling to find an efficient way to do this.

Table Customer_Data (c.200k rows):

```<code>| FirstName | LastName | StartDate | EndDate |
|:-----:|:-----:|:------:|:------|
| John | Doe | 02-02-2022 | 09-02-2022 |
</code>```

CalendarService: requires 3 arguments - a start date, an end date and a calendar (e.g. LDN or NYK etc).

I have the following code:

```<code>SELECT
*
FROM CalendarService
WHERE Calendar = 'LDN'
and StartDate in (select startdate from customer_data)
and endDate in (select endDate from customer_data)
</code>```

My issue is this returns over 5m rows as it essentially takes every single start date and compares that to every single end date to give me all the possible business day combinations, instead of only running it for the combinations in the first table.

Is there a more efficient way to pass each row in customer_data through the calendar_service?

I am using a proprietary data platform for my organisation that uses an adapted SQL variant so need to keep solutions generic. The platform does also take Python and R, but I dont know either of them.

答:
Here is an example inline table function. Not sure what you are pulling out of the CalendarService table so this leaves it open to add additional fields to the output opposed to using a single valued scalar function. You will still need some way of determining that Calendar value more dynamically...not sure on your options for that so I just have it set to a static value in this example.It would seem to me that should be something to track on your Customer_Data table, but that's up to you and your options.</p>
```<code>IF OBJECT_ID('dbo.fnGetBusinessDaysFromDateRange') IS NOT NULL
    DROP FUNCTION dbo.fnGetBusinessDaysFromDateRange
GO

CREATE FUNCTION dbo.fnGetBusinessDaysFromDateRange
(
    @StartDate DATETIME, @EndDate DATETIME, @CalendarType VARCHAR(8)
)
RETURNS TABLE
AS
    RETURN (
        SELECT
            CalendarService.DaysValue as BusinessDays,
            CalendarService.SomeValue
        FROM CalendarService
        WHERE CalendarService.Calendar = @CalendarType
        AND CalendarService.StartDate = @StartDate
        AND CalendarService.EndDate = @EndDate
    )

GO

--Usage:
SELECT
    CD.*,
    CalendarBusinessDays.BusinessDays,
    CalendarBusinessDays.SomeValue
FROM Customer_Data CD
CROSS APPLY dbo.fnGetBusinessDaysFromDateRange(CD.StartDate, CD.EndDate, 'NKY') as CalendarBusinessDays
</code>```

Body:
Hope you could please help me. I have looked at a few questions on here that are similar in nature, but I have not been able to find what I am looking for, so hopefully this isn't a duplicate question.

I am trying to build a process whereby customers get billed for the number of business days they were renting a product.

I have one table which shows the start date and the end date for a particular rental.

And my organisation provides a Calendar service where if you feed it the start date, end date and calendar, it will return the number of business days.

My problem is that the start dates and end dates from the first table need to be passed as arguments in the query for the second table and I am struggling to find an efficient way to do this.

Table Customer_Data (c.200k rows):

| FirstName | LastName | StartDate | EndDate |
|:-----:|:-----:|:------:|:------|
| John | Doe | 02-02-2022 | 09-02-2022 |

CalendarService: requires 3 arguments - a start date, an end date and a calendar (e.g. LDN or NYK etc).

I have the following code:

SELECT
*
FROM CalendarService
WHERE Calendar = 'LDN'
and StartDate in (select startdate from customer_data)
and endDate in (select endDate from customer_data)

My issue is this returns over 5m rows as it essentially takes every single start date and compares that to every single end date to give me all the possible business day combinations, instead of only running it for the combinations in the first table.

Is there a more efficient way to pass each row in customer_data through the calendar_service?

I am using a proprietary data platform for my organisation that uses an adapted SQL variant so need to keep solutions generic. The platform does also take Python and R, but I dont know either of them.

Body:
Here is an example inline table function. Not sure what you are pulling out of the CalendarService table so this leaves it open to add additional fields to the output opposed to using a single valued scalar function. You will still need some way of determining that Calendar value more dynamically...not sure on your options for that so I just have it set to a static value in this example.It would seem to me that should be something to track on your Customer_Data table, but that's up to you and your options.

IF OBJECT_ID('dbo.fnGetBusinessDaysFromDateRange') IS NOT NULL
    DROP FUNCTION dbo.fnGetBusinessDaysFromDateRange
GO

CREATE FUNCTION dbo.fnGetBusinessDaysFromDateRange
(
    @StartDate DATETIME, @EndDate DATETIME, @CalendarType VARCHAR(8)
)
RETURNS TABLE
AS
    RETURN (
        SELECT
            CalendarService.DaysValue as BusinessDays,
            CalendarService.SomeValue
        FROM CalendarService
        WHERE CalendarService.Calendar = @CalendarType
        AND CalendarService.StartDate = @StartDate
        AND CalendarService.EndDate = @EndDate
    )

GO

--Usage:
SELECT
    CD.*,
    CalendarBusinessDays.BusinessDays,
    CalendarBusinessDays.SomeValue
FROM Customer_Data CD
CROSS APPLY dbo.fnGetBusinessDaysFromDateRange(CD.StartDate, CD.EndDate, 'NKY') as CalendarBusinessDays


问:
How to get only specific fields with Google Directory API users.list
The documentation (https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list#query-parameters) says you can use customFieldMask to get only specific fields. I cannot figure out the format/structure of this property.

For example, given this for a user:

```<code>{
  "kind": "admin#directory#user",
  "id": "...",
  "etag": "\"...\"",
  "primaryEmail": "...",
  "name": {
    "givenName": "...",
    "familyName": "...",
    "fullName": "......"
  },
  "emails": [
    {
      "address": "...",
      "primary": true
    }
  ]
}
</code>```

I only want to get primaryEmail but I can't figure out how.

答: The Directory API can't retrieve the 'primaryEmail' with the customFieldMask attribute, with this attribute you can only specify the custom schema names that you create in the Admin console.

Body:
The documentation (https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list#query-parameters) says you can use customFieldMask to get only specific fields. I cannot figure out the format/structure of this property.

For example, given this for a user:

{
  "kind": "admin#directory#user",
  "id": "...",
  "etag": "\"...\"",
  "primaryEmail": "...",
  "name": {
    "givenName": "...",
    "familyName": "...",
    "fullName": "......"
  },
  "emails": [
    {
      "address": "...",
      "primary": true
    }
  ]
}

I only want to get primaryEmail but I can't figure out how.


问:
JsonConvert.SerializeObject() not serializing a List(of T) where T is a custom Class of mine
I am trying to format Quote items data into a JSON Object to later save to MySQL. the following code produces JSONObject, which is returning an empty JSON object, like this: [{}], even though Quote_Items_Info_Data IS NOT empty. No errors are being triggered!
Why on earth is JsonConvert is not serializing?

```<code>Friend Class JSON_Quote_Item
    Friend Property ItemNumber As String
    Friend Property ItemDescription As String
    Friend Property ItemQty As String
    Friend Property ItemPrice As String
    Public Sub New()
    End Sub
    Public Sub New(ByVal _ItemNumber As String, ByVal _ItemDescription As String, ByVal _itemQty As String, ByVal _itemPrice As String)
        ItemNumber = _ItemNumber.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemDescription = _ItemDescription.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemQty = _itemQty.Trim
        ItemPrice = _itemPrice.Trim
    End Sub
End Class
'
'
''' <summary>
''' Convert all Quote items to a JSON object on the form and save it to the server DB.
''' senderFRM is the Quote Creator/Editor. Following an example from: https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
''' and https://www.newtonsoft.com/json
''' </summary>
''' <param name="senderFRM"></param>
''' <returns></returns>
Friend Function SaveAllQuoteItems(senderFRM As frmQuotesCreatorEditor) As Boolean
    Try
        'make sure I will not run into an exception!
        If senderFRM IsNot Nothing AndAlso String.IsNullOrEmpty(senderFRM.txtQuoteNumber.Text.Trim) = False Then
            Dim QuoteNumber As String = senderFRM.txtQuoteNumber.Text.Trim
            'Holds a list of the custom class JSON_Quote_Item as T and contain all the form quote items data.
            Dim Quote_Items_Info_Data As List(Of JSON_Quote_Item) = New List(Of JSON_Quote_Item)
            '

            '
            'Go thru all FlowLayout controls in the form with the finality of finding the Quote items data and put this into a JSON (serialized) string.
            For Each myPanel As Panel In senderFRM.flpQuoteItems.Controls.OfType(Of Panel)
                Dim myElementHost As ElementHost = myPanel.Controls.OfType(Of ElementHost).FirstOrDefault
                Dim MyUserControl_QuoteItem As UserControl_QuoteItem = TryCast(myElementHost.Child, UserControl_QuoteItem)
                '
                Dim myQuoteItemNumber As String = MyUserControl_QuoteItem.txtItemNumber.Text
                Dim myQuoteItemDescription As String = MyUserControl_QuoteItem.txtItemDescription.Text
                Dim myQuoteItemQty As String = MyUserControl_QuoteItem.txtItemQty.Text
                Dim MyQuoteItemPrice As String = MyUserControl_QuoteItem.txtItemListedCustomerPrice.Text
                '
                'Perhaps not necessary but here to check that all parameters contain data.
                If String.IsNullOrEmpty(myQuoteItemNumber) = False And String.IsNullOrEmpty(myQuoteItemDescription) = False And
                    String.IsNullOrEmpty(myQuoteItemQty) = False And String.IsNullOrEmpty(MyQuoteItemPrice) = False Then
                    'add the data to the list of UserControl_QuoteItem
                    Quote_Items_Info_Data.Add(New JSON_Quote_Item(myQuoteItemNumber, myQuoteItemDescription, MyQuoteItemPrice, myQuoteItemQty))
                End If
            Next
            '
            Dim JSONObject As Object = DBNull.Value
            If Quote_Items_Info_Data IsNot Nothing AndAlso Quote_Items_Info_Data.Count > 0 Then
                '
                'NuGet - Newtonsoft.Json.JsonConvert
                'Return as string, but will keep as an object to be able to use it on the parameterization of the SQL query later!
                JSONObject = JsonConvert.SerializeObject(Quote_Items_Info_Data)
            End If
            '
            Console.WriteLine(JSONObject.ToString)
            'JSONObject is returning an empty JSON Object returning this: [{}] ,  even though Quote_Items_Info_Data was not empty.
            'Why on earth is JsonConvert is not serializing?
            '
            'Code to save to the quote column in the database code goes here if the above ever Works!
        End If
        Return True
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return False
End Function
</code>```

答:
Found the solution!
The problem lies is that the new short form of properties (a one-liner).
Changed:

```<code> Friend Property ItemNumber As String
 Friend Property ItemDescription As String
 Friend Property ItemQty As String
 Friend Property ItemPrice As String
</code>```

To this:

```<code>        Private itemNumber As String
        Public Property _itemNumber() As String
            Get
                Return itemNumber
            End Get
            Set(ByVal value As String)
                itemNumber = value
            End Set
        End Property
        '
        Private ItemDescription As String
        Public Property _ItemDescription() As String
            Get
                Return ItemDescription
            End Get
            Set(ByVal value As String)
                ItemDescription = value
            End Set
        End Property

        Private ItemQty As String
        Public Property _ItemQty() As String
            Get
                Return ItemQty
            End Get
            Set(ByVal value As String)
                ItemQty = value
            End Set
        End Property
        Private ItemPrice As String
        Public Property _ItemPrice() As String
            Get
                Return ItemPrice
            End Get
            Set(ByVal value As String)
                ItemPrice = value
            End Set
        End Property
</code>```

And it all worked!! No getter in the short form?

Body:
I am trying to format Quote items data into a JSON Object to later save to MySQL. the following code produces JSONObject, which is returning an empty JSON object, like this: [{}], even though Quote_Items_Info_Data IS NOT empty. No errors are being triggered!
Why on earth is JsonConvert is not serializing?

Friend Class JSON_Quote_Item
    Friend Property ItemNumber As String
    Friend Property ItemDescription As String
    Friend Property ItemQty As String
    Friend Property ItemPrice As String
    Public Sub New()
    End Sub
    Public Sub New(ByVal _ItemNumber As String, ByVal _ItemDescription As String, ByVal _itemQty As String, ByVal _itemPrice As String)
        ItemNumber = _ItemNumber.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemDescription = _ItemDescription.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemQty = _itemQty.Trim
        ItemPrice = _itemPrice.Trim
    End Sub
End Class
'
'
'''
''' Convert all Quote items to a JSON object on the form and save it to the server DB.
''' senderFRM is the Quote Creator/Editor. Following an example from: https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
''' and https://www.newtonsoft.com/json
'''
''' <param name="senderFRM"></param>
''' <returns></returns>
Friend Function SaveAllQuoteItems(senderFRM As frmQuotesCreatorEditor) As Boolean
    Try
        'make sure I will not run into an exception!
        If senderFRM IsNot Nothing AndAlso String.IsNullOrEmpty(senderFRM.txtQuoteNumber.Text.Trim) = False Then
            Dim QuoteNumber As String = senderFRM.txtQuoteNumber.Text.Trim
            'Holds a list of the custom class JSON_Quote_Item as T and contain all the form quote items data.
            Dim Quote_Items_Info_Data As List(Of JSON_Quote_Item) = New List(Of JSON_Quote_Item)
            '

            '
            'Go thru all FlowLayout controls in the form with the finality of finding the Quote items data and put this into a JSON (serialized) string.
            For Each myPanel As Panel In senderFRM.flpQuoteItems.Controls.OfType(Of Panel)
                Dim myElementHost As ElementHost = myPanel.Controls.OfType(Of ElementHost).FirstOrDefault
                Dim MyUserControl_QuoteItem As UserControl_QuoteItem = TryCast(myElementHost.Child, UserControl_QuoteItem)
                '
                Dim myQuoteItemNumber As String = MyUserControl_QuoteItem.txtItemNumber.Text
                Dim myQuoteItemDescription As String = MyUserControl_QuoteItem.txtItemDescription.Text
                Dim myQuoteItemQty As String = MyUserControl_QuoteItem.txtItemQty.Text
                Dim MyQuoteItemPrice As String = MyUserControl_QuoteItem.txtItemListedCustomerPrice.Text
                '
                'Perhaps not necessary but here to check that all parameters contain data.
                If String.IsNullOrEmpty(myQuoteItemNumber) = False And String.IsNullOrEmpty(myQuoteItemDescription) = False And
                    String.IsNullOrEmpty(myQuoteItemQty) = False And String.IsNullOrEmpty(MyQuoteItemPrice) = False Then
                    'add the data to the list of UserControl_QuoteItem
                    Quote_Items_Info_Data.Add(New JSON_Quote_Item(myQuoteItemNumber, myQuoteItemDescription, MyQuoteItemPrice, myQuoteItemQty))
                End If
            Next
            '
            Dim JSONObject As Object = DBNull.Value
            If Quote_Items_Info_Data IsNot Nothing AndAlso Quote_Items_Info_Data.Count > 0 Then
                '
                'NuGet - Newtonsoft.Json.JsonConvert
                'Return as string, but will keep as an object to be able to use it on the parameterization of the SQL query later!
                JSONObject = JsonConvert.SerializeObject(Quote_Items_Info_Data)
            End If
            '
            Console.WriteLine(JSONObject.ToString)
            'JSONObject is returning an empty JSON Object returning this: [{}] ,  even though Quote_Items_Info_Data was not empty.
            'Why on earth is JsonConvert is not serializing?
            '
            'Code to save to the quote column in the database code goes here if the above ever Works!
        End If
        Return True
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return False
End Function

Body:
Found the solution!
The problem lies is that the new short form of properties (a one-liner).
Changed:

 Friend Property ItemNumber As String
 Friend Property ItemDescription As String
 Friend Property ItemQty As String
 Friend Property ItemPrice As String

To this:

        Private itemNumber As String
        Public Property _itemNumber() As String
            Get
                Return itemNumber
            End Get
            Set(ByVal value As String)
                itemNumber = value
            End Set
        End Property
        '
        Private ItemDescription As String
        Public Property _ItemDescription() As String
            Get
                Return ItemDescription
            End Get
            Set(ByVal value As String)
                ItemDescription = value
            End Set
        End Property

        Private ItemQty As String
        Public Property _ItemQty() As String
            Get
                Return ItemQty
            End Get
            Set(ByVal value As String)
                ItemQty = value
            End Set
        End Property
        Private ItemPrice As String
        Public Property _ItemPrice() As String
            Get
                Return ItemPrice
            End Get
            Set(ByVal value As String)
                ItemPrice = value
            End Set
        End Property

And it all worked!! No getter in the short form?


问:
How can I convert an array of characters to an integer (for 2 or more digits)
The array has to be entered by the user, and not specified in the app itself.

```<code>char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}
</code>```

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

答:
This is technically possible but with limitation. In C++ char size is usually 1 byte (check first comment) while int size is 4 bytes, so the largest value you can store in a char is maximum 255 (check first comment) because 255 is the largest number that can be represented with only 1 byte.

So in the for loop you can use a new int variable to store in it the user input, and then store the bytes in the char variable.
And when trying to get the stored integer cast it to an int like:

```<code>char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    int x = 0;
    cin>>x;
    coeff[i] = (char) x;
    cout<<(int) coeff[0];
}
</code>```

Body:
The array has to be entered by the user, and not specified in the app itself.

char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

Body:
This is technically possible but with limitation. In C++ char size is usually 1 byte (check first comment) while int size is 4 bytes, so the largest value you can store in a char is maximum 255 (check first comment) because 255 is the largest number that can be represented with only 1 byte.

So in the for loop you can use a new int variable to store in it the user input, and then store the bytes in the char variable.
And when trying to get the stored integer cast it to an int like:

char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    int x = 0;
    cin>>x;
    coeff[i] = (char) x;
    cout<<(int) coeff[0];
}


问:
Stopping a poll/voting session if the result is conclusive
Stopping a poll/voting session if the result is conclusive

I'm trying to create an algorithm for stopping a poll/voting session if it has a conclusive result, without waiting for everyone. How many people can vote for a poll is known/defined when creating the poll. Poll question/option count are known as well. Each person can cast one vote for a poll.

For example; a poll defined as

```<code>Maximum votes: 5
Poll options: 3
</code>```

If three people vote for "option 1", we can end the voting session without waiting for the other 2 because nothing can change the result that "option 1" is won. (option 1 will win by 60%, 80% or 100%)

I come up with following:
If (winning option vote count - second place option vote count) > remaining vote count, stop voting

I'm not sure if it is correct and I'd like to ask for validation and/or for a different algorithm.

Some tests:

```<code>Max votes: 6, current votes: 4 as
Option 1: 3
Option 2: 1
Option 3: 0

3 - 1 is NOT greater than 2, so we can't stop the voting.
Validation: remaining 2 people may vote for Option 2, thus changing the result (a tie).

Max votes: 7, current votes: 6 as
Option 1: 4
Option 2: 2
Option 3: 0

4 - 2 > 1, OK so we can stop the voting.
Validation: remaining vote can't change the result, Option 1 already won.
</code>```

Thanks

答:
I think if you take the top 2 voted options and check if the difference is greater than the votes left then it should win. Here's a pseudocode example (assuming the first two options are the most picked):</p>
```<code>if ( (option1 - option2) > (maxVotes - currentVotes) ) {
    endPoll();
}
</code>```

Body:
Stopping a poll/voting session if the result is conclusive

I'm trying to create an algorithm for stopping a poll/voting session if it has a conclusive result, without waiting for everyone. How many people can vote for a poll is known/defined when creating the poll. Poll question/option count are known as well. Each person can cast one vote for a poll.

For example; a poll defined as

Maximum votes: 5
Poll options: 3

If three people vote for "option 1", we can end the voting session without waiting for the other 2 because nothing can change the result that "option 1" is won. (option 1 will win by 60%, 80% or 100%)

I come up with following:
If (winning option vote count - second place option vote count) > remaining vote count, stop voting

I'm not sure if it is correct and I'd like to ask for validation and/or for a different algorithm.

Some tests:

Max votes: 6, current votes: 4 as
Option 1: 3
Option 2: 1
Option 3: 0

3 - 1 is NOT greater than 2, so we can't stop the voting.
Validation: remaining 2 people may vote for Option 2, thus changing the result (a tie).

Max votes: 7, current votes: 6 as
Option 1: 4
Option 2: 2
Option 3: 0

4 - 2 > 1, OK so we can stop the voting.
Validation: remaining vote can't change the result, Option 1 already won.

Thanks

Body:
I think if you take the top 2 voted options and check if the difference is greater than the votes left then it should win. Here's a pseudocode example (assuming the first two options are the most picked):

if ( (option1 - option2) > (maxVotes - currentVotes) ) {
    endPoll();
}


问:
Counter doesn't work when click on Checkbox (JavaScript)
I have a problem with my JavaScript Code...
I'm developing a "ToDo-List", where you can add and remove Elements all of these things are already working but I also like to have an "counter" which shows the number (length) of all unchecked checkboxes.

I have created a button with JS:

```<code>   let btn = document.createElement("button");
   btn.classList.add("destroy");
</code>```

and I already have saved the right place for show the number (length) for the unchecked checkboxes:

```<code>let counter = document.getElementsByClassName("todo-count");
</code>```

and then i wrote code to show me the unclicked boxes:

```<code>for(let btn of buttons) {
                if(btn.classList.contains("destroy")) {
                    btn.addEventListener("click", function() {
                        btn.parentElement.parentElement.remove();

                        for(let counts of counter) {
                            let parsed = parseInt(counts.innerText);
                            counts.innerText = parsed - 1;
                        }

                    })
                }
            }
</code>```

As already mentioned, adding elements already works, but as soon as I add e.g. 5 elements and the first element (which, like all other elements, also has a checkbox) is calculated as minus 5 instead of minus 1...

答:
"...but when I click a checkbox, the counter should subtract by one."

You'll need another event listener for the change event. The change event fires off when the user changes the value of a form control and then clicks elsewhere (which is another event like blur or focusout).

If you haven't already, wrap everything in a <form> so you can use the HTMLFormElement interface. It's very terse and specialized for forms and form controls. Bind your event handler to the form so you can have the advantages Event Delegation will give you like listening for events for an unlimited number of elements whether they are static or dynamically added.

const uncheckedCount = e => {
  const io = e.currentTarget.elements;
  const out = io.out;

  if (e.target.name === 'btn' || e.type === 'change') {
    const unchecked = [...io].filter(inp => inp.checked === false)
    out.value = unchecked.length;
  }
};

const ui = document.forms[0];

ui.addEventListener('change', uncheckedCount);

ui.addEventListener('click', uncheckedCount);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type='checkbox' checked>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <br>

  <button name='btn' type='button'>GO</button>
  <output name='out'></output>
</form></code>```

Body:
I have a problem with my JavaScript Code...
I'm developing a "ToDo-List", where you can add and remove Elements all of these things are already working but I also like to have an "counter" which shows the number (length) of all unchecked checkboxes.

I have created a button with JS:

   let btn = document.createElement("button");
   btn.classList.add("destroy");

and I already have saved the right place for show the number (length) for the unchecked checkboxes:

let counter = document.getElementsByClassName("todo-count");

and then i wrote code to show me the unclicked boxes:

for(let btn of buttons) {
                if(btn.classList.contains("destroy")) {
                    btn.addEventListener("click", function() {
                        btn.parentElement.parentElement.remove();

                        for(let counts of counter) {
                            let parsed = parseInt(counts.innerText);
                            counts.innerText = parsed - 1;
                        }

                    })
                }
            }

As already mentioned, adding elements already works, but as soon as I add e.g. 5 elements and the first element (which, like all other elements, also has a checkbox) is calculated as minus 5 instead of minus 1...

Body:
"...but when I click a checkbox, the counter should subtract by one."

You'll need another event listener for the change event. The change event fires off when the user changes the value of a form control and then clicks elsewhere (which is another event like blur or focusout).

If you haven't already, wrap everything in a <form> so you can use the HTMLFormElement interface. It's very terse and specialized for forms and form controls. Bind your event handler to the form so you can have the advantages Event Delegation will give you like listening for events for an unlimited number of elements whether they are static or dynamically added.

const uncheckedCount = e => {
  const io = e.currentTarget.elements;
  const out = io.out;

  if (e.target.name === 'btn' || e.type === 'change') {
    const unchecked = [...io].filter(inp => inp.checked === false)
    out.value = unchecked.length;
  }
};

const ui = document.forms[0];

ui.addEventListener('change', uncheckedCount);

ui.addEventListener('click', uncheckedCount);

<form>
  <input type='checkbox' checked>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox'>
  <input type='checkbox' checked>
  <br>

  <button name='btn' type='button'>GO</button>
  <output name='out'></output>
</form>


问:
sigaction and ignoring a signal with c in linux environment
I am new to this type of programming, so sorry if my question is trivial.
What I am trying to do is to cause a segmentation fault in my program and instead of exiting the program, I want to handle the signal and continue execution after segmentation fault. I wrote a code that seem to be working, I just want to make sure that this is the way to do this. So here is my code.

```<code>void myhandle(int mysignal, siginfo_t *si, void* arg)
{
  printf("Signal is %d\n",mysignal);

  ucontext_t *context = (ucontext_t *)arg;
  context->uc_mcontext.gregs[REG_RIP]++;
}

int main(int argc, char *argv[])
{
   struct sigaction action;

  action.sa_handler=myhandle;
  sigaction(11,&action,NULL);

  printf("Before segfault\n");

  int *a=NULL;
  int b=*a;

  printf("I am still alive\n");

  return 0;
}
</code>```

Can someone explain to me why the printf inside myhandle runs twice ?
Also is this code ok ?

Thank you.

答:
Not sure if this has been said, but it is NOT SAFE to call printf() from a signal handler, because of its use of malloc().

Please read more to understand what functions are safe from with the signal handling context. On Linux and also on BSD/MacOS, an alternative is to arrange for signal delivery on a special file descriptor-- on Linux, this is done via the signalfd family of functions, and then you can handle the signal in a normal event loop.

Michael Kerrisk's book on Linux is a fantastic reference here.

ContentLicense: CC BY-SA 3.0

Body:
I am new to this type of programming, so sorry if my question is trivial.
What I am trying to do is to cause a segmentation fault in my program and instead of exiting the program, I want to handle the signal and continue execution after segmentation fault. I wrote a code that seem to be working, I just want to make sure that this is the way to do this. So here is my code.

void myhandle(int mysignal, siginfo_t *si, void* arg)
{
  printf("Signal is %d\n",mysignal);

  ucontext_t *context = (ucontext_t *)arg;
  context->uc_mcontext.gregs[REG_RIP]++;
}

int main(int argc, char *argv[])
{
   struct sigaction action;

  action.sa_handler=myhandle;
  sigaction(11,&action,NULL);

  printf("Before segfault\n");

  int *a=NULL;
  int b=*a;

  printf("I am still alive\n");

  return 0;
}

Can someone explain to me why the printf inside myhandle runs twice ?
Also is this code ok ?

Thank you.


问:
Magento 2 commands. setup update let theme disappear
I have Magento 2.
I edit a module and then i try run this command code:

```<code>php -dmemory_limit=5G -f bin/magento setup:upgrade
</code>```

But i after done that site and back-end theme disappear so i have to run this command always:

```<code>php -dmemory_limit=5G -f bin/magento setup:static-content:deploy -f
</code>```

Is it possible to prevent the site from falling down after upgrading a module?

答:
Switch to developer mode in your local repo

bin/magento deploy:mode:set developer

Body:
I have Magento 2.
I edit a module and then i try run this command code:

php -dmemory_limit=5G -f bin/magento setup:upgrade

But i after done that site and back-end theme disappear so i have to run this command always:

php -dmemory_limit=5G -f bin/magento setup:static-content:deploy -f

Is it possible to prevent the site from falling down after upgrading a module?


问:
Git Structure when dealing with clients
Please bear with me. I'm not a git expert so I may be wrong with everything I'm even saying here.

Ok. So I saw a few questions that are similar to this one. However, I feel like mine is different enough to ask here.

We have several microapps that we have created in Github. I feel I took out all of the common parts between the microapps and separated them into a sort of library for all of the microapps to use.

Clients will purchase our microapps but sometimes want them customized in a way that's not as common. However, no matter what there are a majority of files that don't change in each microapp.

I created a repository for each microapp and for the library. I have questions on how to structure the clients' repository.

My current structure is the following:

```<code>MicroApp1
|-- File 1
|-- File 2
|-- File 3

MicroApp2
|-- File 1
|-- File 2
|-- File 3

MicroAppLibrary
|-- File 1
|-- File 2
|-- File 3
</code>```

My first question would be how should I include the library in the main microapp repositories? From my understanding, I should use submodules. I want to be able to update the library repository and merge it to all of the microapp repositories.

My second and deeper question is how I should structure the clients' repositories? The way I'm thinking of doing it is by having one repository for each client. In each repository, I would have directories basically containing the repositories. Like the following (if i don't do the submodule and instead just clone the library every time):

```<code>Client 1
|-- MicroApp1
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroApp2
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroAppLibrary
    |-- File 1
    |-- File 2
    |-- File 3
</code>```

My problem with that is how to update and merge the code to all of my clients' repositories? For example, If I make a change in the main repository of a microapp, how would I push that change to all of my clients' repositories? It doesn't seem like I can merge a repository to a directory. Would I instead use branches? There's quite a few microapps, and I would want a dev and prod branch on each of them as well.

I have many more questions but feel like it'll be too much for one post.

答:
Forget about submodules, use subtree

If GitHub, then each client's MicroApp repo is created as fork of base MicroApp, and all customer-specific customization performed in it, while you can always pull common changes from base

Title: Git Structure when dealing with clients

Body:
Please bear with me. I'm not a git expert so I may be wrong with everything I'm even saying here.

Ok. So I saw a few questions that are similar to this one. However, I feel like mine is different enough to ask here.

We have several microapps that we have created in Github. I feel I took out all of the common parts between the microapps and separated them into a sort of library for all of the microapps to use.

Clients will purchase our microapps but sometimes want them customized in a way that's not as common. However, no matter what there are a majority of files that don't change in each microapp.

I created a repository for each microapp and for the library. I have questions on how to structure the clients' repository.

My current structure is the following:

MicroApp1
|-- File 1
|-- File 2
|-- File 3

MicroApp2
|-- File 1
|-- File 2
|-- File 3

MicroAppLibrary
|-- File 1
|-- File 2
|-- File 3

My first question would be how should I include the library in the main microapp repositories? From my understanding, I should use submodules. I want to be able to update the library repository and merge it to all of the microapp repositories.

My second and deeper question is how I should structure the clients' repositories? The way I'm thinking of doing it is by having one repository for each client. In each repository, I would have directories basically containing the repositories. Like the following (if i don't do the submodule and instead just clone the library every time):

Client 1
|-- MicroApp1
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroApp2
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroAppLibrary
    |-- File 1
    |-- File 2
    |-- File 3

My problem with that is how to update and merge the code to all of my clients' repositories? For example, If I make a change in the main repository of a microapp, how would I push that change to all of my clients' repositories? It doesn't seem like I can merge a repository to a directory. Would I instead use branches? There's quite a few microapps, and I would want a dev and prod branch on each of them as well.

I have many more questions but feel like it'll be too much for one post.


问:
How to get the attachment count when sending email C#
I'm not that good at C# to be honest and I'm trying to create a little app for my job that need to count the number of attachment in the email that the user want to send. I've look in the MS doc and on other StackOverflow's threads but I'm still unable to find something that work for me.

Here's what I have for now, I just need to get the count of attachment of the email:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace OutlookAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
        }

        void Application_ItemSend(object Item, ref bool Cancel)
        {
            MessageBox.Show("You have" + Application_ItemAttached().ToString() + "item(s) attached in this mail");
            Cancel = true;
        }

        public static int Application_ItemAttached(Outlook.MailItem mailitems)
        {
            var attachments = mailitems.Attachments;
            return attachments.Count;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Remarque : Outlook ne déclenche plus cet événement. Si du code
            //    doit s'exécuter à la fermeture d'Outlook (consultez https://go.microsoft.com/fwlink/?LinkId=506785)
        }

        #region Code généré par VSTO

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
</code>```

Thanks for your help!

答:
Does your code actually compile? You already have the function that counts the attachments, but it takes MailItem object as a parameter, and you are not passing anything. Change it to

```<code>MessageBox.Show("You have " + Application_ItemAttached(Item as Outlook.MailItem).ToString() + " item(s) attached in this mail");
</code>```

Body:
I'm not that good at C# to be honest and I'm trying to create a little app for my job that need to count the number of attachment in the email that the user want to send. I've look in the MS doc and on other StackOverflow's threads but I'm still unable to find something that work for me.

Here's what I have for now, I just need to get the count of attachment of the email:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace OutlookAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
        }

        void Application_ItemSend(object Item, ref bool Cancel)
        {
            MessageBox.Show("You have" + Application_ItemAttached().ToString() + "item(s) attached in this mail");
            Cancel = true;
        }

        public static int Application_ItemAttached(Outlook.MailItem mailitems)
        {
            var attachments = mailitems.Attachments;
            return attachments.Count;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Remarque : Outlook ne déclenche plus cet événement. Si du code
            //    doit s'exécuter à la fermeture d'Outlook (consultez https://go.microsoft.com/fwlink/?LinkId=506785)
        }

        #region Code généré par VSTO

        ///
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        ///
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

Thanks for your help!

Body:
Does your code actually compile? You already have the function that counts the attachments, but it takes MailItem object as a parameter, and you are not passing anything. Change it to

MessageBox.Show("You have " + Application_ItemAttached(Item as Outlook.MailItem).ToString() + " item(s) attached in this mail");