问:
Entity Framework + Life Time + StructureMap + Unit Of Work + Windows Forms?
I have a windows service (or a Windows Forms) and when a timer is elapsed, my service completes some tasks.

I don't want to use just one Entity Framework context as long as my app is running.

I saw session factory in NHibernate samples. Is there any thing like that for EF?

Here is how I use EF + StructureMap in my ASP.NET or MVC apps:

Application Start:

```<code>ObjectFactory.Configure(Function(config) config.For(Of IUnitOfWork).HybridHttpOrThreadLocalScoped.Use(Of UnitOfWork)())
</code>```

End Request:

```<code>ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()
</code>```

My UnitOfWork is Started per web request, and is disposed after request is ended.

In my Win App scenario, UoW should start when the timer is elapsed and disposed after my job is complete and I don't want to handle it myself.

How can I achieve something like this in a windows form app?

If I register my UoW using : HybridHttprThreadLocalScoped There is just one UoW per thread and if I dispose it, it's gone.

EDIT:

I have my repositories + services in a dll and I want to use them in both web or win apps, and because of that I used HybridHttpOrThreadLocalScoped.

Update 2:

Here is my Repository:

```<code>Public Class ProductRepository

    Private ReadOnly _databaseFactory As DataAccess.IDatabaseFactory

    Public Sub New(ByVal databaseFactory As DataAccess.IDatabaseFactory)
        _databaseFactory = databaseFactory
    End Sub

    Public Function GetById(ByVal id As Integer) As Product
        Return (From item In _databaseFactory.GetDataContext.Products Where item.ProductId = id).FirstOrDefault
    End Function

End Class
</code>```

and here is my Service:

```<code>Public Class ProductService

    Private ReadOnly _Repository As ProductRepository

    Public Sub New(ByVal repository As ProductRepository)
        _Repository = repository
    End Sub

    Public Function GetById(ByVal id As Integer) As Product
        Return _Repository.GetById(id)
    End Function

End Class
</code>```

And I'm using StructureMap. StructureMap takes car of my DatabaseFactory and UoW lifetime in web scenarios. But I have no idea what to do in win apps. I can manage lifetime of UoW myself, but I'm searching for a way so StructureMap would handle it for me as it handles the lifetime in web apps.

答:
Entity Framework gives you "Context" which is a kind of Session with Scope of Unit Of Work within itself, all operations done for one Context remains in Scope of Context. And Entity Framework implements Unit Of Work pattern already. EF also implements identity map, so for one primary key, you will find only one object referenced everywhere in navigation property.

For Desktop Application, you have to only maintain one Context, that will be scope of all operations and it stores all operations in correct state till you call SaveChanges.

For Web Application, you can put your context in Session of ASP.NET, that may increase the load on server, but it might allow you to store changes for longer duration then just a single page.

I don't want to use just one Entity Framework context as long as my app is running.

What is wrong with one context as long as app is running? Instead it is the correct way to do it. Keeping one context alive does not mean you are keeping connection to database alive. Database connections are opened and closed only while querying and saving changes.

If your app goes little out of balance and causes memory issues, best way would be to just allocate new context and refresh your UI, it will put all old context and its objects into garbage collector and your new context will serve you with lesser memory.

Body:
I have a windows service (or a Windows Forms) and when a timer is elapsed, my service completes some tasks.

I don't want to use just one Entity Framework context as long as my app is running.

I saw session factory in NHibernate samples. Is there any thing like that for EF?

Here is how I use EF + StructureMap in my ASP.NET or MVC apps:

Application Start:

ObjectFactory.Configure(Function(config) config.For(Of IUnitOfWork).HybridHttpOrThreadLocalScoped.Use(Of UnitOfWork)())

End Request:

ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()

My UnitOfWork is Started per web request, and is disposed after request is ended.

In my Win App scenario, UoW should start when the timer is elapsed and disposed after my job is complete and I don't want to handle it myself.

How can I achieve something like this in a windows form app?

If I register my UoW using : HybridHttprThreadLocalScoped There is just one UoW per thread and if I dispose it, it's gone.

EDIT:

I have my repositories + services in a dll and I want to use them in both web or win apps, and because of that I used HybridHttpOrThreadLocalScoped.

Update 2:

Here is my Repository:

Public Class ProductRepository

    Private ReadOnly _databaseFactory As DataAccess.IDatabaseFactory

    Public Sub New(ByVal databaseFactory As DataAccess.IDatabaseFactory)
        _databaseFactory = databaseFactory
    End Sub

    Public Function GetById(ByVal id As Integer) As Product
        Return (From item In _databaseFactory.GetDataContext.Products Where item.ProductId = id).FirstOrDefault
    End Function

End Class

and here is my Service:

Public Class ProductService

    Private ReadOnly _Repository As ProductRepository

    Public Sub New(ByVal repository As ProductRepository)
        _Repository = repository
    End Sub

    Public Function GetById(ByVal id As Integer) As Product
        Return _Repository.GetById(id)
    End Function

End Class

And I'm using StructureMap. StructureMap takes car of my DatabaseFactory and UoW lifetime in web scenarios. But I have no idea what to do in win apps. I can manage lifetime of UoW myself, but I'm searching for a way so StructureMap would handle it for me as it handles the lifetime in web apps.


来源: stackexchange

问:
Return struct after parsing json in Swift
I am writing a function that calls stock exchange api and returns basic data about specific stock. After that I parse the data into my struct, but then I am not able to return this struct when I add the return statement.

This function compiles without any troble and works as expected.

```<code>func getData(symbol: String){

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }
</code>```

But when I add the following code, i get an error saying Unexpected non-void return value in void function

```<code>func getData(symbol: String) -> Stock {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                return stockResult

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }
</code>```

any way i can force it to compile and return my stock struct?

答:
Make your function have a completion parameter, like so:

```<code>func getData(symbol: String, completion: @escaping (Stock?) -> (Void) ) {
    ...
}
</code>```

and invoke that when you've parsed the result

```<code>let stockResult = Stock(...)
completion(stockResult)
</code>```

and in case of an error, call completion(nil)

Generally speaking, don't fight the asynchronous nature of network calls.

ContentLicense: CC BY-SA 4.0

Body:
I am writing a function that calls stock exchange api and returns basic data about specific stock. After that I parse the data into my struct, but then I am not able to return this struct when I add the return statement.

This function compiles without any troble and works as expected.

