Category Archives: How To

How-To: Create an image recognition app with Vuforia and HoloLens

Image recognition and interpretation is a very requested task into modern application. Either you want to identify a specific image or object or either you want to interpret what the users get in front their smartphone camera.

A technology that is becoming more and more popular among developers with this task is Vuforia. This framework can recognize a specific image and track it while the image is in the scene. The same goes to Custom 3D object, Cylinders, boxes, etc.

Moreover, Vuforia is widely accepted because we can use it with almost any device, from older and cheap Android smartphone to the most recent VR/AR/MX devices. In this post, we will use the Vuforia capabilities from Unity3D because it is also multi-platform.

Read More

How to make an Active/Passive STS using “Zermatt” Framework

Definition

“A Security Token Service (STS) is the plumbing that builds, signs, and issues security tokens using the interoperable protocols…”

“The “Zermatt” Framework makes it easy to build your own STS. It’s up to you to figure out how to implement the logic, or rules that drive it (often referred to as security policy).”

Active vs Passive

Active STSPassive STS
ImplementationWS-Trust protocolWS-Federation passive protocol
Built asWCF serviceASP.NET web application
HostingSelf-hosted / IISIIS

Steps to create our STS

  1. Implement a custom STS class
  2. Implement a custom STS configuration class
  3. Integrate the STS implementation with the hosting environment. (Here’s the differences between an active and passive STS implementation)

#1 – Implement a custom STS class

SecurityTokenService class handles the task of serializing and de-serializing the protocols. We can implement a custom STS by inheriting from this class and providing the following functionality:

  • Decide what claims to issue.
  • Decide what STS signing credentials the STS should use to sign the issued token.
  • Decide what relying party encrypting credentials the STS should use to encrypt the token before sending it (typically, the RP’s certificate information is shared out of band).
  • Decide what URL the response message goes to.

We need to override two methods from SecurityTokenService class:

GetScope

/// <summary>
/// This methods returns the configuration for the token issuance request. The configuration
/// is represented by the Scope class.
/// </summary>
/// <param name="principal">The caller's principal</param>
/// <param name="request">The incoming request</param>
/// <returns></returns>
protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
{
            // Validate the request's AppliesTo
            ValidateAppliesTo(request.AppliesTo);

            // Create the scope using the request and the STS signing credentials.
            // The request.appliesTo is automatically copied to the scope instance.
            Scope scope = new Scope(request, _signingCreds);

            // Setting the encrypting credentials
            scope.EncryptingCredentials = _encryptingCreds;

            // Set the ReplyTo address for the WS-Federation passive protocol
            // (THIS IS NOT USED IN THE WS-TRUST ACTIVE CASE)
            scope.ReplyToAddress = scope.AppliesToAddress + "/Default.aspx";

            return scope;
}

GetOutputSubjects

/// <summary>
/// This methods returns the claims to be included in the issued token.
/// </summary>
/// <param name="scope">The scope that was previously returned by GetScope method</param>
/// <param name="principal">The caller's principal</param>
/// <param name="request">The incoming request</param>
/// <returns>The claims to be included in the issued token.</returns>
public override ClaimsIdentityCollection GetOutputSubjects(Scope scope, IClaimsPrincipal principal, RequestSecurityToken request)
{
            IClaimsIdentity callerIdentity = (IClaimsIdentity)principal.Identity;
            ClaimsIdentity outputIdentity = new ClaimsIdentity();
            ClaimsIdentityCollection returnValue = new ClaimsIdentityCollection();

            // Name claim
            outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, callerIdentity.Name));

            // Age Claim (custom claim)
            outputIdentity.Claims.Add(new Claim("http://ZermattSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer));

            returnValue.Add(outputIdentity);
            return returnValue;
}

#2 – Implement a custom STS configuration class

We can implement a custom STS configuration class by inheriting from SecurityTokenServiceConfiguration class and configuring the following properties:

  • The STS IssuerName. Configure this by passing the value to the base class constructor.
  • The STS implementation class type. Configure this to point to your custom STS implementation class.
public class MySecurityTokenServiceConfiguration : SecurityTokenServiceConfiguration
{
        public MySecurityTokenServiceConfiguration()
            : base("HelloWorldSTS")
        {
            SecurityTokenService = typeof(MySecurityTokenService);
        }
}

#3 – Integrate the STS implementation with the hosting environment

The integration step varies between active and passive STSes.

Active STS

Hosted in a console application
SecurityTokenServiceConfiguration config = new MySecurityTokenServiceConfiguration();

// Add the STS endoint information
config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration("http://localhost:6000/HelloWorldSTS", new WSHttpBinding(), typeof(IWSTrustFeb2005SyncContract)));

