RSS

Monthly Archives: April 2014

Android: Speech To Text Using API

By 

Android has a very cool feature that still many developers dont know. Apps like Any.DO uses speech to text conversion feature quite creatively. In today’s world of Siri, voice commands are of utmost importance. Android natively provides feature of Speech to Text so why not to use it in our app!

I will show you how to use Android’s Speech to Text API in an application.

Let’s make our demo application.

Demo App

The App will be very simple. It will have a button with Mic symbol. On click of which we trigger Android’s Speech to Text Intent which shows a dialog to take speech input. The speech input is then converted into text. The text is then displayed in a text view.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as SpeechToTextDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.speechtotextdemo.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. Just one Image Button to trigger Speech to Text API and one TextView to display result text that is converted from speech.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >
    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />
    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

The UI is very simply. One LinearLayout to organize the button and text view. Note the id for button:btnSpeak and text view: txtText which we will use in our Java code.

Step 3: Android Java Code to trigger Speech to Text API

Open SpeechToTextDemoActivity class and replace the code with following.

File: SpeechToTextDemoActivity.java

package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    protected static final int RESULT_SPEECH = 1;
    private ImageButton btnSpeak;
    private TextView txtText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtText = (TextView) findViewById(R.id.txtText);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txtText.setText(text.get(0));
            }
            break;
        }
        }
    }
}

The heart of Speech to text Android API is package android.speech and specifically classandroid.speech.RecognizerIntent. Basically we trigger an Intent (android.speech.RecognizerIntent) which shows dialog box to recognize speech input. This Activity then converts the speech into text and send backs the result to our calling Activity. When we invoke android.speech.RecognizerIntent intent, we must use startActivityForResult() as we must listen back for result text.

Note how in above code we crate intent android.speech.RecognizerIntent and trigger it. Also we add one extra parameter using .putExtra() method. When invoking RecognizerIntent, we must provide extraRecognizerIntent.EXTRA_LANGUAGE_MODE. Here we are setting its value to en-US.

Since we triggered the RecognizerIntent via startActivityForResult(), we override methodonActivityResult(int requestCode, int resultCode, Intent data) to handle the result data. The
RecognizerIntent will convert the speech input to text and send back the result as ArraList with key RecognizerIntent.EXTRA_RESULTS. Generally this list should be ordered in descending order of speech recognizer confidence. Only present when RESULT_OK is returned in an activity result. We just set the text that we got in result in text view txtText using txtText.setText().

One thing worth noting here is how to handle devices/android version that doesn’t support speech to text API. In such case, exception ActivityNotFoundException will be thrown when we try to start activity. In above example, we have catched this exception and displayed a message “Opps! Your device doesn’t support Speech to Text” using Toast.

Screen shots of Android App

And that’s all! Just execute the app in Android emulator or real device and see following output.

android-speech-to-text-api-demo

android-speech-to-text-activity

android-speech-to-text-conversion

android-speech-text

Download Source Code

Android_SpeechToTextDemo.zip (350 KB)

References

RecognizerIntent.html#ACTION_RECOGNIZE_SPEECH Documentation

Copy from: http://viralpatel.net/blogs/android-speech-to-text-api/

 
1 Comment

Posted by on April 30, 2014 in Android, Mobile Development

 

Run Android on The Real Device

Using Hardware Devices

When building a mobile application, it’s important that you always test your application on a real device before releasing it to users. This page describes how to set up your development environment and Android-powered device for testing and debugging on the device.

You can use any Android-powered device as an environment for running, debugging, and testing your applications. The tools included in the SDK make it easy to install and run your application on the device each time you compile. You can install your application on the device directly from Eclipse or from the command line with ADB. If you don’t yet have a device, check with the service providers in your area to determine which Android-powered devices are available.

If you want a SIM-unlocked phone, then you might consider a Nexus phone. To purchase a Nexus phone, visit the Google Play store.

Note: When developing on a device, keep in mind that you should still use the Android emulator to test your application on configurations that are not equivalent to those of your real device. Although the emulator does not allow you to test every device feature (such as the accelerometer), it does allow you to verify that your application functions properly on different versions of the Android platform, in different screen sizes and orientations, and more.

Setting up a Device for Development


With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator. Before you can start, there are just a few things to do:

  1. Declare your application as “debuggable” in your Android Manifest.When using Eclipse, you can skip this step, because running your app directly from the Eclipse IDE automatically enables debugging.

    In the AndroidManifest.xml file, add android:debuggable="true" to the <application> element.

    Note: If you manually enable debugging in the manifest file, be sure to disable it before you build for release (your published application should usually not be debuggable).

  2. Enable USB debugging on your device.
    • On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development.
    • On Android 4.0 and newer, it’s in Settings > Developer options.

      Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.

  3. Set up your system to detect your device.
    • If you’re developing on Windows, you need to install a USB driver for adb. For an installation guide and links to OEM drivers, see the OEM USB Drivers document.
    • If you’re developing on Mac OS X, it just works. Skip this step.
    • If you’re developing on Ubuntu Linux, you need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on Ubuntu Linux:
      1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.Use this format to add each vendor to the file:
        SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

        In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUPdefines which Unix group owns the device node.

        Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.

      2. Now execute:
        chmod a+r /etc/udev/rules.d/51-android.rules