func getData(symbol: String){

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

But when I add the following code, i get an error saying Unexpected non-void return value in void function

func getData(symbol: String) -> Stock {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                return stockResult

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

any way i can force it to compile and return my stock struct?

Body:
Make your function have a completion parameter, like so:

func getData(symbol: String, completion: @escaping (Stock?) -> (Void) ) {
    ...
}

and invoke that when you've parsed the result

let stockResult = Stock(...)
completion(stockResult)

and in case of an error, call completion(nil)

Generally speaking, don't fight the asynchronous nature of network calls.


问:
SQL DimCalendar dynamic fiscal week for calendar 5-4-4
My aims is to create a 5-4-4 calendar where my Accounting starting period = '2019-04-01' and ending period = '2020-03-31'
 My Fiscal Week should start from Week 1 to Week 52.
 Below is my SQL query which display my accounting calendar

```<code>DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
  CALENDAR_DATE DATE,
  WEEK_NUM INTEGER,
  START_WEEK DATE,
  END_WEEK DATE
)

WHILE @START_DATE <= @END_DATE
BEGIN

SET DATEFIRST 4

INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

SELECT
 @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE) Sunday

SET @START_DATE = DATEADD(day, 1, @START_DATE)
SET @COUNTER = @COUNTER + 1

END

SELECT DISTINCT
  START_WEEK,
  END_WEEK,
  CASE
    WHEN START_WEEK = '2019-04-01' AND END_WEEK = '2019-04-07' THEN 'WEEK 1'
    WHEN START_WEEK = '2019-04-08' AND END_WEEK = '2019-04-14' THEN 'WEEK 2'
    WHEN START_WEEK = '2019-04-15' AND END_WEEK = '2019-04-21' THEN 'WEEK 3'
    WHEN START_WEEK = '2019-04-22' AND END_WEEK = '2019-04-28' THEN 'WEEK 4'
    WHEN START_WEEK = '2019-04-29' AND END_WEEK = '2019-05-05' THEN 'WEEK 5'
    WHEN START_WEEK = '2019-05-06' AND END_WEEK = '2019-05-12' THEN 'WEEK 6'
    WHEN START_WEEK = '2019-05-13' AND END_WEEK = '2019-05-19' THEN 'WEEK 7'
    WHEN START_WEEK = '2019-05-20' AND END_WEEK = '2019-05-26' THEN 'WEEK 8'
    WHEN START_WEEK = '2019-05-27' AND END_WEEK = '2019-06-02' THEN 'WEEK 9'
    WHEN START_WEEK = '2019-06-03' AND END_WEEK = '2019-06-09' THEN 'WEEK 10'
    WHEN START_WEEK = '2019-06-10' AND END_WEEK = '2019-06-16' THEN 'WEEK 11'
    WHEN START_WEEK = '2019-06-17' AND END_WEEK = '2019-06-23' THEN 'WEEK 12'
    WHEN START_WEEK = '2019-06-24' AND END_WEEK = '2019-06-30' THEN 'WEEK 13'
    WHEN START_WEEK = '2019-07-01' AND END_WEEK = '2019-07-07' THEN 'WEEK 14'
    WHEN START_WEEK = '2019-07-08' AND END_WEEK = '2019-07-14' THEN 'WEEK 15'
    WHEN START_WEEK = '2019-07-15' AND END_WEEK = '2019-07-21' THEN 'WEEK 16'
    WHEN START_WEEK = '2019-07-22' AND END_WEEK = '2019-07-28' THEN 'WEEK 17'
    WHEN START_WEEK = '2019-07-29' AND END_WEEK = '2019-08-04' THEN 'WEEK 18'
    WHEN START_WEEK = '2019-08-05' AND END_WEEK = '2019-08-11' THEN 'WEEK 19'
    WHEN START_WEEK = '2019-08-12' AND END_WEEK = '2019-08-18' THEN 'WEEK 20'
    WHEN START_WEEK = '2019-08-19' AND END_WEEK = '2019-08-25' THEN 'WEEK 21'
    WHEN START_WEEK = '2019-08-26' AND END_WEEK = '2019-09-01' THEN 'WEEK 22'
    WHEN START_WEEK = '2019-09-02' AND END_WEEK = '2019-09-08' THEN 'WEEK 23'
    WHEN START_WEEK = '2019-09-09' AND END_WEEK = '2019-09-15' THEN 'WEEK 24'
    WHEN START_WEEK = '2019-09-16' AND END_WEEK = '2019-09-22' THEN 'WEEK 25'
    WHEN START_WEEK = '2019-09-23' AND END_WEEK = '2019-09-29' THEN 'WEEK 26'
    WHEN START_WEEK = '2019-09-30' AND END_WEEK = '2019-10-06' THEN 'WEEK 27'
    WHEN START_WEEK = '2019-10-07' AND END_WEEK = '2019-10-13' THEN 'WEEK 28'
    WHEN START_WEEK = '2019-10-14' AND END_WEEK = '2019-10-20' THEN 'WEEK 29'
    WHEN START_WEEK = '2019-10-21' AND END_WEEK = '2019-10-27' THEN 'WEEK 30'
    WHEN START_WEEK = '2019-10-28' AND END_WEEK = '2019-11-03' THEN 'WEEK 31'
    WHEN START_WEEK = '2019-11-04' AND END_WEEK = '2019-11-10' THEN 'WEEK 32'
    WHEN START_WEEK = '2019-11-11' AND END_WEEK = '2019-11-17' THEN 'WEEK 33'
    WHEN START_WEEK = '2019-11-18' AND END_WEEK = '2019-11-24' THEN 'WEEK 34'
    WHEN START_WEEK = '2019-11-25' AND END_WEEK = '2019-12-01' THEN 'WEEK 35'
    WHEN START_WEEK = '2019-12-02' AND END_WEEK = '2019-12-08' THEN 'WEEK 36'
    WHEN START_WEEK = '2019-12-09' AND END_WEEK = '2019-12-15' THEN 'WEEK 37'
    WHEN START_WEEK = '2019-12-16' AND END_WEEK = '2019-12-22' THEN 'WEEK 38'
    WHEN START_WEEK = '2019-12-23' AND END_WEEK = '2019-12-29' THEN 'WEEK 39'
    WHEN START_WEEK = '2019-12-30' AND END_WEEK = '2020-01-05' THEN 'WEEK 40'
    WHEN START_WEEK = '2020-01-06' AND END_WEEK = '2020-01-12' THEN 'WEEK 41'
    WHEN START_WEEK = '2020-01-13' AND END_WEEK = '2020-01-19' THEN 'WEEK 42'
    WHEN START_WEEK = '2020-01-20' AND END_WEEK = '2020-01-26' THEN 'WEEK 43'
    WHEN START_WEEK = '2020-01-27' AND END_WEEK = '2020-02-02' THEN 'WEEK 44'
    WHEN START_WEEK = '2020-02-03' AND END_WEEK = '2020-02-09' THEN 'WEEK 45'
    WHEN START_WEEK = '2020-02-10' AND END_WEEK = '2020-02-16' THEN 'WEEK 46'
    WHEN START_WEEK = '2020-02-17' AND END_WEEK = '2020-02-23' THEN 'WEEK 47'
    WHEN START_WEEK = '2020-02-24' AND END_WEEK = '2020-03-01' THEN 'WEEK 48'
    WHEN START_WEEK = '2020-03-02' AND END_WEEK = '2020-03-08' THEN 'WEEK 49'
    WHEN START_WEEK = '2020-03-09' AND END_WEEK = '2020-03-15' THEN 'WEEK 50'
    WHEN START_WEEK = '2020-03-16' AND END_WEEK = '2020-03-22' THEN 'WEEK 51'
    WHEN START_WEEK = '2020-03-23' AND END_WEEK = '2020-03-29' THEN 'WEEK 52'
  END AS FY_WEEK
 FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;
</code>```

My problem is the Fiscal Week (FY_WEEK) column, I don't want to hard-code those START_WEEK and END_WEEK value.

I'm looking for a way where I can dynamically populate my fiscal week column instead of hardcoding values.

答:
I did only few changes in your code:

```<code>DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT
SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
 CALENDAR_DATE DATE,WEEK_NUM INTEGER,START_WEEK DATE,
  END_WEEK DATE
  )

 WHILE @START_DATE <= @END_DATE
 BEGIN
 SET DATEFIRST 4
 INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

 SELECT  @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE)
 Sunday
 SET @START_DATE = DATEADD(day, 1, @START_DATE)
 SET @COUNTER = @COUNTER + 1
 END
 select DISTINCT  START_WEEK,  END_WEEK
 into #temp FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;
</code>```

and run

```<code>  `select * ,concat( 'week',ROW_NUMBER() OVER ( ORDER BY START_WEEK)) row_num from
  #temp`
</code>```

Body:
My aims is to create a 5-4-4 calendar where my Accounting starting period = '2019-04-01' and ending period = '2020-03-31'
 My Fiscal Week should start from Week 1 to Week 52.
 Below is my SQL query which display my accounting calendar

DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
  CALENDAR_DATE DATE,
  WEEK_NUM INTEGER,
  START_WEEK DATE,
  END_WEEK DATE
)

WHILE @START_DATE <= @END_DATE
BEGIN

SET DATEFIRST 4

INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

SELECT
 @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE) Sunday

SET @START_DATE = DATEADD(day, 1, @START_DATE)
SET @COUNTER = @COUNTER + 1

END

SELECT DISTINCT
  START_WEEK,
  END_WEEK,
  CASE
    WHEN START_WEEK = '2019-04-01' AND END_WEEK = '2019-04-07' THEN 'WEEK 1'
    WHEN START_WEEK = '2019-04-08' AND END_WEEK = '2019-04-14' THEN 'WEEK 2'
    WHEN START_WEEK = '2019-04-15' AND END_WEEK = '2019-04-21' THEN 'WEEK 3'
    WHEN START_WEEK = '2019-04-22' AND END_WEEK = '2019-04-28' THEN 'WEEK 4'
    WHEN START_WEEK = '2019-04-29' AND END_WEEK = '2019-05-05' THEN 'WEEK 5'
    WHEN START_WEEK = '2019-05-06' AND END_WEEK = '2019-05-12' THEN 'WEEK 6'
    WHEN START_WEEK = '2019-05-13' AND END_WEEK = '2019-05-19' THEN 'WEEK 7'
    WHEN START_WEEK = '2019-05-20' AND END_WEEK = '2019-05-26' THEN 'WEEK 8'
    WHEN START_WEEK = '2019-05-27' AND END_WEEK = '2019-06-02' THEN 'WEEK 9'
    WHEN START_WEEK = '2019-06-03' AND END_WEEK = '2019-06-09' THEN 'WEEK 10'
    WHEN START_WEEK = '2019-06-10' AND END_WEEK = '2019-06-16' THEN 'WEEK 11'
    WHEN START_WEEK = '2019-06-17' AND END_WEEK = '2019-06-23' THEN 'WEEK 12'
    WHEN START_WEEK = '2019-06-24' AND END_WEEK = '2019-06-30' THEN 'WEEK 13'
    WHEN START_WEEK = '2019-07-01' AND END_WEEK = '2019-07-07' THEN 'WEEK 14'
    WHEN START_WEEK = '2019-07-08' AND END_WEEK = '2019-07-14' THEN 'WEEK 15'
    WHEN START_WEEK = '2019-07-15' AND END_WEEK = '2019-07-21' THEN 'WEEK 16'
    WHEN START_WEEK = '2019-07-22' AND END_WEEK = '2019-07-28' THEN 'WEEK 17'
    WHEN START_WEEK = '2019-07-29' AND END_WEEK = '2019-08-04' THEN 'WEEK 18'
    WHEN START_WEEK = '2019-08-05' AND END_WEEK = '2019-08-11' THEN 'WEEK 19'
    WHEN START_WEEK = '2019-08-12' AND END_WEEK = '2019-08-18' THEN 'WEEK 20'
    WHEN START_WEEK = '2019-08-19' AND END_WEEK = '2019-08-25' THEN 'WEEK 21'
    WHEN START_WEEK = '2019-08-26' AND END_WEEK = '2019-09-01' THEN 'WEEK 22'
    WHEN START_WEEK = '2019-09-02' AND END_WEEK = '2019-09-08' THEN 'WEEK 23'
    WHEN START_WEEK = '2019-09-09' AND END_WEEK = '2019-09-15' THEN 'WEEK 24'
    WHEN START_WEEK = '2019-09-16' AND END_WEEK = '2019-09-22' THEN 'WEEK 25'
    WHEN START_WEEK = '2019-09-23' AND END_WEEK = '2019-09-29' THEN 'WEEK 26'
    WHEN START_WEEK = '2019-09-30' AND END_WEEK = '2019-10-06' THEN 'WEEK 27'
    WHEN START_WEEK = '2019-10-07' AND END_WEEK = '2019-10-13' THEN 'WEEK 28'
    WHEN START_WEEK = '2019-10-14' AND END_WEEK = '2019-10-20' THEN 'WEEK 29'
    WHEN START_WEEK = '2019-10-21' AND END_WEEK = '2019-10-27' THEN 'WEEK 30'
    WHEN START_WEEK = '2019-10-28' AND END_WEEK = '2019-11-03' THEN 'WEEK 31'
    WHEN START_WEEK = '2019-11-04' AND END_WEEK = '2019-11-10' THEN 'WEEK 32'
    WHEN START_WEEK = '2019-11-11' AND END_WEEK = '2019-11-17' THEN 'WEEK 33'
    WHEN START_WEEK = '2019-11-18' AND END_WEEK = '2019-11-24' THEN 'WEEK 34'
    WHEN START_WEEK = '2019-11-25' AND END_WEEK = '2019-12-01' THEN 'WEEK 35'
    WHEN START_WEEK = '2019-12-02' AND END_WEEK = '2019-12-08' THEN 'WEEK 36'
    WHEN START_WEEK = '2019-12-09' AND END_WEEK = '2019-12-15' THEN 'WEEK 37'
    WHEN START_WEEK = '2019-12-16' AND END_WEEK = '2019-12-22' THEN 'WEEK 38'
    WHEN START_WEEK = '2019-12-23' AND END_WEEK = '2019-12-29' THEN 'WEEK 39'
    WHEN START_WEEK = '2019-12-30' AND END_WEEK = '2020-01-05' THEN 'WEEK 40'
    WHEN START_WEEK = '2020-01-06' AND END_WEEK = '2020-01-12' THEN 'WEEK 41'
    WHEN START_WEEK = '2020-01-13' AND END_WEEK = '2020-01-19' THEN 'WEEK 42'
    WHEN START_WEEK = '2020-01-20' AND END_WEEK = '2020-01-26' THEN 'WEEK 43'
    WHEN START_WEEK = '2020-01-27' AND END_WEEK = '2020-02-02' THEN 'WEEK 44'
    WHEN START_WEEK = '2020-02-03' AND END_WEEK = '2020-02-09' THEN 'WEEK 45'
    WHEN START_WEEK = '2020-02-10' AND END_WEEK = '2020-02-16' THEN 'WEEK 46'
    WHEN START_WEEK = '2020-02-17' AND END_WEEK = '2020-02-23' THEN 'WEEK 47'
    WHEN START_WEEK = '2020-02-24' AND END_WEEK = '2020-03-01' THEN 'WEEK 48'
    WHEN START_WEEK = '2020-03-02' AND END_WEEK = '2020-03-08' THEN 'WEEK 49'
    WHEN START_WEEK = '2020-03-09' AND END_WEEK = '2020-03-15' THEN 'WEEK 50'
    WHEN START_WEEK = '2020-03-16' AND END_WEEK = '2020-03-22' THEN 'WEEK 51'
    WHEN START_WEEK = '2020-03-23' AND END_WEEK = '2020-03-29' THEN 'WEEK 52'
  END AS FY_WEEK
 FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;

My problem is the Fiscal Week (FY_WEEK) column, I don't want to hard-code those START_WEEK and END_WEEK value.

I'm looking for a way where I can dynamically populate my fiscal week column instead of hardcoding values.

Body:
I did only few changes in your code:

DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT
SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
 CALENDAR_DATE DATE,WEEK_NUM INTEGER,START_WEEK DATE,
  END_WEEK DATE
  )

 WHILE @START_DATE <= @END_DATE
 BEGIN
 SET DATEFIRST 4
 INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

 SELECT  @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE)
 Sunday
 SET @START_DATE = DATEADD(day, 1, @START_DATE)
 SET @COUNTER = @COUNTER + 1
 END
 select DISTINCT  START_WEEK,  END_WEEK
 into #temp FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;

and run

  `select * ,concat( 'week',ROW_NUMBER() OVER ( ORDER BY START_WEEK)) row_num from
  #temp`


答:
Because you have network call in your function, you should use a callback to return data.

func getData(symbol: String, completion: @escaping ((Stock?)-> Void)) {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                // Here return your completion like this
                completion(stockResult)

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }
```

<p>you can call your function like this in your controller or ViewModel :</p>

<pre class="lang-swift prettyprint-override"><code>
getData(symbol: "yoursymbol") { stock in
    // process your stock
}
</code>```

Title: Return struct after parsing json in Swift

Body:
Because you have network call in your function, you should use a callback to return data.

func getData(symbol: String, completion: @escaping ((Stock?)-> Void)) {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                // Here return your completion like this
                completion(stockResult)

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

you can call your function like this in your controller or ViewModel :

getData(symbol: "yoursymbol") { stock in
    // process your stock
}


问:
.NET Model item shows up in Input box but not in link
I have a Url that I want to generate like this:

```<code>@Html.HiddenFor(m=>m.Id)
@Html.TextBoxFor(x=>x.Id)
@{ var cancel = Url.Action("Index", "KeySetting", new { area = "Document"})+"&Id="+@Model.Id; }
</code>```

However, when I load the page, my TextBox is not empty but my url.action is missing the Model.Id value.

I have also tried this:

```<code>@Html.ActionLink("Cancel", "Index", "KeySetting", new { area = "Document", Id = @Model.Id }, new { @class = "btn btn-outline-secondary" })
</code>```

But my Id doesn't appear as well. Why?

EDIT: Route Settings

```<code>        app.UseMvc(routes =>
        {
            routes.MapRoute(
              name: "areas",
              template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

        });
</code>```

答:
Have you made sure to define your view model up top? Sometimes I forget that.

```<code>@model YourViewModelName
</code>```

Also, maybe try this if you want your id as a route value:

```<code>@Html.ActionLink(
    linkText: "Edit",
    actionName: "Index",
    controllerName: "KeySetting",
    routeValues: new { area = "Document", id = @Model.Id },
    htmlAttributes: new { @class = "btn btn-outline-secondary" })
</code>```

If you want a query string parameter like ?queryparam=yourmodelid

Try something like this:

```<code><a href="@Url.Action("Index", "KeySetting", new { Area = "Document" })?id=@Model.Id" class="btn btn-outline-secondary">Edit</a>
</code>```

Body:
I have a Url that I want to generate like this:

@Html.HiddenFor(m=>m.Id)
@Html.TextBoxFor(x=>x.Id)
@{ var cancel = Url.Action("Index", "KeySetting", new { area = "Document"})+"&Id="+@Model.Id; }

However, when I load the page, my TextBox is not empty but my url.action is missing the Model.Id value.

I have also tried this:

@Html.ActionLink("Cancel", "Index", "KeySetting", new { area = "Document", Id = @Model.Id }, new { @class = "btn btn-outline-secondary" })

But my Id doesn't appear as well. Why?

EDIT: Route Settings

        app.UseMvc(routes =>
        {
            routes.MapRoute(
              name: "areas",
              template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

        });

Body:
Have you made sure to define your view model up top? Sometimes I forget that.

@model YourViewModelName

Also, maybe try this if you want your id as a route value:

@Html.ActionLink(
    linkText: "Edit",
    actionName: "Index",
    controllerName: "KeySetting",
    routeValues: new { area = "Document", id = @Model.Id },
    htmlAttributes: new { @class = "btn btn-outline-secondary" })

If you want a query string parameter like ?queryparam=yourmodelid

Try something like this:

<a href="@Url.Action("Index", "KeySetting", new { Area = "Document" })?id=@Model.Id" class="btn btn-outline-secondary">Edit</a>


问:
integrated Rest API (json) BPMN with React or Angular 8 & typescript ready
i need a angular or react bpmn library with typescript and rest api service not xml or any thing else. also dont wana pars xml to json.

search a lot about that but I see lot of limitations and cant find bpmn library with json service.

i need to make a workflow like this with react or angular
  that communicate via json with back-end and typescript ready.

Has anyone experience about this?

答:
You could use NestJS and bpmn-engine together. These are server-side technologies.

I don't think you'll find an angular or react library that does this, because these are primarily client-side view rendering libraries.


问:
recursive method that checks if a string is palindrome in java
the input: "mnkknm" where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it's a homework

```<code>public static int PalindromeCheck(String x , int n)
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}
</code>```

答:
try this method please </p>

```<code>public static boolean isPal(String s)
{
    if(s.length() == 0 || s.length() == 1) {
        return true;
    }
    if(s.charAt(0) == s.charAt(s.length()-1)) {

        return isPal(s.substring(1, s.length() - 1));
    }
    return false;
}
</code>```

Body:
the input: "mnkknm" where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it's a homework

public static int PalindromeCheck(String x , int n)
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}

Body:
try this method please

public static boolean isPal(String s)
{
    if(s.length() == 0 || s.length() == 1) {
        return true;
    }
    if(s.charAt(0) == s.charAt(s.length()-1)) {

        return isPal(s.substring(1, s.length() - 1));
    }
    return false;
}


问:
Get associations when using getModel on another model sequelize
I would like include team association when getting teams by my user instance. I could not find way to do it.

```<code>const userTeams = await user.getTeams({
      joinTableAttributes: []
});
</code>```

I tried do it by passing "include" like:

```<code>const userTeams = await user.getTeams({
    joinTableAttributes: [],
    include: { model: Board, as: 'boards', through: { attributes: [] } }
});
</code>```

答:
You need to define the association for user and team before calling the getTeams method on User model.

E.g.

index.ts:

import { sequelize } from '../../db';
import { Model, DataTypes, HasManyGetAssociationsMixin } from 'sequelize';

class User extends Model {
  public getTeams!: HasManyGetAssociationsMixin<Team>;
}
User.init({}, { sequelize, modelName: 'user' });

class Team extends Model {}
Team.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'team' },
);

User.hasMany(Team);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    const user = await User.create({ teams: [{ name: 'Bull' }, { name: 'Thunder' }] }, { include: [Team] });
    const teams = await user.getTeams();
    const teamDataValues = teams.map((team) => team.dataValues);
    console.log('teamDataValues: ', teamDataValues);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();
```

<p>Execution result:</p>

<pre class="lang-sh prettyprint-override"><code>{ POSTGRES_HOST: '127.0.0.1',
  POSTGRES_PORT: '5430',
  POSTGRES_PASSWORD: 'testpass',
  POSTGRES_USER: 'testuser',
  POSTGRES_DB: 'node-sequelize-examples' }
Executing (default): DROP TABLE IF EXISTS "team" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "user" ("id"   SERIAL , PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'user' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "team" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "team" ("id"   SERIAL , "name" VARCHAR(255), "userId" INTEGER REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'team' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "user" ("id") VALUES (DEFAULT) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): SELECT "id", "name", "userId" FROM "team" AS "team" WHERE "team"."userId" = 1;
teamDataValues:  [ { id: 1, name: 'Bull', userId: 1 },
  { id: 2, name: 'Thunder', userId: 1 } ]
</code>```

Check the data records in the database:

node-sequelize-examples=# select * from "user";
 id
----
  1
(1 row)

node-sequelize-examples=# select * from "team";
 id |  name   | userId
----+---------+--------
  1 | Bull    |      1
  2 | Thunder |      1
(2 rows)
```

Body:
I would like include team association when getting teams by my user instance. I could not find way to do it.

const userTeams = await user.getTeams({
      joinTableAttributes: []
});

I tried do it by passing "include" like:

const userTeams = await user.getTeams({
    joinTableAttributes: [],
    include: { model: Board, as: 'boards', through: { attributes: [] } }
});

Body:
You need to define the association for user and team before calling the getTeams method on User model.

E.g.

index.ts:

import { sequelize } from '../../db';
import { Model, DataTypes, HasManyGetAssociationsMixin } from 'sequelize';

class User extends Model {
  public getTeams!: HasManyGetAssociationsMixin<Team>;
}
User.init({}, { sequelize, modelName: 'user' });

class Team extends Model {}
Team.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'team' },
);

User.hasMany(Team);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    const user = await User.create({ teams: [{ name: 'Bull' }, { name: 'Thunder' }] }, { include: [Team] });
    const teams = await user.getTeams();
    const teamDataValues = teams.map((team) => team.dataValues);
    console.log('teamDataValues: ', teamDataValues);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

Execution result:

{ POSTGRES_HOST: '127.0.0.1',
  POSTGRES_PORT: '5430',
  POSTGRES_PASSWORD: 'testpass',
  POSTGRES_USER: 'testuser',
  POSTGRES_DB: 'node-sequelize-examples' }
Executing (default): DROP TABLE IF EXISTS "team" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "user" ("id"   SERIAL , PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'user' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "team" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "team" ("id"   SERIAL , "name" VARCHAR(255), "userId" INTEGER REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'team' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "user" ("id") VALUES (DEFAULT) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): SELECT "id", "name", "userId" FROM "team" AS "team" WHERE "team"."userId" = 1;
teamDataValues:  [ { id: 1, name: 'Bull', userId: 1 },
  { id: 2, name: 'Thunder', userId: 1 } ]

Check the data records in the database:

node-sequelize-examples=# select * from "user";
 id
----
  1
(1 row)

node-sequelize-examples=# select * from "team";
 id |  name   | userId
----+---------+--------
  1 | Bull    |      1
  2 | Thunder |      1
(2 rows)


问:
Enable Live metrics stream for Azure Application Insights
I'm monitoring an on-prem IIS web app using Azure application insights, but when I check Live metrics stream, I can note that it does not work as shown in the following

As a result, I tried to install Microsoft.ApplicationInsights nugget using the following PowerShell Cmdlet:

```<code>Install-Package Microsoft.ApplicationInsights -Version 2.7.1
</code>```

But unfortunately, it does not work and I get the following error:

```<code>Install-Package : A parameter cannot be found that matches parameter name 'Version'.
</code>```

Considering that the version already exists and I've tried it with other versions.

答: Install Microsoft.ApplicationInsights.AspNetCore package in your application and you should be able to see the AppInsights in Live Metrics Stream.</p>

Body:
I'm monitoring an on-prem IIS web app using Azure application insights, but when I check Live metrics stream, I can note that it does not work as shown in the following

As a result, I tried to install Microsoft.ApplicationInsights nugget using the following PowerShell Cmdlet:

Install-Package Microsoft.ApplicationInsights -Version 2.7.1

But unfortunately, it does not work and I get the following error:

Install-Package : A parameter cannot be found that matches parameter name 'Version'.

Considering that the version already exists and I've tried it with other versions.


问:
Java 11: Implementation of JAXB-API has not been found on module path or classpath
I have a little project which does throw an exception when i let it run.

The problem is here (TestObject.java):

```<code>final JAXBContext jaxbContext = JAXBContext.newInstance(...);
</code>```

I really do not understand why this throws the exception. I also created a test which works like a charm (TestTest.java). Please forgive me the names, but this is just a small test application to get this working with java 11.

I followed this: javax.xml.bind.JAXBException Implementation of JAXB-API has not been found on module path or classpath
and added

```<code>compile('javax.xml.bind:jaxb-api:2.3.0')
compile('javax.activation:activation:1.1')
compile('org.glassfish.jaxb:jaxb-runtime:2.3.0')
</code>```

to my build.gradle but then it complains that

```<code>Error:java: module not found: java.activation
</code>```

is missing. As this is also removed from Java 11 i added:

```<code>compile 'com.sun.activation:javax.activation:1.2.0'
</code>```

but then it throws a lot of errors:

```<code>Error:java: the unnamed module reads package com.sun.xml.bind from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.util from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.marshaller from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.api from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2 from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.util from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.model.impl from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.model.annotation from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.runtime from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.runtime.unmarshaller from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.unmarshaller from both jaxb.runtime and jaxb.core
Error:java: module jaxb.runtime reads package com.sun.xml.bind from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.util from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.marshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.api from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2 from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.util from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.model.impl from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.model.annotation from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.runtime from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.runtime.unmarshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.unmarshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.core reads package com.sun.xml.bind from both jaxb.core and jaxb.runtime
</code>```

What is so confusing to me: the test works. So it seems like there is some kind of jaxb-implementation in the junit5 environment.
I also found some other information in how to migrate a java 8 app to java 9 modules, where i found this:

```<code>compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.4.0-b180830.0359'
compile group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.4.0-b180830.0438'
compile group: 'org.glassfish.jaxb', name: 'jaxb-xjc', version: '2.4.0-b180830.0438'
</code>```

But this is also not working. I would be very happy if someone can help me to get that running.
I use java-openjdk-11.0.1.13-11.rolling.fc29.x86_64 on Fedora 29, 64 bit.

ps.: i wanted to write all that into the comment of the post with topic "javax.xml.bind.JAXBException..." but i was not allowed to do so. So i created this new post.

edit: the exception which is thrown in that sample application is this:

```<code>Exception in thread "main" java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
    at test/com.example.TestObject.doSomething(TestObject.java:21)
    at test/com.example.TestObject.main(TestObject.java:12)
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
    at java.xml.bind/javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:269)
    at java.xml.bind/javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
    at java.xml.bind/javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at java.xml.bind/javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at test/com.example.TestObject.doSomething(TestObject.java:17)
    ... 1 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.xml.bind/javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
    at java.xml.bind/javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
    at java.xml.bind/javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:267)
    ... 5 more
