Writing Our First Quantum Program

What You’ll Learn

  • How to set up a quantum solution and project in Visual Studio
  • The components of a Q# operation
  • How to call a Q# operation from C#
  • How to build and execute your quantum algorithm

Creating a Bell State in Q#

Now that you’ve installed the Microsoft Quantum Development Kit and seen how it works, let’s write your first quantum application. We’ll start with the simplest program possible and build it up to demonstrate quantum superposition and quantum entanglement. We will start with a qubit in a basis state |0⟩, perform some operations on it and then measure the result.

Step 1: Create a Project and Solution

Open up Visual Studio 2017. Go to the File menu and select New > Project.... In the project template explorer, under Installed > Visual C#, select the Q# Application template. Give your project the name MyFirstQuantumApplication.

Step 2 (optional): Update NuGet Packages

If you want to run the latest version, update the Microsoft.Quantum.Development.Kit and Microsoft.Quantum.CanonNuGet packages, as described in Updating a Package.

Step 3: Enter the Q# Code

Our goal is to create a Bell State showing entanglement. We will build this up piece by piece to show the concepts of qubit state, gates and measurement.

Visual Studio should have two files open: Driver.cs, which will hold the C# driver for your quantum code, and Operation.qs, which will hold the quantum code itself.+

The first step is to rename the Q# file to Bell.qs. Right-click on Operation.qs in the Visual Studio Solution Explorer, and select the Rename option. Replace Operation with Bell and hit return.

To enter the Q# code, make sure that you are editing the Bell.qs window. The Bell.qs file should have the following contents:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace Quantum.MyFirstQuantumApplication
{
    open Microsoft.Quantum.Primitive;
    open Microsoft.Quantum.Canon;
 
    operation Set (desired: Result, q1: Qubit) : ()
    {
        body
        {
            let current = M(q1);
            if (desired != current)
            {
                X(q1);
            }
        }
    }
 
	}

First, replace the string Operation with Set, and change the operation parameters (the first pair of parentheses) to contain the string desired: Result, q1: Qubit. The file should now look like above.

Add the following operation to the namespace, after the end of the Set operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
 
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

This operation (BellTest) will loop for count iterations, set a specified initial value on a qubit and them measure (M) the result. It will gather statistics on how many zeros and ones we’ve measured and return them to the caller. It performs one other necessary operation. It resets the qubit to a known state (Zero) before returning it allowing others to allocate this qubit in a known state. This is required by the using statement.
All of these calls use primitive quantum operations that are defined in the Microsoft.Quantum.Primitive namespace. For instance, the M operation measures its argument qubit in the computational (Z) basis, and X applies a state flip around the x axis to its argument qubit.

Note

As you can see, Q# uses C#-like semicolons and braces to indicate program structure.
Q# has an if statement that is very much like C#.

Q# deals with variables in a unique way. By default, variables in Q# are immutable; their value may not be changed after they are bound. The let keyword is used to indicate the binding of an immutable variable. Operation arguments are always immutable.

If you need a variable whose value can change, such as numOnes in the example, you can declare the variable with the mutable keyword. A mutable variable’s value may be changed using a set statement.

In both cases, the type of a variable is inferred by the compiler. Q# doesn’t require any type annotations for variables.
The using statement is also special to Q#. It is used to allocate an array of qubits for use in a block of code. In Q#, all qubits are dynamically allocated and released, rather than being fixed resources that are there for the entire lifetime of a complex algorithm. A using statement allocates a set of qubits at the start and releases those qubits at the end of the block. There is an analogous borrowing statement that is used to allocate potentially dirty ancilla qubits.
A for loop in Q# always iterates through a range. There is no Q# equivalent to a traditional C-style computer for the statement. A range may be specified by the first and last integers in the range, as in the example: 1..10 is the range 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. If a step other than +1 is needed, then three integers with .. between them are used: 1..2..10 is the range 1, 3, 5, 7, and 9. Note that ranges are inclusive at both ends.