// Create the WS-Trust service host with our STS configuration
using (WSTrustServiceHost host = new WSTrustServiceHost(
            config,
            new Uri("http://localhost:6000/HelloWorldSTS")))
{
                host.Open();
                Console.WriteLine("Active STS started, press ENTER to stop ...");
                Console.ReadLine();
                host.Close();
}

Hosted in a IIS Web-Based Service

We need to host it in IIS and set up a .svc file in the web site. In this case, the .svc file needs to contain a “Factory” parameter that points to WSTrustServiceHostFactory class or a class inherited from it (if programmatic configuration of the WCF service host is needed), and a “Service” parameter that points to a custom STS configuration class.

> .svc file:

<%@ServiceHost language=C#
                Factory="MyTypes.ActiveSTSFactory"
                Service="MyTypes.MySecurityTokenServiceConfiguration"%>

> Custom STS factory:

// Creating a WSTrustServiceHostFactory instance that is capable of handling WSTrust protocol
public class ActiveSTSFactory : WSTrustServiceHostFactory
{
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            // Set the required parameters and return the serviceHost instance
            ServiceHostBase serviceHost = base.CreateServiceHost(constructorString, baseAddresses);

            //
            // Perform any necessary imperative configuration of the serviceHost instance here
            //

            // return the configured ServiceHost instance to WCF activation
            return serviceHost;
        }
}

Passive STS

Add the custom classes to the web application’s code behind file

To expose the STS functionality that you have implemented by using the WS-Federation passive protocol, we can use the “Zermatt” Framework FederatedPassiveTokenService control. (Note: make sure that you install the “Zermatt” Framework controls into the Visual Studio toolbox).

  1. Create an ASP.NET web page to handle the WS-Federation passive protocol sign-in requests and add the FederatedPassiveTokenService control.
  2. Set the Service attribute of the control to the type name of your STS configuration class.
  3. When deployed, make sure that the intended authentication is enabled for the passive STS Web application. The FederatedPassiveTokenService control requires that the caller be authenticated before the page is rendered. If the caller of the page is not authenticated, the control will not do anything.
<idfx:FederatedPassiveTokenService
            ID="TokenService1"
            runat="server"
            Service="PassiveSTS.MySecurityTokenServiceConfiguration">
</idfx:FederatedPassiveTokenService>

How to replace our Sessions State strategy in Web Client Software Factory with a custom one

With Web Client Software Factory, when you require your application to store information in the session state, you can use the Composite Web Application Block class StateValue to store the information. This class supports code that runs both in a Web server environment (the session is available, and data is stored there) and outside of a Web server environment (no session is available, such as when you run your unit tests, and the data is stored in memory). Therefore, StateValue objects are useful to increase the testing surface of your application.

By default, StateValue objects use the ASP.NET Session when the code is running in a Web server. However, when persisting session information in ASP.NET web applications, developers may not want to rely on the ASP.NET Session state and might prefer to use their own persistence mechanism that, for example, uses a custom database.

The purpose of this post is to demonstrate how to create a new Session State Locator Service, and wire everything up so the StateValue injection occurs with your custom state persistence mechanism.

Implementation

1) Create a class that implements the IHttpSessionState interface. In this example, the session information is stored in a database.

public class MySessionState : IHttpSessionState
{
    private DatabaseHelper _dbHelper;
    private string _userName;
    
    public MySessionState()
    {
        _dbHelper = new DatabaseHelper(/* connection string */);
        _userName = HttpContext.Current.User.Identity.Name;
    }
    
    #region IHttpSessionState Members
    public object this[string name]
    {
        get { return dbHelper.GetValue(_userName, name); }
        set { dbHelper.SetValue(_userName, name, value); }
    }
    
    /// ...
    /// Our IHttpSessionState implementation
    /// ...
    #endregion
}

2) Create a class that implements the Microsoft.Practices.CompositeWeb.Interfaces.ISessionStateLocatorService interface. This service must return an instance of the class that you implemented in the previous step. The Composite Web Application Block uses this service to inject an instance of IHttpSessionState to StateValue objects.

public class MySessionStateLocatorService : ISessionStateLocatorService
{
    #region ISessionStateLocatorService Members
    
    public System.Web.SessionState.IHttpSessionState GetSessionState()
    {
        return new MySessionState();
    }
    
    #endregion
}

3) Create a class that inherits from WebClientApplication class. In this class you will register your custom ISessionStateLocatorService.

public class MyWebApplication : WebClientApplication
{
}

4) Override the AddRequiredServices method, and add code that removes the SessionStateLocatorService service and registers the custom one.

public class MyWebApplication : WebClientApplication
{
    protected override void AddRequiredServices()
    {
        base.AddRequiredServices();
        
        base.RootContainer.Services.Remove();
        this.RootContainer.Services.AddNew();
    }
}

 

