问:
Whole activity's data goes blank by clicking second time on Bottom Bar menu options
I have a problem with my Bottom bar in android. When I click on the bottom menu options second time it goes blank. What is the basic problem? Where is am I wrong? It shows no error or exception in logcat.

Here is my code

```<code>    public class BottomBarActivity extends AppCompatActivity {

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

            final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
            bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    //                Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.action_library:
                            FragmentLibrary fragmentLibrary = new FragmentLibrary();
                            FragmentManager fragmentManager = getSupportFragmentManager();
                            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                            fragmentTransaction.add(R.id.frame_layout1, fragmentLibrary);
                            fragmentTransaction.commit();

                            Toast.makeText(BottomBarActivity.this, "Library", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_notification:
//002
                            Fragment selectedFragmentNotification = FragmentNotification.newInstance();
                            FragmentTransaction fragmentTransactionNotification = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionNotification.replace(R.id.frame_layout1, selectedFragmentNotification);
                            fragmentTransactionNotification.commit();
                            Toast.makeText(BottomBarActivity.this, "Notifications", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_more:
                            Fragment selectedFragmentMore = FragmentMore.newInstance();
                            FragmentTransaction fragmentTransactionMore = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionMore.replace(R.id.frame_layout1, selectedFragmentMore);
                            fragmentTransactionMore.commit();
                            Toast.makeText(BottomBarActivity.this, "More", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_discovered:
                            Fragment selectedFragmentMain = FragmentMain.newInstance();
                            FragmentTransaction fragmentTransactionMain = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionMain.replace(R.id.frame_layout1, selectedFragmentMain);
                            fragmentTransactionMain.commit();
                            Toast.makeText(BottomBarActivity.this, "Discover", Toast.LENGTH_SHORT).show();
                            break;
                    }
                    return true;
                }
            });
            //Manually displaying the first fragment

            Fragment selectedFragment = FragmentMain.newInstance();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame_layout1, selectedFragment);
            fragmentTransaction.commit();

        }
    }
</code>```

Here is the Fragment Class Code.
This fragment is called when I click one of the menu item.

```<code>public class FragmentLibrary extends Fragment {

    private static final String ARG_POSITION = "position";
    private int position;

    private PagerSlidingTabStrip tabs_L;
    private ViewPager pager_L;

    public FragmentLibrary() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_library, container, false);

        pager_L = (ViewPager) view.findViewById(R.id.pagerL);
        pager_L.setAdapter(new MyAdapterLibrary(getFragmentManager()));
        tabs_L = (PagerSlidingTabStrip) view.findViewById(R.id.tabsL);
        tabs_L.setViewPager(pager_L);

        return view;
    }

    // ADAPTER CLASS
    public class MyAdapterLibrary extends FragmentPagerAdapter {
        private String[] titles = {
                getString(R.string.tab_title_current_reading),
                getString(R.string.tab_title_reading_lists),
                getString(R.string.tab_title_history)
        };

        public MyAdapterLibrary(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return FragmentCurrentReading.newInstance(position);
                case 1:
                    return FragmentReadingLists.newInstance(position);
                case 2:
                    return FragmentHistory.newInstance(position);
            }
            return null;
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
</code>```

First time it look like this.

After click second time all data goes blank.

答:
Because each time you click on menu item a new instance of fragment created.

```<code>case R.id.action_library:
    FragmentLibrary fragmentLibrary = new FragmentLibrary(); // Here
    ...
    break;
</code>```

Try to create instance of your fragments outside of item click listener. For example in onCreate method;

Body:
I have a problem with my Bottom bar in android. When I click on the bottom menu options second time it goes blank. What is the basic problem? Where is am I wrong? It shows no error or exception in logcat.

Here is my code

    public class BottomBarActivity extends AppCompatActivity {

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

            final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
            bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    //                Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.action_library:
                            FragmentLibrary fragmentLibrary = new FragmentLibrary();
                            FragmentManager fragmentManager = getSupportFragmentManager();
                            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                            fragmentTransaction.add(R.id.frame_layout1, fragmentLibrary);
                            fragmentTransaction.commit();

                            Toast.makeText(BottomBarActivity.this, "Library", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_notification:
//002
                            Fragment selectedFragmentNotification = FragmentNotification.newInstance();
                            FragmentTransaction fragmentTransactionNotification = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionNotification.replace(R.id.frame_layout1, selectedFragmentNotification);
                            fragmentTransactionNotification.commit();
                            Toast.makeText(BottomBarActivity.this, "Notifications", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_more:
                            Fragment selectedFragmentMore = FragmentMore.newInstance();
                            FragmentTransaction fragmentTransactionMore = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionMore.replace(R.id.frame_layout1, selectedFragmentMore);
                            fragmentTransactionMore.commit();
                            Toast.makeText(BottomBarActivity.this, "More", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.action_discovered:
                            Fragment selectedFragmentMain = FragmentMain.newInstance();
                            FragmentTransaction fragmentTransactionMain = getSupportFragmentManager().beginTransaction();
                            fragmentTransactionMain.replace(R.id.frame_layout1, selectedFragmentMain);
                            fragmentTransactionMain.commit();
                            Toast.makeText(BottomBarActivity.this, "Discover", Toast.LENGTH_SHORT).show();
                            break;
                    }
                    return true;
                }
            });
            //Manually displaying the first fragment

            Fragment selectedFragment = FragmentMain.newInstance();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame_layout1, selectedFragment);
            fragmentTransaction.commit();

        }
    }

Here is the Fragment Class Code.
This fragment is called when I click one of the menu item.

public class FragmentLibrary extends Fragment {

    private static final String ARG_POSITION = "position";
    private int position;

    private PagerSlidingTabStrip tabs_L;
    private ViewPager pager_L;