The BellTest operation returns two values as a tuple. The operation’s return type is (Int, Int), and the return statement has an explicit tuple containing two integer variables. Q# uses tuples as a way to pass multiple values, rather than using structures or records.

Step 4: Enter the C# Driver Code

Switch to the Driver.cs file in Visual Studio. This file should have the following contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
 
namespace Quantum.MyFirstQuantumApplication
{
    public class Driver
    {
        static void Main(string[] args)
        {
            using (var sim = new QuantumSimulator())
            {
                // Try initial values
                Result[] initials = new Result[] { Result.Zero, Result.One };
                foreach (Result initial in initials)
                {
                    var res = BellTest.Run(sim, 1000, initial).Result;
                    var (numZeros, numOnes) = res;
                    System.Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
                }
            }
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
        }
    }
}

Step 5: Build and Run

Just hit F5, and your program should build and run!

The results should be:

The program will exit after you press a key.

Creating Superposition

Now we want to manipulate the qubit. First we’ll just try to flip it. This is accomplished by performing an X gate before we measure it in BellTest:

1
2
                    X(qubits[0]);
                    let res = M (qubits[0]);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
 
                    <span style="color: #ff0000;"><strong>X(qubits[0]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

You have seen that the results are now inversed.

However, everything we’ve seen so far is classical. Let’s get a quantum result. All we need to do is replace the Xgate in the previous run with an H or Hadamard gate. Instead of flipping the qubit all the way from 0 to 1, we will only flip it halfway. The replaced lines in BellTest now look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
		    <span style="color: #ff0000;"><strong>H(qubits[0]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

Now the results get more interesting:

Every time we measure, we ask for a classical value, but the qubit is halfway between 0 and 1, so we get (statistically) 0 half the time and 1 half the time. This is known as superposition and gives us our first real view of a quantum state.

Creating Entanglement

Now we’ll make the promised Bell State and show off entanglement. The first thing we’ll need to do is allocate 2 qubits instead of one in BellTest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
			// Qubit[2] in below line - This will allow us to add a new gate (CNOT) before we measure (M) in BellTest:
            using (qubits = Qubit[2])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
					Set(Zero, qubits[1]);
 
					H(qubits[0]);
					<span style="color: #ff0000;"><strong>CNOT(qubits[0], qubits[1]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
				//We also need to reset the second qubit before releasing it (this could also be done with a for loop). We'll add a line after qubit 0 is reset
				<strong><span style="color: #ff0000;">Set(Zero, qubits[1]);</span></strong>
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

If we run this, we’ll get exactly the same 50-50 result we got before. However, what we’re really interested in is how the second qubit reacts to the first being measured.

We’ll add this statistic with a new version of the BellTest operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
			<span style="color: #ff0000;"><strong>mutable agree=0;</strong></span>
			// Qubit[2] in below line - This will allow us to add a new gate (CNOT) before we measure (M) in BellTest:
            using (qubits = Qubit[2])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
					Set(Zero, qubits[1]);
 
					H(qubits[0]);
					<span style="color: #ff0000;"><strong>CNOT(qubits[0], qubits[1]);</strong></span>
                    let res = M (qubits[0]);
 
					<strong><span style="color: #ff0000;">if(M (qubits[1]) == res)
					{
						set agree=agree + 1;
					}</span></strong>
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
				//We also need to reset the second qubit before releasing it (this could also be done with a for loop). We'll add a line after qubit 0 is reset
				Set(Zero, qubits[1]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes, <span style="color: #ff0000;"><strong>agree</strong></span>);
        }
    }

There is now a new return value (agree) that will keep track of every time the measurement from the first qubit matches the measurement of the second qubit. Of course, we also have to update the Driver.cs file accordingly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (var sim = new QuantumSimulator())
            {
                // Try initial values
                Result[] initials = new Result[] { Result.Zero, Result.One };
                foreach (Result initial in initials)
                {
                    var res = BellTest.Run(sim, 1000, initial).Result;
                    var (numZeros, numOnes, agree) = res;
                    System.Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4} agree={agree,-4}");
                }
            }
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();