</code>```

答:
I believe java.lang.ClassNotFoundException is coming because of multiple versions not able to define definition.

Solution: delete com.sun.xml folder from your local m2 repository, and download only one dependency.

javax.xml.bind:jaxb-api:"latest-version" in pom/gradle.

Body:
I have a little project which does throw an exception when i let it run.

The problem is here (TestObject.java):

final JAXBContext jaxbContext = JAXBContext.newInstance(...);

I really do not understand why this throws the exception. I also created a test which works like a charm (TestTest.java). Please forgive me the names, but this is just a small test application to get this working with java 11.

I followed this: javax.xml.bind.JAXBException Implementation of JAXB-API has not been found on module path or classpath
and added

compile('javax.xml.bind:jaxb-api:2.3.0')
compile('javax.activation:activation:1.1')
compile('org.glassfish.jaxb:jaxb-runtime:2.3.0')

to my build.gradle but then it complains that

Error:java: module not found: java.activation

is missing. As this is also removed from Java 11 i added:

compile 'com.sun.activation:javax.activation:1.2.0'

but then it throws a lot of errors:

Error:java: the unnamed module reads package com.sun.xml.bind from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.util from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.marshaller from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.api from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2 from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.util from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.model.impl from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.model.annotation from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.runtime from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.v2.runtime.unmarshaller from both jaxb.runtime and jaxb.core
Error:java: the unnamed module reads package com.sun.xml.bind.unmarshaller from both jaxb.runtime and jaxb.core
Error:java: module jaxb.runtime reads package com.sun.xml.bind from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.util from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.marshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.api from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2 from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.util from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.model.impl from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.model.annotation from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.runtime from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.v2.runtime.unmarshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.runtime reads package com.sun.xml.bind.unmarshaller from both jaxb.core and jaxb.runtime
Error:java: module jaxb.core reads package com.sun.xml.bind from both jaxb.core and jaxb.runtime

What is so confusing to me: the test works. So it seems like there is some kind of jaxb-implementation in the junit5 environment.
I also found some other information in how to migrate a java 8 app to java 9 modules, where i found this:

compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.4.0-b180830.0359'
compile group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.4.0-b180830.0438'
compile group: 'org.glassfish.jaxb', name: 'jaxb-xjc', version: '2.4.0-b180830.0438'

But this is also not working. I would be very happy if someone can help me to get that running.
I use java-openjdk-11.0.1.13-11.rolling.fc29.x86_64 on Fedora 29, 64 bit.

ps.: i wanted to write all that into the comment of the post with topic "javax.xml.bind.JAXBException..." but i was not allowed to do so. So i created this new post.

edit: the exception which is thrown in that sample application is this:

Exception in thread "main" java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
    at test/com.example.TestObject.doSomething(TestObject.java:21)
    at test/com.example.TestObject.main(TestObject.java:12)
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
    at java.xml.bind/javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:269)
    at java.xml.bind/javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
    at java.xml.bind/javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at java.xml.bind/javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at test/com.example.TestObject.doSomething(TestObject.java:17)
    ... 1 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.xml.bind/javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
    at java.xml.bind/javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
    at java.xml.bind/javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:267)
    ... 5 more


问:
How to disable button in React.js
I have this component:

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

export default class AddItem extends React.Component {

add() {
    this.props.onButtonClick(this.input.value);
    this.input.value = '';
}

render() {
    return (
        <div className="add-item">
            <input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
            <button disabled={!this.input.value} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
        </div>
    );
}

}
</code>```