    public FragmentLibrary() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_library, container, false);

        pager_L = (ViewPager) view.findViewById(R.id.pagerL);
        pager_L.setAdapter(new MyAdapterLibrary(getFragmentManager()));
        tabs_L = (PagerSlidingTabStrip) view.findViewById(R.id.tabsL);
        tabs_L.setViewPager(pager_L);

        return view;
    }

    // ADAPTER CLASS
    public class MyAdapterLibrary extends FragmentPagerAdapter {
        private String[] titles = {
                getString(R.string.tab_title_current_reading),
                getString(R.string.tab_title_reading_lists),
                getString(R.string.tab_title_history)
        };

        public MyAdapterLibrary(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return FragmentCurrentReading.newInstance(position);
                case 1:
                    return FragmentReadingLists.newInstance(position);
                case 2:
                    return FragmentHistory.newInstance(position);
            }
            return null;
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}

First time it look like this.

After click second time all data goes blank.

Body:
Because each time you click on menu item a new instance of fragment created.

case R.id.action_library:
    FragmentLibrary fragmentLibrary = new FragmentLibrary(); // Here
    ...
    break;

Try to create instance of your fragments outside of item click listener. For example in onCreate method;


来源: stackexchange

问:
C# Aws-Lambda Image Resizing
I currently have a working C# AWS-Lambda Function working. It is triggered when any file is upload to my S3 bucket.

I am trying to resize images when they hit the S3 bucket. I don't know how to include/reference an image resizing tool.

Is there an AWS Built-in function I can use within my C# AWS-Lambda project in VS2017?

答:
You can trigger the C# lambda function when the image is uploaded on S3 bucket. Just pass the image reference to lambda function and somethinge like below code can resize it.

```<code>public static Image resizeImage(Image imgToResize, Size size)
    {
       return (Image)(new Bitmap(imgToResize, size));
    }

    yourImage = resizeImage(yourImage, new Size(50,50));
</code>```

Note: code is taken from this answer.

ContentLicense: CC BY-SA 3.0

Title: C# Aws-Lambda Image Resizing

Body:
You can trigger the C# lambda function when the image is uploaded on S3 bucket. Just pass the image reference to lambda function and somethinge like below code can resize it.

public static Image resizeImage(Image imgToResize, Size size)
    {
       return (Image)(new Bitmap(imgToResize, size));
    }

    yourImage = resizeImage(yourImage, new Size(50,50));

Note: code is taken from this answer.


问:
Selectively removing trailing string
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"
</code>```

but I want

```<code>"HELLO X" "D HELLO" "TW X" "H"
</code>```

答:
```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")

aa <- gsub("O","",a)
gsub("HELL", "HELLO",aa)
</code>```

Title: Selectively removing trailing string

Body:
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"

but I want

"HELLO X" "D HELLO" "TW X" "H"


问:
How can I call a method on a custom object created in JavaScript using C#?
I have a WebBrowser control. I have added some JavaScript into the head tag and I can see it is working as expected by adding an alert. Inside of this js I am creating a function and adding some members to it's prototype like so:

```<code>function test() {
}

test.prototype.run = function() {
    alert('success!')
}

function createTest() {
    return new test()
}
</code>```

Then back inside of C# I am doing:

```<code>dynamic test = this.browser.InvokeScript("createTest");
test.run();
</code>```

I can see that the test object is some ComObject but when I call run() nothing happens. I get no error but nothing happens. Does anyone know how to call this type of custom object?

Also suppose I wanted to get rid of the createTest() method, how can I create a new instance of test from C#?

Also, for bonus points, is there anything special I need to know about attaching events to this custom object (on say a 'complete' member) such that it will callback into my C# code?

答: Turns out that the "dynamic" keyword isn't smart enough to figure this out for some reason. What you can do is cast the COM object returned from InvokeScript into IExpando (or IReflect) and call the InvokeMember method. I created a class that inherits from DynamicObject that overrides all TryXYZ methods and transforms them into IReflect/IExpando method calls. Then you can interact with the object like the above snippet.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a WebBrowser control. I have added some JavaScript into the head tag and I can see it is working as expected by adding an alert. Inside of this js I am creating a function and adding some members to it's prototype like so:

function test() {
}

test.prototype.run = function() {
    alert('success!')
}

function createTest() {
    return new test()
}

Then back inside of C# I am doing:

dynamic test = this.browser.InvokeScript("createTest");
test.run();

I can see that the test object is some ComObject but when I call run() nothing happens. I get no error but nothing happens. Does anyone know how to call this type of custom object?

Also suppose I wanted to get rid of the createTest() method, how can I create a new instance of test from C#?

Also, for bonus points, is there anything special I need to know about attaching events to this custom object (on say a 'complete' member) such that it will callback into my C# code?


问:
Running Visual Studio 2017 with Angular 4 and Angular CLI
Is it possible to run an Angular CLI generated project in Visual Studio 2017?

I tried generating a Hello World application and Visual Studio 2017 can't run it.

```<code>ng new HelloWorld
</code>```

I opened the folder as a website and clicked start.  Has anyone else solved this?

The "Loading..." just runs forever.

答:
If You want to install you can use Install-Package Angular4 -Version 1.1.0 on nuget package manager and follow these steps:

```<code>Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'
</code>```

It may help you to create a Angular4 project on Visual studio 2017/2015.

Body:
Is it possible to run an Angular CLI generated project in Visual Studio 2017?

I tried generating a Hello World application and Visual Studio 2017 can't run it.

ng new HelloWorld

I opened the folder as a website and clicked start.  Has anyone else solved this?

The "Loading..." just runs forever.

Body:
If You want to install you can use Install-Package Angular4 -Version 1.1.0 on nuget package manager and follow these steps:

Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'

It may help you to create a Angular4 project on Visual studio 2017/2015.


问:
How to retrive data using angular js and which stored json format in MYSQL coloumn
I have JSON data stored in MySQL column like this, column name is payments_json_details

```<code>[{"amount":"1000","mop":"Cash","paymentdate":"2017-12-04 16:25","remarks":"testt1"},{"amount":"2500","mop":"Cheque","paymentdate":"2017-12-05","remarks":"testt2"}]
</code>```

When we use this angular js for display purpose, iam getting data like above as it is., but i want to retrieve each values like amount, mop etc

```<code>{{pdata.deliveryinfo[index].payments_json_details}}