Using the Custom Implementation

To use the custom implementation you have to update the Global.asax file to specify the custom global application class.

<%@ Application Language="C#" Inherits="MyCustomSessionState.MyWebApplication" %>

After that, you can use StateValue objects to manage state across requests in the same way as always:

1) Add a public field of type StateValue to your class, where T is the type of the object you want to persist across requests (in this case, the Customer class)

public StateValue _currentCustomer;

2) To access the info, use the Value property of the StateValue class.

// Set the value
_currentCustomer.Value = new Customer();

// Get the value
Customer customer = _currentCustomer.Value;

You can find more information about the StateValue class in the topic Developing Web Client Applications | How to: Use Session State with Unit Testing from the WCSF Documentation.

Important: The code available for download is provided “as is” with no warranties of any kind.

Attachment(s): MyCustomSessionState.zip

How to: Run the Contextual AutoComplete Bundle with a newer version of the Ajax Control Toolkit

Symptom

When you use a newer version of the AjaxControlToolkit in the AutoComplete QuickStart, a runtime error occurs:

“Parser Error Message: Could not load file or assembly ‘AjaxControlToolkit, Version=1.0.10618.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e’ or one of its dependencies.”

parserError

Root Cause

Since the AjaxControlToolkit.dll assembly is strong named, you must use the same assembly version that the AjaxControlToolkit.WCSFExtensions was compiled against (because the CLR attempts to bind –by default- with the exact version of an assembly that the application was built with).

Workaround

(Note: I smoke tested the AutoComplete QuickStart with AjaxControlToolkit 1.0.10920.x and I faced some issues; therefore, I suggest you not to run the QuickStart with this version. Read the known issues section for more details.)

You can use assembly version redirection to avoid having to rebuild the AjaxControlToolkit.WCSFExtensions.dll assembly. With the redirection mechanism, you can tell the CLR to redirect one assembly version to another:

1) Copy AjaxControlToolkit.dll (and all the sub-directories) located in the SampleWebSiteBin folder of the toolkit’s zip file to the LibAjaxControlToolkit folder of the QuickStart directory.

2) Open the AutoComplete QuickStart.

3) Add the following XML code to the AutoCompleteQuickStart Web.config file after the close tag. Replace the newVersion attribute to match the version of the AJAX Control Toolkit that you are using (for example, the current version is 1.0.10920.32880).

    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      
        <assemblyIdentity name="AjaxControlToolkit"
                          publicKeyToken="28f01b0e84b6d53e"
                          culture="neutral"/>
        <bindingRedirect oldVersion="1.0.10618.0"
                         newVersion="1.0.10920.32880"/>
      
    

Note: You can find the assembly version number in the properties of the reference to the AjaxControlToolkit assembly

AjaxControlToolkitVersion

4) Run the QuickStart.

 

AjaxControlToolkit (1.0.10920.x) issues

This section describes the issues faced when running the Autocomplete QuickStart with the AjaxControlToolkit 1.0.10920.x.

o No autocomplete list is shown until you hit the backspace key.

toolkit_issue1

o On Numeric fields, you get a list of “undefined” words. This seems to be related with an issue with this version of the the AjaxControlToolkit.

Note: This issue was resolved with changeset 27752. More information, go to here.

toolkit_issue2

How to: Upgrade to GAT/GAX July 2007 CTP

It is a minor update to the previous February 2007 CTP, and includes the following fixes and improvements:

  • Support for both Visual Studio 2005 and Visual Studio 2008 Betas 1 and 2 (Orcas)
  • Improved installer (using The Windows Installer XML (WiX))
  • Support for Registration as Normal User (RANU) and experimental hive
  • Enhanced support for installing Visual Basic templates

Upgrade:

Upgrade is recommended but not required as there are no critical fixes. If you wish to design and run guidance packages on VS2008, this version of GAX/GAT must be installed.

1) Download Guidance Automation Extensions July 2007 CTP

2) Download Guidance Automation Toolkit July 2007 CTP

3) Uninstall Enterprise Library

4) Uninstall Web Client Software Factory and Smart Client Software Factory

5) Unregister ALL existing guidance packages (if remain some)

If you want to manually unregister the guidance package, please check the following posts:

6) Uninstall previous version of GAT

7) Uninstall previous version of GAX

8) Install the new version of GAX (July 2007 CTP)

9) Install the new version of GAT (July 2007 CTP)

10) Install Enterprise Library

11) Install the guidance packages (WCSF, SCSF, etc.)

Enjoy!

More about new GAX/GAT July 2007 Released:

http://blogs.msdn.com/agile/archive/2007/08/02/new-gax-gat-july-2007-released.aspx