I want the button to be disabled when input value is empty. But the code above doesn't work. It says:

add-item.component.js:78 Uncaught TypeError: Cannot read property 'value' of undefined

pointing to disabled={!this.input.value}. What can I be doing wrong  here? I'm guessing that perhaps ref isn't created yet when render method is executed. If, so what is the workararound?

答:
In HTML,

<button disabled/>
<button disabled="true">
<button disabled="false">
<button disabled="21">
```
<p>All of them boils down to <code>disabled="true"</code> that is because it returns <code>true</code> for a non-empty string.
Hence, in order to return <code>false</code>, pass a empty string in a conditional statement like <code>this.input.value ? "true" : ""</code>.</p>
```render() {
    return (

            <input
                type="text"
                className="add-item__input"
                ref={(input) => this.input = input}
                placeholder={this.props.placeholder}
            />
            <button
                disabled={this.input.value ? "true" : ""}
                className="add-item__button"
                onClick={this.add.bind(this)}
            >
                Add
            </button>

    );
}
```

ContentLicense: CC BY-SA 3.0

Title: How to disable button in React.js

Body:
I have this component:

import React from 'react';

export default class AddItem extends React.Component {

add() {
    this.props.onButtonClick(this.input.value);
    this.input.value = '';
}

render() {
    return (

            <input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
            <button disabled={!this.input.value} className="add-item__button" onClick={this.add.bind(this)}>Add</button>

    );
}

}

I want the button to be disabled when input value is empty. But the code above doesn't work. It says:

add-item.component.js:78 Uncaught TypeError: Cannot read property 'value' of undefined

pointing to disabled={!this.input.value}. What can I be doing wrong  here? I'm guessing that perhaps ref isn't created yet when render method is executed. If, so what is the workararound?

Body:
In HTML,

<button disabled/>
<button disabled="true">
<button disabled="false">
<button disabled="21">

All of them boils down to disabled="true" that is because it returns true for a non-empty string.
Hence, in order to return false, pass a empty string in a conditional statement like this.input.value ? "true" : "".

render() {
    return (
        <div className="add-item">
            <input
                type="text"
                className="add-item__input"
                ref={(input) => this.input = input}
                placeholder={this.props.placeholder}
            />
            <button
                disabled={this.input.value ? "true" : ""}
                className="add-item__button"
                onClick={this.add.bind(this)}
            >
                Add
            </button>
        </div>
    );
}


问:
Spark dataFrame for-if loop taking a Long time
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

```<code>val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}
</code>```

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

Body:
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

Body:
scala> import org.apache.spark.sql.expressions.Window

scala> df.show(false)
+----------+--------+--------+
|start_time|end_time|words   |
+----------+--------+--------+
|132       |135     |Hi      |
|135       |135     |,       |
|143       |152     |I       |
|151       |152     |am      |
|159       |169     |working |
|194       |197     |on      |
|204       |211     |hadoop  |
|211       |211     |.       |
|218       |222     |This    |
|226       |229     |is      |
|234       |239     |Spark   |
|245       |249     |DF      |
|253       |258     |coding  |
|258       |258     |.       |
|276       |276     |I       |
+----------+--------+--------+

scala> val w = Window.orderBy("start_time", "end_time")

scala> df.withColumn("temp", sum(when(lag(col("words"), 1).over(w) === ".", lit(1)).otherwise(lit(0))).over(w))
             .groupBy("temp").agg(min("start_time").alias("start_time"), max("end_time").alias("end_time"),concat_ws(" ",collect_list(trim(col("words")))).alias("sentenses"))
             .drop("temp")
             .show(false)
+----------+--------+-----------------------------+
|start_time|end_time|sentenses                    |
+----------+--------+-----------------------------+
|132       |211     |Hi , I am working on hadoop .|
|218       |258     |This is Spark DF coding .    |
|276       |276     |I                            |
+----------+--------+-----------------------------+


答:
I found the solution. You have to add a closure and then use it when calling the function.

```<code>func getData(symbol: String, completion: @escaping (Stock) -> Void) {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                completionBlock(stockResult)

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }
</code>```

then in the main you call

```<code>getData(symbol: "aapl") {(output) in
            print(output)
}
</code>```

Body:
I am writing a function that calls stock exchange api and returns basic data about specific stock. After that I parse the data into my struct, but then I am not able to return this struct when I add the return statement.

This function compiles without any troble and works as expected.

func getData(symbol: String){

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

But when I add the following code, i get an error saying Unexpected non-void return value in void function

func getData(symbol: String) -> Stock {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                return stockResult

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

any way i can force it to compile and return my stock struct?

Body:
I found the solution. You have to add a closure and then use it when calling the function.

func getData(symbol: String, completion: @escaping (Stock) -> Void) {

        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                completionBlock(stockResult)

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

then in the main you call

getData(symbol: "aapl") {(output) in
            print(output)
}


问:
Invoking soap web service via spring boot fails with Un-authorized 401 exception
I am trying to invoke a secured soap web service via spring boot application.

However, when I am trying to do so, I keep getting the following exception always despite passing the required credentials.

```<code>{
    "timestamp": "2020-02-02T17:17:09.081+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Unauthorized [401]",
    "trace": "org.springframework.ws.client.WebServiceTransportException: Unauthorized [401]\n\tat org.springframework.ws.client.core.WebServiceTemplate.handleError(WebServiceTemplate.java:699)\n\tat org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:609)\n\tat org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)\n\tat org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)\n\tat org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)\n\tat com.app.oracle.doo.ominvoker.client.SoapClient.createOrder(SoapClient.java:30)\n\tat com.app.oracle.doo.ominvoker.controller.OrderImportController.createOrder(OrderImportController.java:55)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.lang.Thread.run(Thread.java:748)\n",
    "path": "/createOrder"
}
</code>```

I have been able to invoke the same webservice via SOAP tool by providing the same credentials.
I am not sure of the right way to pass the soap header information with the credentials to invoke the webservice.

I referred many threads and found the following way to implement it. However, it still does not work for me.

Any help in this regard would be highly appreciated.

One more point is that while invoking the service via soap tool, I have also set the domain information as oracle/wss11_username_token_with_message_protection_client_policy.

I did not know how to pass this information so set it as one of the property in Connection Request (set in Authentication.java file as mentioned below)

Thanks

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.13.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <args>
                        <arg>-XautoNameResolution</arg>
                    </args>
                    <generatePackage>com.app.oracle.doo.ominvoker.soap.api.orderimport</generatePackage>
                    <generateDirectory>${project.basedir}/src/main/java</generateDirectory>
                    <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
                    <schemaIncludes>
                        <include>*.wsdl</include>
                    </schemaIncludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

SoapConfig.java

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

import com.app.oracle.doo.ominvoker.client.SoapClient;

@Configuration
public class SoapConfig {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan("com.app.oracle.doo.ominvoker.soap.api.orderimport");
        return marshaller;
    }

    @Bean
    public SoapClient orderImportClient(Jaxb2Marshaller marshaller) {
        SoapClient client = new SoapClient();
        client.setDefaultUri("https://host:port/order/OrderServices");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        client.setMessageSender(new Authentication("Manager", "Welcome1"));
        return client;
    }

}
</code>```