Note: When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you’re able to unlock the device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2 or higher.

When plugged in over USB, you can verify that your device is connected by executing adb devices from your SDKplatform-tools/ directory. If connected, you’ll see the device name listed as a “device.”

If using Eclipse, run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s). Select the device upon which you want to install and run the application.

If using the Android Debug Bridge (adb), you can issue commands with the -d flag to target your connected device.

USB Vendor IDs

This table provides a reference to the vendor IDs needed in order to add USB device support on Linux. The USB Vendor ID is the value given to the ATTR{idVendor} property in the rules file, as described above.

Company USB Vendor ID
Acer 0502
ASUS 0b05
Dell 413c
Foxconn 0489
Fujitsu 04c5
Fujitsu Toshiba 04c5
Garmin-Asus 091e
Google 18d1
Haier 201E
Hisense 109b
HTC 0bb4
Huawei 12d1
K-Touch 24e3
KT Tech 2116
Kyocera 0482
Lenovo 17ef
LG 1004
Motorola 22b8
MTK 0e8d
NEC 0409
Nook 2080
Nvidia 0955
OTGV 2257
Pantech 10a9
Pegatron 1d4d
Philips 0471
PMC-Sierra 04da
Qualcomm 05c6
SK Telesys 1f53
Samsung 04e8
Sharp 04dd
Sony 054c
Sony Ericsson 0fce
Teleepoch 2340
Toshiba 0930
ZTE 19d2
 
Leave a comment

Posted by on April 28, 2014 in Android, Mobile Development

 

OWIN OAuth 2.0 Authorization Server

By Rick AndersonHongye Sun and Praburaj Thiagarajan|March 20, 2014

This tutorial will guide you on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware. This is an advanced tutorial that only outlines the steps to create an OWIN OAuth 2.0 Authorization Server. This is not a step by step tutorial. Download the sample code.

Note: This outline should not be intended to be used for creating a secure production app. This tutorial is intended to provide only an outline on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware.

Software versions

Shown in the tutorial Also works with
Windows 8.1 Windows 8, Windows 7
Visual Studio 2013 Visual Studio 2013 Express for Desktop.

Visual Studio 2012 with the latest update should work, but the tutorial has not been tested with it, and some menu selections and dialog boxes are different.

.NET 4.5

Questions and Comments

If you have questions that are not directly related to the tutorial, you can post them athttp://katanaproject.codeplex.com/discussions. For questions and comments regarding the tutorial itself, see the comments section at the bottom of the page.

The  OAuth 2.0 framework enables a third-party app to obtain limited access to an HTTP service. Instead of using the resource owner’s credentials to access a protected resource, the client obtains an access token (which is a string denoting a specific scope, lifetime, and other access attributes). Access tokens are issued to third-party clients by an authorization server with the approval of the resource owner.

This tutorial will cover:

  • How to create an authorization server to support 4 Authorization Grants and refresh tokens.
  • Authorization code grant:
    • Implicit Grant
    • Resource Owner Password Credentials Grant
    • Client Credentials Grant
  • Creating a resource server which is protected by an access token.
  • Creating OAuth 2.0 clients.

Prerequisites

Create an Authorization Server

In this tutorial, we will roughly sketch out how to use OWIN and ASP.NET MVC to create an authorization server. We hope to soon provide a download for the completed sample, as this tutorial does not include each step. First, create an empty web app named AuthorizationServer and install the following packages:

  • Microsoft.AspNet.Mvc
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Security.Google (Or any other social login package such as Microsoft.Owin.Security.Facebook)

Add an OWIN Startup class under the project root folder named Startup.

usingMicrosoft.Owin;usingOwin;[assembly:OwinStartup(typeof(AuthorizationServer.Startup))]namespaceAuthorizationServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);}}}

Create an App_Start folder. Select the App_Start folder and use Shift+Alt+A to add the downloaded version of theAuthorizationServer\App_Start\Startup.Auth.cs file.