<span ng-repeat="(key, value) in pdata.deliveryinfo[index].payments_json_details">
        {{value}}
</span>
</code>```

Iam tried this way, but there is no output, can anyone help?

```<code>JSON format like this

    {
        "jobcard_id": "33",
        "jobcard_sno": "8",
        "user_id": "140",
        "address_id": "22",
        "delivery_address_id": "22",
        "orderdetails": [{
            "id": "71",
            "jobcard_id": "33",
            "product_id": "462",
            "product_quantity": "2",
            "product_price": "324.00"
        }],
        "deliverydetails": [{
            "id": "4",
            "type": "Delivery Agent"
        }, {
            "id": "5",
            "type": "Delivery Agent"
        }],
        "deliveryinfo": [{
            "delivery_id": "7",
            "order_id": "33",
            "product_ids": "462",
            "payment_collected": "Partial",
            "payments_json_details": "[{\"amount\":\"1000\",\"mop\":\"Cash\",\"paymentdate\":\"2017-12-04 16:25\",\"remarks\":\"testt1\"},{\"amount\":\"2500\",\"mop\":\"Cheque\",\"paymentdate\":\"2017-12-05\",\"remarks\":\"testt2\"}]",
            "totaltime": "39:17:00"
        },{
            "delivery_id": "7",
            "order_id": "35",
            "product_ids": "485",
            "payment_collected": "Partial",
            "payments_json_details": "[{\"amount\":\"5000\",\"mop\":\"Cash\",\"paymentdate\":\"2017-12-04 16:25\",\"remarks\":\"testt1\"},{\"amount\":\"7000\",\"mop\":\"Cheque\",\"paymentdate\":\"2017-12-05\",\"remarks\":\"testt2\"}]",
            "totaltime": "39:17:00"
}],
        "$$hashKey": "testt"
    }
</code>```

答:
I am considering pdata.deliveryinfo is an array containing JSON objects. If its pdata.deliveryinfo[index].payments_json_details then use it in ng-repeat.

```<code><span ng-repeat="data in pdata.deliveryinfo>
   Amount: {{data.amount}}, MOP : {{data.mop}}, Payment Date : {{data.paymentdate}}, Remarks : {{data.remarks}}
</span>
</code>```

Body:
I have JSON data stored in MySQL column like this, column name is payments_json_details

[{"amount":"1000","mop":"Cash","paymentdate":"2017-12-04 16:25","remarks":"testt1"},{"amount":"2500","mop":"Cheque","paymentdate":"2017-12-05","remarks":"testt2"}]

When we use this angular js for display purpose, iam getting data like above as it is., but i want to retrieve each values like amount, mop etc

{{pdata.deliveryinfo[index].payments_json_details}}

        {{value}}

Iam tried this way, but there is no output, can anyone help?

JSON format like this

    {
        "jobcard_id": "33",
        "jobcard_sno": "8",
        "user_id": "140",
        "address_id": "22",
        "delivery_address_id": "22",
        "orderdetails": [{
            "id": "71",
            "jobcard_id": "33",
            "product_id": "462",
            "product_quantity": "2",
            "product_price": "324.00"
        }],
        "deliverydetails": [{
            "id": "4",
            "type": "Delivery Agent"
        }, {
            "id": "5",
            "type": "Delivery Agent"
        }],
        "deliveryinfo": [{
            "delivery_id": "7",
            "order_id": "33",
            "product_ids": "462",
            "payment_collected": "Partial",
            "payments_json_details": "[{\"amount\":\"1000\",\"mop\":\"Cash\",\"paymentdate\":\"2017-12-04 16:25\",\"remarks\":\"testt1\"},{\"amount\":\"2500\",\"mop\":\"Cheque\",\"paymentdate\":\"2017-12-05\",\"remarks\":\"testt2\"}]",
            "totaltime": "39:17:00"
        },{
            "delivery_id": "7",
            "order_id": "35",
            "product_ids": "485",
            "payment_collected": "Partial",
            "payments_json_details": "[{\"amount\":\"5000\",\"mop\":\"Cash\",\"paymentdate\":\"2017-12-04 16:25\",\"remarks\":\"testt1\"},{\"amount\":\"7000\",\"mop\":\"Cheque\",\"paymentdate\":\"2017-12-05\",\"remarks\":\"testt2\"}]",
            "totaltime": "39:17:00"
}],
        "$$hashKey": "testt"
    }

Body:
I am considering pdata.deliveryinfo is an array containing JSON objects. If its pdata.deliveryinfo[index].payments_json_details then use it in ng-repeat.

<span ng-repeat="data in pdata.deliveryinfo>
   Amount: {{data.amount}}, MOP : {{data.mop}}, Payment Date : {{data.paymentdate}}, Remarks : {{data.remarks}}
</span>


问:
Why does this handler not return anything?
I'm just starting the ASP.NET tutorial and I don't understand why there is no return statement in the method:

```<code>public async Task OnGetAsync()
{
    Movie = await _context.Movie.ToListAsync();
}
</code>```

Are one line methods automatically returned like arrow statements or does it have to do with the Task in ASP?

答:
if you want to return the list of Movie
then your function should be :

```<code>public async Task<List<Movie>> OnGetAsync()
{
    return await _context.Movie.ToListAsync();
}
</code>```

Body:
I'm just starting the ASP.NET tutorial and I don't understand why there is no return statement in the method:

public async Task OnGetAsync()
{
    Movie = await _context.Movie.ToListAsync();
}

Are one line methods automatically returned like arrow statements or does it have to do with the Task in ASP?

Body:
if you want to return the list of Movie
then your function should be :

public async Task<List<Movie>> OnGetAsync()
{
    return await _context.Movie.ToListAsync();
}


问:
Filter matched items in an array of string with another (key,value) objects in angularjs
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

```<code>var obj = {"viki-1100":6,"mark-2100":2}
</code>```

To return only the non matched keys from stringArr,So desired output:

```<code>var result = ["vijay-1110","ram-2110"]
</code>```

I haven tried the below code which doesnot return the desired output?

```<code>var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}
</code>```

this wont filter the stringArr, It always return all the results in stringArr?

答:
The code below works and manage the case where obj is an empty object. Object.keys(...).length is here to check if obj is an empty object or not

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var filterFunction = function(stringArr,obj){
    return stringArr.filter(str => Object.keys(obj).length === 0 || obj[str] );
}

console.log(filterFunction(stringArr, obj));
console.log(filterFunction(stringArr, {}));```