SoapClient.java

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

import com.app.oracle.doo.ominvoker.soap.api.orderimport.CreateOrders;
import com.app.oracle.doo.ominvoker.soap.api.orderimport.CreateOrdersResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class SoapClient extends WebServiceGatewaySupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class);

    @Autowired
    private Jaxb2Marshaller marshaller;

    private WebServiceTemplate template;

    public CreateOrdersResponse createOrder(CreateOrders request) {
        template = new WebServiceTemplate(marshaller);
        return (CreateOrdersResponse) template.marshalSendAndReceive("https://host:port/order/OrderServices", request);
    }

}
</code>```

Authentication.java

```<code>package com.app.oracle.doo.ominvoker.config;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Base64;

import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender;

public class Authentication extends HttpUrlConnectionMessageSender {

    private String username;

    private String password;

    public Authentication() {
    }

    public Authentication(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    protected void prepareConnection(HttpURLConnection connection) throws IOException {
       String userpassword = username+":"+password;
       String encoded = Base64.getEncoder().withoutPadding().encodeToString(userpassword.getBytes());
       connection.setRequestProperty("Authorization", "Basic " + encoded);
       connection.setRequestProperty("domain", "oracle/wss11_username_token_with_message_protection_client_policy");
       super.prepareConnection(connection);
   }

}
</code>```

答:
Isn't your WS secured by WS-Security .
Instead of: HttpUrlConnectionMessageSender you should define: org.springframework.ws.soap.security.wss4j2.Wss4jSecurityInterceptor

```<code>@Bean
    public Wss4jSecurityInterceptor securityInterceptor(){
        Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
        wss4jSecurityInterceptor.setSecurementActions("Timestamp UsernameToken");
        wss4jSecurityInterceptor.setSecurementUsername("Manager");
        wss4jSecurityInterceptor.setSecurementPassword("Welcome1");
        return wss4jSecurityInterceptor;
    }
</code>```

And then inject it, into your Soap Client:

```<code>    ClientInterceptor[] interceptors = new ClientInterceptor[] {securityInterceptor()};
    client.setInterceptors(interceptors);
</code>```

Body:
I am trying to invoke a secured soap web service via spring boot application.

However, when I am trying to do so, I keep getting the following exception always despite passing the required credentials.

{
    "timestamp": "2020-02-02T17:17:09.081+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Unauthorized [401]",
    "trace": "org.springframework.ws.client.WebServiceTransportException: Unauthorized [401]\n\tat org.springframework.ws.client.core.WebServiceTemplate.handleError(WebServiceTemplate.java:699)\n\tat org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:609)\n\tat org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)\n\tat org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)\n\tat org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)\n\tat com.app.oracle.doo.ominvoker.client.SoapClient.createOrder(SoapClient.java:30)\n\tat com.app.oracle.doo.ominvoker.controller.OrderImportController.createOrder(OrderImportController.java:55)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.lang.Thread.run(Thread.java:748)\n",
    "path": "/createOrder"
}

I have been able to invoke the same webservice via SOAP tool by providing the same credentials.
I am not sure of the right way to pass the soap header information with the credentials to invoke the webservice.

I referred many threads and found the following way to implement it. However, it still does not work for me.

Any help in this regard would be highly appreciated.

One more point is that while invoking the service via soap tool, I have also set the domain information as oracle/wss11_username_token_with_message_protection_client_policy.

I did not know how to pass this information so set it as one of the property in Connection Request (set in Authentication.java file as mentioned below)

Thanks

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.13.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <args>
                        <arg>-XautoNameResolution</arg>
                    </args>
                    <generatePackage>com.app.oracle.doo.ominvoker.soap.api.orderimport</generatePackage>
                    <generateDirectory>${project.basedir}/src/main/java</generateDirectory>
                    <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
                    <schemaIncludes>
                        <include>*.wsdl</include>
                    </schemaIncludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

SoapConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

import com.app.oracle.doo.ominvoker.client.SoapClient;

@Configuration
public class SoapConfig {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan("com.app.oracle.doo.ominvoker.soap.api.orderimport");
        return marshaller;
    }

    @Bean
    public SoapClient orderImportClient(Jaxb2Marshaller marshaller) {
        SoapClient client = new SoapClient();
        client.setDefaultUri("https://host:port/order/OrderServices");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        client.setMessageSender(new Authentication("Manager", "Welcome1"));
        return client;
    }

}

SoapClient.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

import com.app.oracle.doo.ominvoker.soap.api.orderimport.CreateOrders;
import com.app.oracle.doo.ominvoker.soap.api.orderimport.CreateOrdersResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class SoapClient extends WebServiceGatewaySupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class);

    @Autowired
    private Jaxb2Marshaller marshaller;

    private WebServiceTemplate template;

    public CreateOrdersResponse createOrder(CreateOrders request) {
        template = new WebServiceTemplate(marshaller);
        return (CreateOrdersResponse) template.marshalSendAndReceive("https://host:port/order/OrderServices", request);
    }

}

Authentication.java

package com.app.oracle.doo.ominvoker.config;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Base64;

import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender;

public class Authentication extends HttpUrlConnectionMessageSender {

    private String username;

    private String password;

    public Authentication() {
    }

    public Authentication(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    protected void prepareConnection(HttpURLConnection connection) throws IOException {
       String userpassword = username+":"+password;
       String encoded = Base64.getEncoder().withoutPadding().encodeToString(userpassword.getBytes());
       connection.setRequestProperty("Authorization", "Basic " + encoded);
       connection.setRequestProperty("domain", "oracle/wss11_username_token_with_message_protection_client_policy");
       super.prepareConnection(connection);
   }

}

Body:
Isn't your WS secured by WS-Security .
Instead of: HttpUrlConnectionMessageSender you should define: org.springframework.ws.soap.security.wss4j2.Wss4jSecurityInterceptor

@Bean
    public Wss4jSecurityInterceptor securityInterceptor(){
        Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
        wss4jSecurityInterceptor.setSecurementActions("Timestamp UsernameToken");
        wss4jSecurityInterceptor.setSecurementUsername("Manager");
        wss4jSecurityInterceptor.setSecurementPassword("Welcome1");
        return wss4jSecurityInterceptor;
    }

And then inject it, into your Soap Client:

    ClientInterceptor[] interceptors = new ClientInterceptor[] {securityInterceptor()};
    client.setInterceptors(interceptors);


问:
When i tried to send mail using phpmailer, i am getting error
Could not instantiate mail function.

Message couldnot be sentMailer Error: Could not instantiate mail function.

```<code>require 'PHPMailer/PHPMailerAutoload.php';
$mail =new PHPMailer;
$mail->HOST ='localhost';
$mail->PORT = 25;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = 'Username';
$mail->Password = 'Pass';
$mail->setFrom('info@zoeticpolymers.com');
$mail->addAddress('nitesh54546@gmail.com','Nitesh');
$mail->AddReplyTo("info@zoeticpolymers.com");
$mail->isHTMl(true);
$mail->Subject = 'PHP Mailer Subject';
$mail->Body = '<h1>You are Welcome Here.....</h1>';
if(!$mail->send()){
    echo 'Message couldnot be sent';
     echo 'Mailer Error: ' . $mail->ErrorInfo; die;
}else{
    echo 'Message has been sent'; die;
}
</code>```

答:
Your Mistake: You used HOST as Localhost it's SMTP.mail.com change mail to your server

You are using older version of PHPMailer also let me help you by typing the correct one

You should download from PHPMailer GitHub
Not vendor for this example

```<code>use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';     //for Gmail
    $mail->SMTPAuth   = true;