publicvoidConfigureAuth(IAppBuilder app){// Enable the Application Sign In Cookie.
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="Application",AuthenticationMode=AuthenticationMode.Passive,LoginPath=newPathString(Paths.LoginPath),LogoutPath=newPathString(Paths.LogoutPath),});// Enable the External Sign In Cookie.
     app.SetDefaultSignInAsAuthenticationType("External");
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="External",AuthenticationMode=AuthenticationMode.Passive,CookieName=CookieAuthenticationDefaults.CookiePrefix+"External",ExpireTimeSpan=TimeSpan.FromMinutes(5),});// Enable Google authentication.
     app.UseGoogleAuthentication();// Setup Authorization Server
     app.UseOAuthAuthorizationServer(newOAuthAuthorizationServerOptions{AuthorizeEndpointPath=newPathString(Paths.AuthorizePath),TokenEndpointPath=newPathString(Paths.TokenPath),ApplicationCanDisplayErrors=true,#if DEBUGAllowInsecureHttp=true,#endif// Authorization server provider which controls the lifecycle of Authorization ServerProvider=newOAuthAuthorizationServerProvider{OnValidateClientRedirectUri=ValidateClientRedirectUri,OnValidateClientAuthentication=ValidateClientAuthentication,OnGrantResourceOwnerCredentials=GrantResourceOwnerCredentials,OnGrantClientCredentials=GrantClientCredetails},// Authorization code provider which creates and receives the authorization code.AuthorizationCodeProvider=newAuthenticationTokenProvider{OnCreate=CreateAuthenticationCode,OnReceive=ReceiveAuthenticationCode,},// Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}

The code above enables application/external sign in cookies and Google authentication, which are used by authorization server itself to manage accounts.

The UseOAuthAuthorizationServer extension method is to setup the authorization server. The setup options are:

  • AuthorizeEndpointPath: The request path where client applications will redirect the user-agent in order to obtain the users consent to issue a token or code. It must begin with a leading slash, for example,  “/Authorize“.
  • TokenEndpointPath: The request path client applications directly communicate to obtain the access token. It must begin with a leading slash, like “/Token”. If the client is issued a client_secret, it must be provided to this endpoint.
  • ApplicationCanDisplayErrors: Set to true if the web application wants to generate a custom error page for the client validation errors on /Authorize endpoint. This is only needed for cases where the browser is not redirected back to the client application, for example, when the client_id or redirect_uri are incorrect. The /Authorize endpoint should expect to see the “oauth.Error”, “oauth.ErrorDescription”, and “oauth.ErrorUri” properties are added to the OWIN environment.
    Note: If not true, the authorization server will return a default error page with the error details.
  • AllowInsecureHttp: True to allow authorize and token requests to arrive on HTTP URI addresses, and to allow incoming redirect_uri authorize request parameters to have HTTP URI addresses.
    Security Note: This is for development only.
  • Provider: The object provided by the application to process events raised by the Authorization Server middleware. The application may implement the interface fully, or it may create an instance ofOAuthAuthorizationServerProvider and assign delegates necessary for the OAuth flows this server supports.
  • AuthorizationCodeProvider: Produces a single-use authorization code to return to the client application. For the OAuth server to be secure the application MUST provide an instance forAuthorizationCodeProvider where the token produced by the OnCreate/OnCreateAsync event is considered valid for only one call to OnReceive/OnReceiveAsync.
  • RefreshTokenProvider: Produces a refresh token which may be used to produce a new access token when needed. If not provided the authorization server will not return refresh tokens from the /Token endpoint.

Account Management

 OAuth doesn’t care where or how you manage your user account information. It’s ASP.NET Identity which is responsible for it. In this tutorial, we will simplify the account management code and just make sure that user can login using OWIN cookie middleware. Here is the simplified sample code for the AccountController:

publicclassAccountController:Controller{publicActionResultLogin(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){var isPersistent =!string.IsNullOrEmpty(Request.Form.Get("isPersistent"));if(!string.IsNullOrEmpty(Request.Form.Get("submit.Signin"))){
                authentication.SignIn(newAuthenticationProperties{IsPersistent= isPersistent },newClaimsIdentity(new[]{newClaim(ClaimsIdentity.DefaultNameClaimType,Request.Form["username"])},"Application"));}}returnView();}publicActionResultLogout(){returnView();}publicActionResultExternal(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){foreach(var key inRequest.Form.AllKeys){if(key.StartsWith("submit.External.")&&!string.IsNullOrEmpty(Request.Form.Get(key))){var authType = key.Substring("submit.External.".Length);
                    authentication.Challenge(authType);returnnewHttpUnauthorizedResult();}}}var identity = authentication.AuthenticateAsync("External").Result.Identity;if(identity !=null){
            authentication.SignOut("External");
            authentication.SignIn(newAuthenticationProperties{IsPersistent=true},newClaimsIdentity(identity.Claims,"Application", identity.NameClaimType, identity.RoleClaimType));returnRedirect(Request.QueryString["ReturnUrl"]);}returnView();}}
privateTaskValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context){if(context.ClientId==Clients.Client1.Id){
        context.Validated(Clients.Client1.RedirectUrl);}elseif(context.ClientId==Clients.Client2.Id){
        context.Validated(Clients.Client2.RedirectUrl);}returnTask.FromResult(0);}privateTaskValidateClientAuthentication(OAuthValidateClientAuthenticationContext context){string clientId;string clientSecret;if(context.TryGetBasicCredentials(out clientId,out clientSecret)||
        context.TryGetFormCredentials(out clientId,out clientSecret)){if(clientId ==Clients.Client1.Id&& clientSecret ==Clients.Client1.Secret){
            context.Validated();}elseif(clientId ==Clients.Client2.Id&& clientSecret ==Clients.Client2.Secret){
            context.Validated();}}returnTask.FromResult(0);}