Body:
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

var obj = {"viki-1100":6,"mark-2100":2}

To return only the non matched keys from stringArr,So desired output:

var result = ["vijay-1110","ram-2110"]

I haven tried the below code which doesnot return the desired output?

var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}

this wont filter the stringArr, It always return all the results in stringArr?


问:
deploy spring boot war into tomcat
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

        <!-- tag::security[] -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- end::security[] -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>
    <!-- To use the plugin goals in your POM or parent POM -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>
</code>```

2.Application.java

```<code>@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

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

}
</code>```

答:
I fixed similar issue. There is no error but some warning when you try open web page. Probably you can take "Warning: No mapping found".
You dont need to SpringBootServletInitializer and override metode in application class. Spring boot is developed for autoconfiguration. Your html or jsp page should be in resources/template or resources/static folder. Please peruse Serving Web Content with Spring MVC , this page can be help you. </p>

Title: deploy spring boot war into tomcat

Body:
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>

2.Application.java

@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

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

}


问:
Hibernate design pattern question
Im working with Hibernate. It works great. However, say that I have a class that corresponds to a database table with only getters and setters and toString, equal methods. Now I would like to add some more methods for helping purpose, for example, say that I would like to get the creationdate with some added description text as shown below.

```<code>public class Client {
        private long id;
        private Calendar creationDate;
        protected String password;

            public long getId() {
            return id;
        }

        @SuppressWarnings("unused")
        private void setId(long id) {
            this.id = id;
        }

        public Calendar getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Calendar creationDate) {
            this.creationDate = creationDate;
        }

        ..
        .. some other getters and setters that corresponding to SQL columns

        //Here I would like to have some help methods. Is it recommended to put it here?
        public String getCreationDateInSecs() {
            return "Date in secs: " + creationDate.getTimeInMillis * 1000;
        }
    }
</code>```

The question is: Where should I place this method?

Should I add it in the same class as the Value Object or should I place it somewhere else? I would like to know the best practice if you know what I mean =)

Best regards

答:
Bozho basically outlined two possible approaches: rich model and anemic model, and suggested a rich model as more OOPish. I'll advocate an anemic approach here.

The functionality you describe looks like a responsibility of a presentation layer. I think it would be better to put it into UI-related classes rather than into the domain model.

Putting it into domain model looks harmless as long as the logic is as simple as

```<code>return "Date in secs: " + creationDate.getTimeInMillis * 1000;
</code>```

However, imagine that you got an additional requirement to return a localized description. You will have to add dependencies on localization facilities to your domain model, that increases coupling of your code.

So, it's better to keep responsibilities of different layer separated.

Title: Hibernate design pattern question

Body:
Im working with Hibernate. It works great. However, say that I have a class that corresponds to a database table with only getters and setters and toString, equal methods. Now I would like to add some more methods for helping purpose, for example, say that I would like to get the creationdate with some added description text as shown below.

public class Client {
        private long id;
        private Calendar creationDate;
        protected String password;

            public long getId() {
            return id;
        }

        @SuppressWarnings("unused")
        private void setId(long id) {
            this.id = id;
        }

        public Calendar getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Calendar creationDate) {
            this.creationDate = creationDate;
        }

        ..
        .. some other getters and setters that corresponding to SQL columns

        //Here I would like to have some help methods. Is it recommended to put it here?
        public String getCreationDateInSecs() {
            return "Date in secs: " + creationDate.getTimeInMillis * 1000;
        }
    }

The question is: Where should I place this method?

Should I add it in the same class as the Value Object or should I place it somewhere else? I would like to know the best practice if you know what I mean =)

Best regards

Body:
Bozho basically outlined two possible approaches: rich model and anemic model, and suggested a rich model as more OOPish. I'll advocate an anemic approach here.

The functionality you describe looks like a responsibility of a presentation layer. I think it would be better to put it into UI-related classes rather than into the domain model.

Putting it into domain model looks harmless as long as the logic is as simple as

return "Date in secs: " + creationDate.getTimeInMillis * 1000;

However, imagine that you got an additional requirement to return a localized description. You will have to add dependencies on localization facilities to your domain model, that increases coupling of your code.

So, it's better to keep responsibilities of different layer separated.


问:
date parsing in java to desire date format
I am trying to do an integration between 2 system,
so there is a datetime field in the source system which has format like
"dd-MMM-yyyy HH:mm:ss" for example- 19-JUN-2017 16:12:30
but what my target system reads is like "yyyy-MM-DD HH:mm:ss"
for example- 2017-12-04 19:14:16

As I am setting a value like

Tableset.setValue("TRANSACTIONDATE",CSVFILECOLUMN[1], 2L);

can any one tell me how can I parse the date format in CSV file here to set the parsed value in my TRANSACTIONDATE field.

答:
Covert your date like this

```<code>String mydate="19-JUN-2017 16:12:30";
SimpleDateFormat currentFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date d = currentFormat.parse(mydate);
String formattedTime = newFormat.format(d);
</code>```

then calculate difference

Body:
Covert your date like this

String mydate="19-JUN-2017 16:12:30";
SimpleDateFormat currentFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date d = currentFormat.parse(mydate);
String formattedTime = newFormat.format(d);

then calculate difference


问:
Django: How to change the page at the click of a line?
I'm trying to make some views in Ddjango when i click on a line in a  tag in HTMl and i need some advise and please take into account that i'm a beginner in Django.
Indeed, i would like to change my view when i click on it, what will open a new view called like the Hash inside my  tag.
Let me explain you with this code called bap2pmonitoring.html:

```<code>{% load staticfiles %}
<!DOCTYPE html>
<html lang="fr">
<head>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />
</head>
<body>