    $mail->Username   = 'user@gmail.com';
    $mail->Password   = 'your Gmail pass';

    $mail->Port       = 587;                                    // TCP port

    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');

    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}```

**Your error was that you used HOST as localhost and older version of PHPMailer.

But use default mail() but change the PHP version to 7.3 since it's better now.**
```

Body:
Could not instantiate mail function.

Message couldnot be sentMailer Error: Could not instantiate mail function.

require 'PHPMailer/PHPMailerAutoload.php';
$mail =new PHPMailer;
$mail->HOST ='localhost';
$mail->PORT = 25;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = 'Username';
$mail->Password = 'Pass';
$mail->setFrom('info@zoeticpolymers.com');
$mail->addAddress('nitesh54546@gmail.com','Nitesh');
$mail->AddReplyTo("info@zoeticpolymers.com");
$mail->isHTMl(true);
$mail->Subject = 'PHP Mailer Subject';
$mail->Body = '
You are Welcome Here.....
';
if(!$mail->send()){
    echo 'Message couldnot be sent';
     echo 'Mailer Error: ' . $mail->ErrorInfo; die;
}else{
    echo 'Message has been sent'; die;
}

Body:
Your Mistake: You used HOST as Localhost it's SMTP.mail.com change mail to your server

You are using older version of PHPMailer also let me help you by typing the correct one