ValidateClientRedirectUri is used to validate the client with its registered redirect URL.ValidateClientAuthentication checks the basic scheme header and form body to get the client’s credentials.

The login page is shown below:

Review the IETF’s OAuth 2 Authorization Code Grant section now.  Provider (in the table below) isOAuthAuthorizationServerOptions.Provider, which is of type OAuthAuthorizationServerProvider, which contains all OAuth server events.

Flow steps from Authorization Code Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
  (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification. Provider.MatchEndpoint
Provider.ValidateClientAuthentication
AuthorizationCodeProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantAuthorizationCode
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync

A sample implementation for AuthorizationCodeProvider.CreateAsync and ReceiveAsync to control the creation and validation of authorization code is shown below.

privatereadonlyConcurrentDictionary<string,string> _authenticationCodes =newConcurrentDictionary<string,string>(StringComparer.Ordinal);privatevoidCreateAuthenticationCode(AuthenticationTokenCreateContext context){
     context.SetToken(Guid.NewGuid().ToString("n")+Guid.NewGuid().ToString("n"));
     _authenticationCodes[context.Token]= context.SerializeTicket();}privatevoidReceiveAuthenticationCode(AuthenticationTokenReceiveContext context){string value;if(_authenticationCodes.TryRemove(context.Token,out value)){
         context.DeserializeTicket(value);}}

The code above uses an in-memory concurrent dictionary to store the code and identity ticket and restore the identity after receiving the code. In a real application, it would be replaced by a persistent data store.

The authorization endpoint is for the resource owner to grant access to the client. Usually, it needs a user interface to allow the user to click a button and confirm the grant. OWIN OAuth middleware allows application code to handle the authorization endpoint. In our sample app, we use an MVC controller called OAuthController to handle it. Here is the sample implementation:

publicclassOAuthController:Controller{publicActionResultAuthorize(){if(Response.StatusCode!=200){returnView("AuthorizeError");}var authentication =HttpContext.GetOwinContext().Authentication;var ticket = authentication.AuthenticateAsync("Application").Result;var identity = ticket !=null? ticket.Identity:null;if(identity ==null){authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}var scopes =(Request.QueryString.Get("scope")??"").Split(' ');if(Request.HttpMethod=="POST"){if(!string.IsNullOrEmpty(Request.Form.Get("submit.Grant"))){
                 identity =newClaimsIdentity(identity.Claims,"Bearer", identity.NameClaimType, identity.RoleClaimType);foreach(var scope in scopes){
                     identity.AddClaim(newClaim("urn:oauth:scope", scope));}
                 authentication.SignIn(identity);}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Login"))){
                 authentication.SignOut("Application");
                 authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}}returnView();}}

The Authorize action will first check if the user has logged in to the authorization server. If not, the authentication middleware challenges the caller to authenticate using the “Application” cookie and redirects to the login page. (See highlighted code above.) If user has logged in, it will render the Authorize view, as shown below:

If the Grant button is selected, the Authorize action will create a new “Bearer” identity and sign in with it. It will trigger the authorization server to generate a bearer token and send it back to the client with JSON payload.

Implicit Grant

Refer to the IETF’s OAuth 2 Implicit Grant section now.