<h1> BAP2P Monitoring</h1>

<table>
    <tr>
        <th width=550 height=20>Torrent Hash</th>
        <th width=720 height=20>Torrent Name</th>
        <th width=120 height=20>Size</th>
        <th width=170 height=20>Active Peers</th>
    </tr>

{% for torrent in torrents %}
        <p id="demo">
        <tr bgcolor=eeeeee>
            <td width=550 height=20><a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a></td>
            <td width=720 height=20>{{ torrent.Name }}</td>
            <td width=120 height=20>{{ torrent.Size }}</td>
            <td width=170 height=20></td>
    </tr>
        </p>
{% endfor %}

</table>

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

I obtain thus this result:

![enter image description here][1]

My idea is that when i click in one of these 2 lines, it render a new view with informations about this torrent with the hash of the torrent as url like this:

```<code>127.0.0.1:8000/torrents/606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b
</code>```

Following the Django tutorial, i tried lot's of things without success and then i tried a "onclick" to start one of my def in my view.py like this:

```<code>from django.shortcuts import render_to_response
from django.template import Template , Context
from polls.models import Torrent
# Create your views here.
# -*- coding: utf-8 -*-

def home(request):
    return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})

def details(request, torrent_hash):
    return render_to_response('mysite/detail_torrent.html', {'torrents':Torrent.objects.filter(hash=torrent_hash)})
</code>```

I also tried to display the hash as an url like this in urls.py:

```<code>from django.conf.urls import patterns,include, url
from django.contrib import admin
from polls.models import Torrent

urlpatterns = patterns('polls.views',

     url(r'^torrents$', 'home', name = 'home'),
     url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'),
     url(r'^admin/', include(admin.site.urls)),
)
</code>```

I don't understand how can i resolve this, any idea are welcomed and appreciated

Now i'm obtaining this error page:

```<code>NoReverseMatch at /torrents

Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']
</code>```

And this Traceback:

```<code>   Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/torrents

Django Version: 1.8.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Template error:
In template /home/florian/Documents/mysite/templates/mysite/bap2pmonitoring.html, error at line 23
   Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

   13 :     <tr>

   14 :         <th width=550 height=20>Torrent Hash</th>

   15 :         <th width=720 height=20>Torrent Name</th>

   16 :         <th width=120 height=20>Size</th>

   17 :         <th width=170 height=20>Active Peers</th>

   18 :     </tr>

   19 :

   20 : {% for torrent in torrents %}

   21 :         <p id="demo">

   22 :         <tr bgcolor=eeeeee>

   23 :             <td width=550 height=20><a href=" {% url 'hash' torrent.Hash %} ">{{ torrent.Hash }}</a></td>

   24 :             <td width=720 height=20>{{ torrent.Name }}</td>

   25 :             <td width=120 height=20>{{ torrent.Size }}</td>

   26 :             <td width=170 height=20></td>

   27 :         </tr>

   28 :         </p>

   29 : {% endfor %}

   30 :

   31 : </table>

   32 :

   33 : </body>

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/florian/Documents/mysite/polls/views.py" in home
  8.     return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render_to_response
  39.         content = loader.render_to_string(template_name, context, using=using)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  99.         return template.render(context, request)
File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render
  74.         return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  209.                     return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  201.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  903.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  79.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  217.                             nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  507.                         six.reraise(*exc_info)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  493.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
  579.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  496.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /torrents
Exception Value: Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']
</code>```

答:
Thanks to Ralph's suggestion, I managed to do the same thing as the poster. However, with one tweak, namely, I am staying (intentionally) on the initial page, i.e., in the above example I am only using

'mysite/bap2pmonitoring.html'

where I invoke

```<code><a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a>
</code>```

(within the for loop)

the view consequently points back to 'mysite/bap2pmonitoring.html' instead of 'mysite/detail_torrent.html'

everything works well in terms of the link. However, once I click the link, and  the result of the details view is displayed (correctly), the links of the loop disappear. Everything else of the initial page remains. Is there a way to prevent this, i.e., keep the links?

(The idea is to create a pannel and to display the details below, being able to update the details by the links of the pannel)

Body:
I'm trying to make some views in Ddjango when i click on a line in a  tag in HTMl and i need some advise and please take into account that i'm a beginner in Django.
Indeed, i would like to change my view when i click on it, what will open a new view called like the Hash inside my  tag.
Let me explain you with this code called bap2pmonitoring.html:

{% load staticfiles %}
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />

 BAP2P Monitoring

        Torrent Hash
        Torrent Name
        Size
        Active Peers

{% for torrent in torrents %}

            {{ torrent.Hash }}
            {{ torrent.Name }}
            {{ torrent.Size }}

{% endfor %}

I obtain thus this result:

![enter image description here][1]

My idea is that when i click in one of these 2 lines, it render a new view with informations about this torrent with the hash of the torrent as url like this:

127.0.0.1:8000/torrents/606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b

Following the Django tutorial, i tried lot's of things without success and then i tried a "onclick" to start one of my def in my view.py like this:

from django.shortcuts import render_to_response
from django.template import Template , Context
from polls.models import Torrent
# Create your views here.
# -*- coding: utf-8 -*-

def home(request):
    return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})

def details(request, torrent_hash):
    return render_to_response('mysite/detail_torrent.html', {'torrents':Torrent.objects.filter(hash=torrent_hash)})

I also tried to display the hash as an url like this in urls.py:

from django.conf.urls import patterns,include, url
from django.contrib import admin
from polls.models import Torrent

urlpatterns = patterns('polls.views',

     url(r'^torrents$', 'home', name = 'home'),
     url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'),
     url(r'^admin/', include(admin.site.urls)),
)

I don't understand how can i resolve this, any idea are welcomed and appreciated

Now i'm obtaining this error page:

NoReverseMatch at /torrents

Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

And this Traceback:

   Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/torrents

Django Version: 1.8.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Template error:
In template /home/florian/Documents/mysite/templates/mysite/bap2pmonitoring.html, error at line 23
   Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

   13 :

   14 :         Torrent Hash

   15 :         Torrent Name

   16 :         Size

   17 :         Active Peers

   18 :

   19 :

   20 : {% for torrent in torrents %}

   21 :

   22 :

   23 :             {{ torrent.Hash }}

   24 :             {{ torrent.Name }}

   25 :             {{ torrent.Size }}

   26 :

   27 :

   28 :

   29 : {% endfor %}

   30 :

   31 :

   32 :

   33 :

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/florian/Documents/mysite/polls/views.py" in home
  8.     return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render_to_response
  39.         content = loader.render_to_string(template_name, context, using=using)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  99.         return template.render(context, request)
File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render
  74.         return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  209.                     return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  201.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  903.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  79.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  217.                             nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  507.                         six.reraise(*exc_info)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  493.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
  579.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  496.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /torrents
Exception Value: Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

Body:
Thanks to Ralph's suggestion, I managed to do the same thing as the poster. However, with one tweak, namely, I am staying (intentionally) on the initial page, i.e., in the above example I am only using

'mysite/bap2pmonitoring.html'

where I invoke

<a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a>

(within the for loop)

the view consequently points back to 'mysite/bap2pmonitoring.html' instead of 'mysite/detail_torrent.html'

everything works well in terms of the link. However, once I click the link, and  the result of the details view is displayed (correctly), the links of the loop disappear. Everything else of the initial page remains. Is there a way to prevent this, i.e., keep the links?

(The idea is to create a pannel and to display the details below, being able to update the details by the links of the pannel)


问:
Navigate to parent of parent stack
I have this scenario where i have a StackNavigator nested in a TabNavigator nested in another StackNavigator.

```<code>const TabOneStack = StackNavigator({
  ScreenA: { screen: ScreenA },
  ScreenB: { screen: ScreenB }
});

const MainTabs = TabNavigator({
  TabOne: { screen: TabOneStack },
  TabTwo: { screen: TabTwoStack }
});

const Root = StackNavigator({
  HomeScreen: { screen: HomeScreen },
  MainTabs: { screen: MainTabs }
});
</code>```

Everything works but i cant figure out how to navigate for example from ScreenA back to the Home screen in the root StackNavigator.
After the HomeScreen the User navigates directly to ScreenA.
The back button in the header in ScreenA works fine and brings me back to Home but need a way to have a button that brings me back to the HomeScreen.
this.props.navigation.goBack() does not work unfortunately.

i also tried

```<code>const backAction = NavigationActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({ routeName: 'HomeScreen'})
  ]
});
this.props.navigation.dispatch(backAction));
</code>```

but i get:

There is no route defined for key HomeScreen. Must be one of: 'ScreenA', 'ScreenB'.

What is the correct way to do this?

答:
To traverse from child StackNavigator back to parent StackNavigator, do:

class ScreenA extends Component {
    render() {
        return (<Button onPress={() => {
            this.props.navigation.dispatch({type: 'Navigation/BACK'});
        }} title='ScreenA. back to Home' />);
    }
}
```

<p><code>this.props.navigation.dispatch()</code> with <code>'Navigation/BACK'</code> works exactly the same as the top-most back button.<br>
It differs from <code>goBack()</code> by apply parent-child stack traversing, while <code>goBack()</code> does not.</p>

<h2>Result:</h2>

<p><img src="https://i.stack.imgur.com/58D23.gif" alt="enter image description here"></p>

<p>And note @Jigar's answer is also correct, it's just a shorthand notation of mine. The key is to pass <code>null</code> argument into <code>goBack()</code>. It won't work without that.</p>

<pre class="lang-js prettyprint-override"><code>this.props.navigation.goBack(null);
</code>```

Title: Navigate to parent of parent stack

Body:
I have this scenario where i have a StackNavigator nested in a TabNavigator nested in another StackNavigator.

const TabOneStack = StackNavigator({
  ScreenA: { screen: ScreenA },
  ScreenB: { screen: ScreenB }
});

const MainTabs = TabNavigator({
  TabOne: { screen: TabOneStack },
  TabTwo: { screen: TabTwoStack }
});