You should download from PHPMailer GitHub
Not vendor for this example

use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';     //for Gmail
    $mail->SMTPAuth   = true;

    $mail->Username   = 'user@gmail.com';
    $mail->Password   = 'your Gmail pass';

    $mail->Port       = 587;                                    // TCP port

    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');

    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}```

**Your error was that you used HOST as localhost and older version of PHPMailer.

But use default mail() but change the PHP version to 7.3 since it's better now.**


问:
How to know the Type of a Property if it is collection in Reflection?
```<code>List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;
</code>```

Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.

If i try to get the Type of property using GetType like ,

```<code>      Type t = obj.GetType();
</code>```

It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.

I also tried the way like

```<code>        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }
</code>```

But it is returning error because of the Value of the collection property is null so we cant get the Type.

In this situation how can i get the Type of a collection Property.

Please help me !

Thanks in Advance.

答:
Use propertyInfo.PropertyType which has property with name IsGenericType, e.g.:

```<code>if (propertyInfo.PropertyType.IsGenericType)
{
    // code ...
}
</code>```

Body:
List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.

If i try to get the Type of property using GetType like ,

      Type t = obj.GetType();

It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.

I also tried the way like

        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }

But it is returning error because of the Value of the collection property is null so we cant get the Type.

In this situation how can i get the Type of a collection Property.

Please help me !

Thanks in Advance.

Body:
Use propertyInfo.PropertyType which has property with name IsGenericType, e.g.:

if (propertyInfo.PropertyType.IsGenericType)
{
    // code ...
}