The Implicit Grant flow shown in Figure 4 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Implicit Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
  (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.

Since we already implemented the authorization endpoint (OAuthController.Authorize action) for authorization code grant, it automatically enables implicit flow as well.

Note: Provider.ValidateClientRedirectUri is used to validate the client ID with its redirection URL, which protects the implicit grant flow from sending the access token to malicious clients (Man-in-the-middle attack).

Resource Owner Password Credentials Grant

Refer to the IETF’s OAuth 2 Resource Owner Password Credentials Grant section now.

The Resource Owner Password Credentials Grant flow shown in Figure 5 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Resource Owner Password Credentials Grant section Sample download performs these steps with:
(A) The resource owner provides the client with its username and password.
(B) The client requests an access token from the authorization server’s token endpoint by including the credentials received from the resource owner. When making the request, the client authenticates with the authorization server. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantResourceOwnerCredentials Provider.TokenEndpoint AccessToken
Provider.CreateAsync
RefreshTokenProvider.CreateAsync
(C) The authorization server authenticates the client and validates the resource owner credentials, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantResourceOwnerCredentials:

privateTaskGrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.UserName,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps. It does not check the resource owners credentials. It assumes every credential is valid and creates a new identity for it. The new identity will be used to generate the access token and refresh token. Please replace the code with your own secure account management code.

Client Credentials Grant

Refer to the IETF’s OAuth 2 Client Credentials Grant section now.

The Client Credentials Grant flow shown in Figure 6 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(A) The client authenticates with the authorization server and requests an access token from the token endpoint. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantClientCredentials
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
 (B) The authorization server authenticates the client, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantClientCredentials:

privateTaskGrantClientCredetails(OAuthGrantClientCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.ClientId,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps.  Please replace the code with your own secure client management code.

Refresh Token

Refer to the IETF’s OAuth 2 Refresh Token section now.

The Refresh Token  flow shown in Figure 2 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(G) The client requests a new access token by authenticating with the authorization server and presenting the refresh token. The client authentication requirements are based on the client type and on the authorization server policies. Provider.MatchEndpoint
Provider.ValidateClientAuthentication RefreshTokenProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantRefreshToken
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
(H) The authorization server authenticates the client and validates the refresh token, and if valid, issues a new access token (and, optionally, a new refresh token).

Here is the sample implementation for Provider.GrantRefreshToken:

publicvoidConfigureAuth(IAppBuilder app){// Code removed for clarity     // Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}
privatevoidCreateRefreshToken(AuthenticationTokenCreateContext context){
     context.SetToken(context.SerializeTicket());}privatevoidReceiveRefreshToken(AuthenticationTokenReceiveContext context){
     context.DeserializeTicket(context.Token);}

Create a Resource Server which is protected by Access Token

 Create an empty web app project and install following packages in the project:

  • Microsoft.AspNet.WebApi.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth

Create a startup class and configure authentication and Web API. See AuthorizationServer\ResourceServer\Startup.csin the sample download.

[assembly:OwinStartup(typeof(ResourceServer.Startup))]namespaceResourceServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);ConfigureWebApi(app);}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.Auth.cs in the sample download.

usingMicrosoft.Owin.Cors;usingMicrosoft.Owin.Security.OAuth;usingOwin;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureAuth(IAppBuilder app){
            app.UseCors(CorsOptions.AllowAll);

            app.UseOAuthBearerAuthentication(newOAuthBearerAuthenticationOptions{});}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.WebApi.cs in the sample download.

usingMicrosoft.Owin.Security.OAuth;usingOwin;usingSystem.Web.Http;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureWebApi(IAppBuilder app){var config =newHttpConfiguration();// Web API configuration and services// Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(newHostAuthenticationFilter(OAuthDefaults.AuthenticationType));// Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name:"DefaultApi",
                routeTemplate:"api/{controller}/{id}",
                defaults:new{ id =RouteParameter.Optional});

            app.UseWebApi(config);}}}
  • UseCors method allows CORS for all domains.
  • UseOAuthBearerAuthentication method enables OAuth bearer token authentication middleware which will receive and validate bearer token from authorization header in the request.
  • Config.SuppressDefaultHostAuthenticaiton suppresses default host authenticated principal from the app, therefore all requests will be anonymous after this call.
  • HostAuthenticationFilter enables authentication just for the specified authentication type. In this case, it’s bearer authentication type.

In order to demonstrate the authenticated identity, we create an ApiController to output current user’s claims.

namespaceResourceServer.Controllers{[Authorize]publicclassMeController:ApiController{// GET api/<controller>publicIEnumerable<object>Get(){var identity =User.IdentityasClaimsIdentity;return identity.Claims.Select(c =>new{Type= c.Type,Value= c.Value});}}}

If the authorization server and  the resource server are not on the same computer, the OAuth middleware will use the different machine keys to encrypt and decrypt bearer access token. In order to share the same private key between both projects, we add the same machinekey setting in both web.config files.

<configuration><appSettings><!-- Keys removed for clarity. --></appSettings><system.web><compilationdebug="true"targetFramework="4.5"/><httpRuntimetargetFramework="4.5"/><machineKeydecryptionKey="Enter decryption Key here"validation="SHA1"validationKey="Enter validation Key here"/></system.web><runtime><!-- Keys removed for clarity. --></runtime></configuration>

Create OAuth 2.0 Clients

We use the DotNetOpenAuth.OAuth2.Client  NuGet package to simplify the client code.

Authorization Code Grant Client

This client is an MVC application. It will trigger an authorization code grant flow to get the access token from backend. It has a single page as shown below:

  • The Authorize button will redirect browser to the authorization server to notify the resource owner to grant access to this client.
  • The Refresh button will get a new access token and refresh token using the current refresh token.
  • The Access Protected Resource API button will call the resource server to get current user’s claims data and show them on the page.

Here is the sample code of the HomeController of the client.

usingConstants;usingDotNetOpenAuth.OAuth2;usingSystem;usingSystem.Net.Http;usingSystem.Web.Mvc;namespaceAuthorizationCodeGrant.Controllers{publicclassHomeController:Controller{privateWebServerClient _webServerClient;publicActionResultIndex(){ViewBag.AccessToken=Request.Form["AccessToken"]??"";ViewBag.RefreshToken=Request.Form["RefreshToken"]??"";ViewBag.Action="";ViewBag.ApiResponse="";InitializeWebServerClient();var accessToken =Request.Form["AccessToken"];if(string.IsNullOrEmpty(accessToken)){var authorizationState = _webServerClient.ProcessUserAuthorization(Request);if(authorizationState !=null){ViewBag.AccessToken= authorizationState.AccessToken;ViewBag.RefreshToken= authorizationState.RefreshToken;ViewBag.Action=Request.Path;}}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize"))){var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[]{"bio","notes"});
            userAuthorization.Send(HttpContext);Response.End();}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh"))){var state =newAuthorizationState{AccessToken=Request.Form["AccessToken"],RefreshToken=Request.Form["RefreshToken"]};if(_webServerClient.RefreshAuthorization(state)){ViewBag.AccessToken= state.AccessToken;ViewBag.RefreshToken= state.RefreshToken;}}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi"))){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;ViewBag.ApiResponse= body;}returnView();}privatevoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
         _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}}}