Our statistics for the first qubit haven’t changed (50-50 chance of a 0 or a 1), but now when we measure the second qubit, it is always the same as what we measured for the first qubit. Our CNOT has entangled the two qubits, so that whatever happens to one of them, happens to the other. If you reversed the measurements (did the second qubit before the first), the same thing would happen. The first measurement would be random and the second would be in lock step with whatever was discovered for the first.

I do hope this walkthrough will be enough for a kick start. I took help and guidance in steps from URL below.

https://docs.microsoft.com/en-gb/quantum/quantum-WriteAQuantumProgram?view=qsharp-preview

Detecting mobile device in Asp.net and node.js

http://hgoebl.github.io/mobile-detect.js/

mobile-detect.js

A loose port of Mobile-Detect to JavaScript.

This script will detect the device by comparing patterns against a given User-Agent string. You can find out information about the device rendering your web page:

  • mobile or not
  • if mobile, whether phone or tablet
  • operating system
  • Mobile Grade (A, B, C)
  • specific versions (e.g. WebKit)

 

Usage

Browser

<script src="mobile-detect.js"></script>
<script>
    var md = new MobileDetect(window.navigator.userAgent);
    // ... see below
</script>

Node.js / Express

var MobileDetect = require('mobile-detect'),
    md = new MobileDetect(req.headers['user-agent']);
// ... see below

General

var md = new MobileDetect(
    'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
    ' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
    ' Version/4.0 Mobile Safari/534.30');

// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding

console.log( md.mobile() );          // 'Sony'
console.log( md.phone() );           // 'Sony'
console.log( md.tablet() );          // null
console.log( md.userAgent() );       // 'Safari'
console.log( md.os() );              // 'AndroidOS'
console.log( md.is('iPhone') );      // false
console.log( md.is('bot') );         // false
console.log( md.version('Webkit') );         // 534.3
console.log( md.versionStr('Build') );       // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false

 

The Csharp Nullable Reference Types Preview

Blog Source: https://github.com/dotnet/csharplang/wiki/Nullable-Reference-Types-Preview

Nullable reference types are a feature currently planned for C# 8.0.

The preview installs on top of Visual Studio 2017 15.5.

Installation instructions

Please note: The preview is pre-release software. The features and behavior may change without notice. Please use for evaluation purposes only.

Please read all instructions before installing.

Installing

To install the preview:

  1. Download and extract Roslyn_Nullable_References_Preview.zip [latest 11/15/17]
  2. Close all instances of Visual Studio
  3. Run .\install.bat from the zip root

The script will install experimental versions of the Roslyn extensions for Visual Studio, replacing the existing Roslyn extensions. The extensions will be installed to the default hive of Visual Studio.

The extensions are supported on Visual Studio 15.5 only (Preview 4 or later). Before upgrading Visual Studio to a later version, uninstall the extensions using the uninstall.bat script.

Installing on a machine with multiple versions of Visual Studio is not supported.

Installing or uninstalling directly from Visual Studio (or double-clicking on the individual .vsix files) is not supported. There are dependencies between the extensions and the scripts are necessary to ensure the extensions are installed and uninstalled in order.

The extensions support .NET Framework projects only currently. Support for .NET Core projects should be available soon.

Uninstalling

To uninstall the preview:

  1. Close all instances of Visual Studio
  2. Run .\uninstall.bat from the zip root

The script will uninstall the experimental versions of the Roslyn extensions, restoring the original Roslyn extensions.

If uninstall fails uninstalling a particular extension, re-run uninstall.exe. In some cases, it may be necessary to run uninstall.exe several times to complete all extensions.

Feedback

Please write up your thoughts and send them to us at this Microsoft email address: nullable@microsoft.com.