const Root = StackNavigator({
  HomeScreen: { screen: HomeScreen },
  MainTabs: { screen: MainTabs }
});

Everything works but i cant figure out how to navigate for example from ScreenA back to the Home screen in the root StackNavigator.
After the HomeScreen the User navigates directly to ScreenA.
The back button in the header in ScreenA works fine and brings me back to Home but need a way to have a button that brings me back to the HomeScreen.
this.props.navigation.goBack() does not work unfortunately.

i also tried

const backAction = NavigationActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({ routeName: 'HomeScreen'})
  ]
});
this.props.navigation.dispatch(backAction));

but i get:

There is no route defined for key HomeScreen. Must be one of: 'ScreenA', 'ScreenB'.

What is the correct way to do this?

Body:
To traverse from child StackNavigator back to parent StackNavigator, do:

class ScreenA extends Component {
    render() {
        return (<Button onPress={() => {
            this.props.navigation.dispatch({type: 'Navigation/BACK'});
        }} title='ScreenA. back to Home' />);
    }
}

this.props.navigation.dispatch() with 'Navigation/BACK' works exactly the same as the top-most back button.

It differs from goBack() by apply parent-child stack traversing, while goBack() does not.

Result:

And note @Jigar's answer is also correct, it's just a shorthand notation of mine. The key is to pass null argument into goBack(). It won't work without that.

this.props.navigation.goBack(null);


问:
How to integrate LUIS service with bot?
I am developing a CORTANA app with LUIS, the Root dialog is consuming the LUIS and based on user intention I am redirecting him to another dialog but I have observed that after execution of Root dialog constructor and exception occurs while I have another dialog without LUIS (i.e. InsightsDialog commented below) that is working fine.

Following code is redirecting to Root Dialog from MessagesController:

```<code>public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                   //await Conversation.SendAsync(activity, () => new Dialogs.InsightsDialog());
            }
            else
            {
                await HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }
</code>```

Root Dialog Code:

```<code>[Serializable]
    public class RootDialog : LuisDialog<object>
    {
        InsightsDialog customerInsightsDialog = null;
        public RootDialog() : base(new LuisService(Utility.GetLUISAttributesFromConfig()))
        {
            customerInsightsDialog = new InsightsDialog();
        }
        public static LuisModelAttribute GetLUISAttributesFromConfig()
        {
                return new LuisModelAttribute(Constants.RootDialogLuisModelId, Constants.RootDialogLuisSubscriptionKey);
        }

       #region Intents
        [LuisIntent("")]
        [LuisIntent("None")]
        public async Task None(IDialogContext context, LuisResult result)
        {
                string userInput = result.Query;
                context.Call(customerInsightsDialog, ResumeAfterInsightsDialog);
        }

        [LuisIntent("Greetings")]
        public async Task Greetings(IDialogContext context, LuisResult result)
        {
                string userInput = result.Query;
                context.Call(customerInsightsDialog, ResumeAfterInsightsDialog);
        }

        private Task ResumeAfterInsightsDialog(IDialogContext context, IAwaitable<object> result)
        {
            return Task.CompletedTask;
        }
       #endregion
    }
</code>```

I found the following exception in logs and it occurs right after calling the constructor of RootDialog class:

```<code>System.ArgumentNullException: Value cannot be null.
Parameter name: stringToEscape
   at System.Uri.EscapeDataString(String stringToEscape)
   at Microsoft.Bot.Builder.Luis.LuisRequest.BuildUri(ILuisModel model)
   at Microsoft.Bot.Builder.Luis.LuisService.Microsoft.Bot.Builder.Luis.ILuisService.BuildUri(LuisRequest luisRequest)
   at Microsoft.Bot.Builder.Luis.Extensions.<QueryAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.LuisDialog`1.<MessageReceived>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()
   at Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog`1.<ResumeAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ScoringEventLoop`1.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.EventLoopDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SetAmbientThreadCulture.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.QueueDrainingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CustomerInsights.MessagesController.<Post>d__0.MoveNext()
</code>```

This code is working fine on emulator and web chat channels but thrown an exception only on CORTANA channel. Appreciate to help me out.

答:
The issue has been resolved by modifying the existing code of class "MessagesController" as follows:

```<code>public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                  if (string.IsNullOrEmpty(activity.Text))
                     {
                          var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                          Activity reply = activity.CreateReply();
                          reply.Text = string.Format(Resources.WELCOME_MESSAGE, Constants.UserInfo.FullName);
                          reply.Speak = SSMLHelper.Speak(string.Format(Resources.WELCOME_MESSAGE, Constants.UserInfo.FullName));
                          reply.InputHint = InputHints.ExpectingInput;

                          await connector.Conversations.ReplyToActivityAsync(reply);
                     }
                 else
                    {
                          await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                     }
            }
            else
            {
                await HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }
</code>```

Actually the "Text" property of "Activity" object was empty. So right now I am asking to user to input (via Speak) some text to proceed further.

Title: How to integrate LUIS service with bot?

Body:
I am developing a CORTANA app with LUIS, the Root dialog is consuming the LUIS and based on user intention I am redirecting him to another dialog but I have observed that after execution of Root dialog constructor and exception occurs while I have another dialog without LUIS (i.e. InsightsDialog commented below) that is working fine.

Following code is redirecting to Root Dialog from MessagesController:

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                   //await Conversation.SendAsync(activity, () => new Dialogs.InsightsDialog());
            }
            else
            {
                await HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

Root Dialog Code:

[Serializable]
    public class RootDialog : LuisDialog<object>
    {
        InsightsDialog customerInsightsDialog = null;
        public RootDialog() : base(new LuisService(Utility.GetLUISAttributesFromConfig()))
        {
            customerInsightsDialog = new InsightsDialog();
        }
        public static LuisModelAttribute GetLUISAttributesFromConfig()
        {
                return new LuisModelAttribute(Constants.RootDialogLuisModelId, Constants.RootDialogLuisSubscriptionKey);
        }

       #region Intents
        [LuisIntent("")]
        [LuisIntent("None")]
        public async Task None(IDialogContext context, LuisResult result)
        {
                string userInput = result.Query;
                context.Call(customerInsightsDialog, ResumeAfterInsightsDialog);
        }

        [LuisIntent("Greetings")]
        public async Task Greetings(IDialogContext context, LuisResult result)
        {
                string userInput = result.Query;
                context.Call(customerInsightsDialog, ResumeAfterInsightsDialog);
        }

        private Task ResumeAfterInsightsDialog(IDialogContext context, IAwaitable<object> result)
        {
            return Task.CompletedTask;
        }
       #endregion
    }

I found the following exception in logs and it occurs right after calling the constructor of RootDialog class:

System.ArgumentNullException: Value cannot be null.
Parameter name: stringToEscape
   at System.Uri.EscapeDataString(String stringToEscape)
   at Microsoft.Bot.Builder.Luis.LuisRequest.BuildUri(ILuisModel model)
   at Microsoft.Bot.Builder.Luis.LuisService.Microsoft.Bot.Builder.Luis.ILuisService.BuildUri(LuisRequest luisRequest)
   at Microsoft.Bot.Builder.Luis.Extensions.<QueryAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.LuisDialog`1.<MessageReceived>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()
   at Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog`1.<ResumeAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ScoringEventLoop`1.<Microsoft-Bot-Builder-Base-IEventLoop-PollAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.EventLoopDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SetAmbientThreadCulture.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.QueueDrainingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CustomerInsights.MessagesController.<Post>d__0.MoveNext()

This code is working fine on emulator and web chat channels but thrown an exception only on CORTANA channel. Appreciate to help me out.

Body:
The issue has been resolved by modifying the existing code of class "MessagesController" as follows:

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                  if (string.IsNullOrEmpty(activity.Text))
                     {
                          var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                          Activity reply = activity.CreateReply();
                          reply.Text = string.Format(Resources.WELCOME_MESSAGE, Constants.UserInfo.FullName);
                          reply.Speak = SSMLHelper.Speak(string.Format(Resources.WELCOME_MESSAGE, Constants.UserInfo.FullName));
                          reply.InputHint = InputHints.ExpectingInput;

                          await connector.Conversations.ReplyToActivityAsync(reply);
                     }
                 else
                    {
                          await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                     }
            }
            else
            {
                await HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

Actually the "Text" property of "Activity" object was empty. So right now I am asking to user to input (via Speak) some text to proceed further.


问:
Asp.net URL Rewrite Rule with Regex
I have rewrite rules on web.config file.

```<code> <rewrite url="~/Login/(.+)$" to="~/Login.aspx?return=$1"/>
 <rewrite url="~/(.+)-xxx-(.+)$" to="~/Post.aspx?ost_name=$1&post_id=$2"/>
</code>```

First one for redirect url after login.
Second one for posts.

If users try login or click comment on post page they will go to login page with redirect url.

```<code> protected void lnkLogin_Click(object sender, EventArgs e)
    {
        Session["GoBackUrl"] = Request.RawUrl.ToString().Replace("/", "$");
         base.Response.Redirect("~/Login/" + Session["GoBackUrl"].ToString());
    }
</code>```

For example

```<code>domain.com/Login/$post_name-xxx-post_id
</code>```

After login they will turn back to post page.

But with this rules they are not going login page.
Url is changing as

```<code> domain.com/Login/$post_name-xxx-post_id
</code>```

but user stays same page.
How can I solve this ?

答:
I found this example from Devrim Altinkurt's(lang:Tr) page and wrote him. He helped me.

Solution:
"processing="stop"

```<code><rewrite url="~/Login/(.+)$" to="~/Login.aspx?return=$1" "processing="stop/>
 <rewrite url="~/(.+)-xxx-(.+)$" to="~/Post.aspx?post_name=$1&post_id=$2"/>
</code>```

When you don't write. Application looks all rules and firing last match
If you got same Url's you should use this. One more detail : rule ranks are important.

Title: Asp.net URL Rewrite Rule with Regex

Body:
I have rewrite rules on web.config file.

 <rewrite url="~/Login/(.+)$" to="~/Login.aspx?return=$1"/>
 <rewrite url="~/(.+)-xxx-(.+)$" to="~/Post.aspx?ost_name=$1&post_id=$2"/>

First one for redirect url after login.
Second one for posts.

If users try login or click comment on post page they will go to login page with redirect url.

 protected void lnkLogin_Click(object sender, EventArgs e)
    {
        Session["GoBackUrl"] = Request.RawUrl.ToString().Replace("/", "$");
         base.Response.Redirect("~/Login/" + Session["GoBackUrl"].ToString());
    }

For example

domain.com/Login/$post_name-xxx-post_id

After login they will turn back to post page.

But with this rules they are not going login page.
Url is changing as

 domain.com/Login/$post_name-xxx-post_id

but user stays same page.
How can I solve this ?

Body:
I found this example from Devrim Altinkurt's(lang:Tr) page and wrote him. He helped me.

Solution:
"processing="stop"

<rewrite url="~/Login/(.+)$" to="~/Login.aspx?return=$1" "processing="stop/>
 <rewrite url="~/(.+)-xxx-(.+)$" to="~/Post.aspx?post_name=$1&amp;post_id=$2"/>

When you don't write. Application looks all rules and firing last match
If you got same Url's you should use this. One more detail : rule ranks are important.