DotNetOpenAuth requires SSL by default. Since our demo is using HTTP, you need to add following setting in the config file:

<configuration><!-- Markup removed for clarity. --><dotNetOpenAuth><messagingrelaxSslRequirements="true"/></dotNetOpenAuth></configuration>
Security Note: Never disable SSL in a production app. Your login credentials are now being sent in clear-text across the wire. The code above is just for local sample debugging and exploration.

Implicit Grant Client

This client is using JavaScript to:

  1. Open a new window and redirect to the authorize endpoint of the Authorization Server.
  2. Get the access token from URL fragments when it redirects back.

The following image shows this process:

The client should have two pages: one for home page and the other for callback.

Here is the sample JavaScript code found in the Index.cshtml file:

<scripttype="text/javascript">(function($){var authorizeUri ='@(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath)';var tokenUri ='@(Paths.AuthorizationServerBaseAddress + Paths.TokenPath)';var apiUri ='@(Paths.ResourceServerBaseAddress + Paths.MePath)';var returnUri ='@Paths.ImplicitGrantCallBackPath';

        $('#Authorize').click(function(){var nonce ='my-nonce';var uri = addQueryString(authorizeUri,{'client_id':'7890ab','redirect_uri': returnUri,'state': nonce,'scope':'bio notes','response_type':'token',});

            window.oauth ={};
            window.oauth.signin =function(data){if(data.state !== nonce){return;}

                $('#AccessToken').val(data.access_token);}

            window.open(uri,'Authorize','width=640,height=480');});

        $('#CallApi').click(function(){
            $.ajax(apiUri,{
                beforeSend:function(xhr){
                    xhr.setRequestHeader('Authorization','Bearer '+ $('#AccessToken').val());},
                dataType:'text',
                cache:false,
                success:function(data){
                    console.log(data);
                    $('#output').text(data);}});});function addQueryString(uri, parameters){var delimiter =(uri.indexOf('?')==-1)?'?':'&';for(var parameterName in parameters){var parameterValue = parameters[parameterName];
                uri += delimiter + encodeURIComponent(parameterName)+'='+ encodeURIComponent(parameterValue);
                delimiter ='&';}return uri;}})(jQuery);</script>

Here is the callback handling code in SignIn.cshtml file:

<scripttype="text/javascript">(function($){function getFragment(){if(window.location.hash.indexOf("#")===0){return parseQueryString(window.location.hash.substr(1));}else{return{};}}function parseQueryString(queryString){var data ={},
                pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;if(queryString ===null){return data;}

            pairs = queryString.split("&");for(var i =0; i < pairs.length; i++){
                pair = pairs[i];
                separatorIndex = pair.indexOf("=");if(separatorIndex ===-1){
                    escapedKey = pair;
                    escapedValue =null;}else{
                    escapedKey = pair.substr(0, separatorIndex);
                    escapedValue = pair.substr(separatorIndex +1);}

                key = decodeURIComponent(escapedKey);
                value = decodeURIComponent(escapedValue);

                data[key]= value;}return data;}var fragments = getFragment();if(window.opener && window.opener.oauth && window.opener.oauth.signin){
            window.opener.oauth.signin(fragments);}
        window.close();})(jQuery);</script>
A best practice is to move the JavaScript to an external file and not embed it with the Razor markup. To keep this sample simple, they have been combined.

Resource Owner Password Credentials Grant Client

We uses a console app to demo this client. Here is the code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.GetClientAccessToken(new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}

Client Credentials Grant Client

Similar to the Resource Owner Password Credentials Grant, here is console app code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.ExchangeUserCredentialForToken("test","test",new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}
 
Leave a comment

Posted by on April 24, 2014 in C#, OAuth, Web API ASP.NET

 

Installing Apache Active MQ on Ubuntu

By: 

After creating a Sales Demonstration system for an industry trade show using Ubuntu 10.10, I decided to create a personal development system based on one of my personal favorite free operating systems, Ubuntu. An old laptop was pressed into service as a meager server on which I could refresh my admin skills and provide a target for testing prototype concepts rambling around my brain. One of the first services this little laptop will host is Apache Active MQ 5.4.2 which was released December of 2010. (Authors Note: This article has been updated to support Ubuntu 11 and ActiveMQ 5.5)