We use email so that your feedback is a conversation between you and us at Microsoft. Community discussion is great, but can happen elsewhere. We don’t want to distract from understanding what you like and don’t like about this feature, and what changes you’d like to see. It is very likely that we will reply with follow-up questions.

Known issues

Enabling nullability warnings

The feature design envisions a separate compiler switch to enable warnings related to nullability. In the prototype, the Nullable Reference Types feature is tied to the C# language version and is enabled automatically with the default or latest version of the preview compiler (C# 8.0). To disable the feature use an explicit language version.

csc.exe -langversion:7.2 Legacy.cs

IntelliSense display

Intellisense displays the declared nullability rather than the nullability inferred from flow analysis.

intellisensedeclarednullability

Uninitialized fields warning

Uninitialized fields with non-nullable reference types are only reported for constructors that do not call this().

class Person
{
    public string FirstName;
    public string? MiddleName;
    public string LastName;

    // warning: FirstName, LastName uninitialized
    Person() 
    {
    }

    // no warning for FirstName
    Person(string lastName) : this()
    {
        LastName = lastName;
    }
}

Nullability tracking for fields and properties

Flow analysis tracks the nullability within a method body of locals and parameters only. Nullability is not tracked for fields or properties currently.

class Person
{
    ...
    public Address? Address;

    bool HasSameAddress(Person other)
    {
        if (Address == null) return other.Address == null;
        if (other.Address == null) return false;
        return Address.State ==        // warning: this.Address may be null
                other.Address.State && // warning: other.Address may be null
            ...;
    }
}

Method type inference

Method type inference uses the declared nullability rather than the nullability inferred from flow analysis.

T F<T>(T t) => t;

string? str = "";
int n = F(str).Length; // unnecessary warning: maybe null

Array initializers

Array initializers use the declared nullability rather than the nullability inferred from flow analysis.

string? str = "";
var array = new[] { str }; // string?[] not string[]
int n = array[0].Length;   // unnecessary warning: maybe null

Array covariance

Nullability mismatches are reported for array conversions that are co-variant with respect to nullability.

string?[] array = new string[] { "Hello", "World!" }; // unnecessary warning

Conversion to interfaces and base classes

Nullability mismatches of type arguments are not reported for conversions to interfaces or base classes.

void F(ICollection<string?> arg) { }
F(new List<string>()); // no warning

Deconstruction

Deconstruction drops nullability.

(string?, string) tuple = (null, "");
var (x, y) = tuple; // (string, string)
x.ToString();       // no warning

Tuple element conversions

Nullability mismatches are not reported for tuple element conversions.

object? x = ...;
string y = ...;
(object, string?) pair = (x, y); // no warning for x

Out var

Out var locals are treated as non-nullable regardless of the corresponding parameter declaration.

void TryGet(out string? s) => s = null;
TryGet(out var t); // string with null assignment warning
int n = t.Length;  // no warning

Conditional operator

Conditional operator uses the nullability of the type arguments from the first operand.

var dA = new Dictionary<string, object?>();
var dB = new Dictionary<string?, object>();
var dC = dA.Count > 0 ? dA : dB; // Dictionary<string, object?>, no warning
dC.Add(null, null); // warning: key is null

Type patterns

Flow analysis does not infer nullability of operand in is Type patterns.

object? obj = F();
if (obj is string str)
{
    obj.ToString(); // unnecessary warning: may be null
}

Type parameters

T? should be reported as an error unless T is constrained to a value type or reference type.

class C<T>
{
    T? F; // should report error: T is unconstrained
}

Frequently asked questions

Warnings from existing assemblies

Q: Why are warnings reported (or not reported) when calling methods in existing assemblies?

string? name = …;
if (string.IsNullOrEmpty(name)) // warning: may be null
    throw Exception();

string[] args = …;
string? arg = args.FirstOrDefault();
int n = arg.Length; // no warning