Although Ubuntu has a large collection of software available in many repositories, there is no way, currently, to perform an apt-get for Active MQ. It has to be installed by hand. Fortunately, this is a relatively simple matter. There are a couple of stumbling blocks which prevented a smooth install for me so I thought this article might help others avoid them.

Ensure you have Java installed

I prefer to have have the sun-java6-bin and sun-java6-jre packages for this purpose. I’m currently testing the free versions which come with Ubuntu. I have a separate link which describes installing sun-java on Ubuntu. It’s like 5 commands; no big deal.

Initial Install

Go to the download page for Apache Active MQ and select the latest available release tarball and extract it on your server.

tar xzf apache-activemq-5.5.0-bin.tar.gz


Move it to /opt where optional software package are intended to be placed.

sudo mv apache-activemq-5.5.0 /opt


The activemq scripts expect to find Active MQ installed in /opt/activemq. I personally do not like having a non-versioned directory like that. Moving the package to /opt/activemq as would be expected by the scripts can make it difficult months down the line to upgrade. What version is installed? Will you remember? Now, this is a personal preference, but I like to know at any time what versions of software I have installed so I generally create a sym-link so the script finds things where it expects and I can see what version is installed. It is also easier to switch versions by simply linking/opt/activemq to another directory containing a different version. If it works fine, I can delete the old version, if not, I can switch the like back all this happens without changing any of the scripts. Here is how I did it:

sudo ln -sf /opt/apache-activemq-5.5.0/ /opt/activemq

 

Add Non-Privileged Account

It’s never a good idea to run a service as root, so it is a common practice to add a dedicated user account which doesn’t have much authority and run the service as this account. This will have the added benefit of making the process easier to identify with tools such as ps and top.

sudo adduser -system activemq


Some (many?, most?) systems will give a system user a false login shell. This will keep theactivemq script from running so you will have to make sure the account uses the bash shell. First, open the /etc/passwd file in your favorite editor. Don’t forget to use sudo as it is a privileged file. Here is the line when using vi:

sudo vi /etc/passwd


Go to the end of the list of accounts and make sure the shell for this account looks something like the following line. Don’t worry about the numbers and such, but make sure the last argument contains /bin/bash and not something like /bin/false, for example, the line should look something like the following:

activemq:x:116:65534::/home/activemq:/bin/bash


Recursively change the ownership of the entire activemq directory to the activemq user you just added.

sudo chown -R activemq: /opt/apache-activemq-5.5.0/


Next, sym-link the init script provided by Active MQ to /etc/init.d/activemq:

sudo ln -sf /opt/activemq/bin/activemq /etc/init.d/


Tell Ubuntu to start Active MQ on boot:

sudo update-rc.d activemq defaults


At this point you will probably get a warning about missing LSB information. LSB information is a block of information which directs how the links are made. See http://wiki.debian.org/LSBInitScriptsfor more details.

Now, let’s build a default configuration file:

sudo /etc/init.d/activemq setup /etc/default/activemq


Change the owner and group of the config file:

sudo chown root:nogroup /etc/default/activemq


Change the file permissions so its read-write by root only:

sudo chmod 600 /etc/default/activemq

 

Editing the Configuration


Unfortunately, this is where you will have to begin searching through your configuration file and make changes specific to your version of software and setup. There have been some changes between releases of Active MQ so the instructions may not match what you see in your files.

Edit the newly generated /etc/default/activemq file. I’ll use vi:

sudo vi /etc/default/activemq


You’re looking for ACTIVEMQ_USER="". Enter the name of your activemq user name between the quotes.

Now we will configure the Active MQ broker to listen for JMX connections. Further down the file, un-comment the JMX configuration lines:

ACTIVEMQ_SUNJMX_START=”-Dcom.sun.management.jmxremote.port=11099 ”
ACTIVEMQ_SUNJMX_START=”$ACTIVEMQ_SUNJMX_START -Dcom.sun.management.jmxremote.password.file=${ACTIVEMQ_CONFIG_DIR}/jmx.password”
ACTIVEMQ_SUNJMX_START=”$ACTIVEMQ_SUNJMX_START -Dcom.sun.management.jmxremote.access.file=${ACTIVEMQ_CONFIG_DIR}/jmx.access”
ACTIVEMQ_SUNJMX_START=”$ACTIVEMQ_SUNJMX_START -Dcom.sun.management.jmxremote.ssl=false”
ACTIVEMQ_SUNJMX_START=”$ACTIVEMQ_SUNJMX_START -Dcom.sun.management.jmxremote”


The above configuration lines enable JMX on port 11099 and use two file to control access through JMX.