A: Reference types in member signatures in unannotated assemblies are currently treated as non-nullable. As a result, warnings are reported when calling a method with nullable values for parameters that allow null, and warnings are not reported when dereferencing return values that may be null. We expect to change the handling of unannotated assemblies so that reference types are treated as neither explicitly nullable nor non-nullable, with no warnings using such references.

Inferring null state from string.IsNullOrEmpty

Q: Can the compiler infer null state based on the return value of method such as string.IsNullOrEmpty?

return string.IsNullOrEmpty(name) ?
    0 :
    name.Length; // warning: may be null

There is a similar issue writing a method such as bool TryGetValue(TKey key, out TValue? value). The caller is forced to check value before derefencing, even if TryGetValue returns true.

A: We are investigating allowing annotations on methods that describe simple relationships between parameters and return value with respect to null values. The compiler could use those annotations when analyzing the calling code.

Warnings for initialized fields

Q: Why are warnings reported for fields that are initialized indirectly by the constructor, or outside the constructor?

A: The compiler recognizes fields assigned explicitly in the current constructor only, and warns for other fields declared as non-nullable. That ignores other ways fields may be initialized such as factory methods, helper methods, property setters, and object initializers. We will investigate recognizing common initialization patterns to avoid unnecessary warnings.

 

CSharp How To: Create Text File And Write To It

Continuing with my new C# “how-to” theme, the code snippet below shows how to create a text file and write content to it using the StreamWriter class. Remember to add the “using System.IO;” directive at the top. Note that there is a StreamWriter constructor which supports a Boolean parameter “append” – if you pass true for this parameter and the file already exists, the StreamWriter will append content to the file rather than overwrite the existing content.

const string TextFilePath = @“C:\WriteTest.txt”;

using (StreamWriter writer = new StreamWriter(TextFilePath))
{
writer.WriteLine(“Hello, world”);
writer.WriteLine(“Bye, world”);
}

Part 3-a – Dynamic CRM Series – Fetch some data using FetchXML in C#

LINK TO PART 1 – Connection

LINK TO PART 2 – Authentication

LINK TO PART 3 – Fetch Data through Fetch XML

LINK TO PART 4 – Fetch Data through CRM SDK

FetchXML is a proprietary query language that is used in Microsoft Dynamics 365 (online & on-premises). It’s based on a schema that describes the capabilities of the language.

Based on our previous two posts, let us say now we have our organization service proxy, and we need to fetch the list of accounts in our CRM SDK, here is what we can do.

Below is a simple method to fetch the names of accounts from accounts entity in dynamics crm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
public class BasicAccountInfo
    {
        public string code { get; set; }
        public string name { get; set; }
    }
 
        /// <summary>
        /// Get all user accounts in CRM
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="searchphrase"></param>
        /// <returns></returns>
        public List<BasicAccountInfo> GetUserAccountsWeb(string email, string password)
        {
            var finalResult = new List<BasicAccountInfo>();
            var crmService = GetCRMService(email, password);
            string fetchXml = "";
 
 
                fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
 			<entity name='account'>
    			<attribute name='name' />
    			<attribute name='accountid' />
    			<order attribute='name' descending='false' />
  			</entity>
			</fetch>";
            }
 
            EntityCollection result = crmService.RetrieveMultiple(new FetchExpression(fetchXml));
            var finalResult = (from data in result.Entities
                                       select new
                                       {
                                           code = ((Microsoft.Xrm.Sdk.Entity)(data)).Attributes["accountid"].ToString(),
                                           name = ((Microsoft.Xrm.Sdk.Entity)(data)).Attributes["name"].ToString()
                                       }).ToList();
 
 
            return finalResult;
        }

Part 2 – Dynamic CRM Series : User Authentication using C#

LINK TO PART 1 – Connection

LINK TO PART 2 – Authentication

LINK TO PART 3 – Fetch Data through Fetch XML

LINK TO PART 4 – Fetch Data through CRM SDK

In our last part of series we made a connection to Dynamic CRM through the CRM SDK.