The next section will specify how the shutdown script will connect to the broker (via JMX) and log into the management console to issue the shutdown command. This line will connect to broker via port 11099 and log in as controlRole with a password of abcd1234. Keep these values (or whatever you change them to) in mind as you will need to make sure they are registered in thedata/jmx.password and data/jmx.access files in the next steps.

ACTIVEMQ_SUNJMX_CONTROL=”–jmxurl service:jmx:rmi:///jndi/rmi://127.0.0.1:11099/jmxrmi –jmxuser controlRole –jmxpassword abcd1234″
# ACTIVEMQ_SUNJMX_CONTROL=””
# Specify the queue manager URL for using “browse” option of sysv initscript
ACTIVEMQ_QUEUEMANAGERURL=”–amqurl tcp://localhost:61616″


Save your changes to the configuration file and exit the editor.

Now, you must edit the conf/jmx.password and conf/jmx.access files. Use the sample data they provide in the comments immediately above the lines. Remember to use the values you specified (or left alone) int the --jmxuser and --jmxpassword of the ACTIVEMQ_SUNJMX_CONTROL configuration line above.

Ensure that these JMX access control files are readable by only the activemq user account!

sudo chmod 600 /opt/apache-activemq-5.5.0/conf/jmx.password
sudo chmod 600 /opt/apache-activemq-5.5.0/conf/jmx.access


Doing that enables the init script to connect to the locally running software via JMX, a management console. Without this configured correctly you’re looking at issuing a shutdown command and seeing a ton of Java errors followed by thirty seconds (configurable) of timeout before the script finally issues a KILL on the process.

Now run the service

sudo /etc/init.d/activemq start


Then look in the /opt/activemq/data directory for the PID and log files. You can tail the log file to see what is happening:

sudo tail -f /opt/activemq/data/activemq.log

 

All Done!

The Active MQ broker should be running. You can test this in a variety of ways including using thetelnet command to connect to the broker on 61616, the JMX port on 11099 or more simply by opening a browser connection to the HTTP management port: http://localhost:8161

 

Copy From: http://servicebus.blogspot.com/2011/02/installing-apache-active-mq-on-ubuntu.html

 
Leave a comment

Posted by on April 10, 2014 in Apache ActiveMQ, Linux, Ubuntu

 

How to: Create Item Templates

The steps in the first procedure of this topic show you how to create an item template by using the Export Template wizard.

If you plan to use the item in a Windows Store app project, you’ll have to perform a few extra steps. The second procedure in this topic helps you accomplish that task.

Note Note
You cannot export templates for C++ projects.

To add a custom project item template to the Add New Item dialog box

  1. Create or open a project in Visual Studio.
  2. Add an item to the project and modify it if you want to.
  3. Modify the code file to indicate where parameter replacement should take place. For more information, see How to: Substitute Parameters in a Template.
  4. On the File menu, click Export Template.
  5. Click Item Template, select the project that contains the item, and click Next.
  6. Select the item for which you want to create a template, and click Next.
  7. Select the assembly references to include in the template, and click Next.
  8. Type the icon file name, preview image, template name, and template description, and click Finish.

    The files for the template are added to a .zip file and copied to the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.

To enable the item template to be used in a Windows Store project

  1. Follow the steps in the procedure above to export an item template.
  2. Extract the .vstemplate file from the .zip file that was copied to the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.
  3. Open the .vstemplate file in Notepad.
  4. In the .vstemplate file, add the following XML within the opening and closing <TemplateData> tag: <TemplateGroupID>WinRT-Managed</TemplateGroupID>.

    The following example shows the entire contents of a .vstemplate file after the line of XML <TemplateGroupID>WinRT-Managed</TemplateGroupID> has been added to it.

    <VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
      <TemplateData>
        <DefaultName>MyItemStoreTemplate.xaml</DefaultName>
        <Name>MyItemStoreTemplate</Name>
        <Description>This is an example itemtemplate</Description>
        <ProjectType>CSharp</ProjectType>
        <SortOrder>10</SortOrder>
        <Icon>__TemplateIcon.ico</Icon>
        <TemplateGroupID>WinRT-Managed</TemplateGroupID>
      </TemplateData>
      <TemplateContent>
        <References />
        <ProjectItem SubType="Designer" TargetFileName="$fileinputname$.xaml" ReplaceParameters="true">MyItemTemplate.xaml</ProjectItem>
        <ProjectItem SubType="Code" TargetFileName="$fileinputname$.xaml.cs" ReplaceParameters="true">MyItemTemplate.xaml.cs</ProjectItem>
      </TemplateContent>
    </VSTemplate>
    
  5. In Notepad, save the .vstemplate file and close it.
  6. Copy and paste the .vstemplate file back to the .zip file located in the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.

    If the Copy File dialog box appears, choose the Copy and Replace option.

You can now add an item based on this template to a Windows Store project by using the Add New Item dialog box.

Copy from: http://msdn.microsoft.com/en-us/library/tsyyf0yh.aspx

 
Leave a comment

Posted by on April 5, 2014 in C#, Window Application