In this part, we will see how we can authenticate a user using Dynamics CRM.

The following method obtains discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
        private TProxy GetProxy<TService, TProxy>(
            IServiceManagement<TService> serviceManagement,
            AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy<TService>
        {
            Type classType = typeof(TProxy);
 
            if (serviceManagement.AuthenticationType !=
                AuthenticationProviderType.ActiveDirectory)
            {
                AuthenticationCredentials tokenCredentials =
                    serviceManagement.Authenticate(authCredentials);
                // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. 
                // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
                return (TProxy) classType
                    .GetConstructor(new Type[] {typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse)})
                    .Invoke(new object[] {serviceManagement, tokenCredentials.SecurityTokenResponse});
            }
 
            // Obtain discovery/organization service proxy for ActiveDirectory environment.
            // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
            return (TProxy) classType
                .GetConstructor(new Type[] {typeof(IServiceManagement<TService>), typeof(ClientCredentials)})
                .Invoke(new object[] {serviceManagement, authCredentials.ClientCredentials});
        }

Following method retrieves the Authentication Credentials from CRM SDK based on authentication provider.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
	private AuthenticationCredentials GetCredentials<TService>(IServiceManagement<TService> service,
            AuthenticationProviderType endpointType, string _userName, string _password)
        {
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();
 
            switch (endpointType)
            {
                case AuthenticationProviderType.ActiveDirectory:
                    authCredentials.ClientCredentials.Windows.ClientCredential =
                        new System.Net.NetworkCredential(_userName,
                            _password,
                            _domain);
                    break;
                case AuthenticationProviderType.LiveId:
                    authCredentials.ClientCredentials.UserName.UserName = _userName;
                    authCredentials.ClientCredentials.UserName.Password = _password;
                    break;
                default: // For Federated and OnlineFederated environments.                    
                    authCredentials.ClientCredentials.UserName.UserName = _userName;
                    authCredentials.ClientCredentials.UserName.Password = _password;
                    if (endpointType == AuthenticationProviderType.OnlineFederation)
                    {
                        IdentityProvider provider =
                            service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName);
                        if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId)
                        {
                            authCredentials.SupportingCredentials = new AuthenticationCredentials();
                        }
                    }
 
                    break;
            }
 
            return authCredentials;
        }

And finally, our login method, it returns true if user is authenticated, and false if it is not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
public bool Login(string Email, string Password)
        {
            OrganizationService orgService;
            bool isValidUser=false;
            IServiceManagement<IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
                    new Uri(_discoveryServiceAddress));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;
 
            // Set the credentials.
 
            String organizationUri = String.Empty;
            // Get the discovery service proxy.
 
            bool result = false;
            try
            {
                AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType, Email,
                    Password);
                var response = GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials);
                result = response != null;
            }
            catch (Exception er)
            {
                result = false;
            }
 
            if (result)
            {
		//Although, our job is done here and we can return true, but if we need to get more user details regarding this logged in user then we can now execute the following calls. Specially the WhoAmIRequest() method of CRM SDK
                orgService = GetCRMService(Email, Password);
                Guid userid = ((WhoAmIResponse) orgService.Execute(new WhoAmIRequest())).UserId;
                dynamic systemUser = orgService.Retrieve("systemuser", userid, new ColumnSet(new string[] {"firstname", "lastname"}));
 
                string UserId = userid.ToString();
 
                string UserName = ((Microsoft.Xrm.Sdk.Entity) systemUser).Attributes["firstname"] + " " +
                                     ((Microsoft.Xrm.Sdk.Entity) systemUser).Attributes["lastname"];                
                isValidUser=true;
            }
            else
            {
                string UserId = "";
 
                string UserName = "";
            }
 
            return isValidUser;
 
        }

I really hope the code was helpful in kick starting your project in dynamics CRM, as authenticating a user from dynamics crm would be the first step if we want to start an application user dynamics CRM