Select Page

## 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

## Prerequisites

• Microsoft’s quantum simulator, installed with the Quantum Development Kit, utilizes Advance Vector Extensions (AVX), and requires an AVX-enabled CPU. Intel processors shipped in Q1 2011 (Sandy Bridge) or later support AVX. We are evaluating support for earlier CPUs and may announce details at a later time.
• The simulator included with the Quantum Development Kit requires a 64-bit installation of Microsoft Windows to run.
• Visual Studio 2017

3. Navigate to your browser’s download folder and double click on the executable file whose name begins with vs_community. The file name will contain a sequence of numbers that varies.
4. Important!  When you are presented with the option to select the tools for specific workloads, check the boxes for Universal Windows Platform development and .NET desktop development

## Creating the Q# Development Environment

1. Install the Microsoft Quantum Development Kit
1. Browse to the Microsoft Quantum page and click the Download now button in the upper left.
2. On the Visual Studio Marketplace Quantum Development Kit page, click Download.
4. Your security software may present a confirmation pane. Click Allow, or the comparable term used by your browser.
5. The Quantum Development Kit extension will be installed in Visual Studio 2017.

In this section you will clone the quantum samples & libraries, and run a sample application to verify that your Q# environment is correctly installed and configured.

1. Clone the Microsoft Quantum Developer Kit Samples and Libraries GitHub repository.
1. Open Visual Studio.
2. Open the Connect view in Team Explorer (Team > Manage Connections)
3. Select Clone under Local Git Repositories and enter https://github.com/Microsoft/Quantum.git
4. Click Clone to clone the repo.
5. The repository will be cloned on your local computer and Visual Studio will switch to the Solution Explorer on the right populated with the libraries and samples.
2. Open the QsharpLibraries.sln solution.
• If prompted by the Install Missing Features pane, click Install to allow the installation of the necessary features. This is most often F# and tools used by some of the samples.
3. Validate your Q# environment by running the teleport sample program:
1. Right click on the TeleportationSample project in Samples > 0.Introduction folder of QsharpLibraries solution, and left click on “Set as Startup Project”.
2. Run the solution (F5.) If teleport runs and the output is similar to the following (has 8 rounds of successful teleportation with varying values True/False sent each round), your Q# environment is ready to support Q# development.

## .net – Kick Start (Introduction) to quantum computing

What is Quantum Computing?

A lot of computer technologies had come up within the last couple of years but Quantum computing is by far the greatest paradigm shift on part of computer science developers.

At the time Quantum computers were proposed first in 1980 by Richard Feynman and Yuri Manin, It was highly criticized as due to limitations in modeling even simpler systems at that time. As time goes on during 1900 and 1925 it still had been a vital part of chemistry, condensed matter physics, and other technologies.

Simulating Quantum mechanics is hard to even to simulate. The simplest explanation could be like this that “A matter, at a quantum level, exists in a host of different possible states or configurations at the same time. Unlike, classical probability theory, which comes to a point that “every statistical experiment will contain elements that are equally likely to happen”, these many configurations of the quantum state, which can be potentially observed, may interfere with each other like waves. This interference prevents the use of statistical sampling to obtain the quantum state configurations.

Limitation in hardware is yet another factor to hinder in the path of quantum computing. Let us say a system of electrons can be in say any of 40 positions. We can, therefore, say that electron is in any of 2^40 configurations (since each position can either have or not have an electron). To store this state in system memory we would require around 130gb of memory. If next, we allow it to be in 41 positions, there would be twice as many configurations which may require around 260 Gb of memory to store the quantum state.

The core of quantum computing is to store information in quantum states of matter and to use quantum gate operations to compute on that information, by learning to “program” quantum interference. In future, we might be able to crack RSA and ECDLF using quantum computing.

MICROSOFT QUANTUM DEVELOPMENT KIT

Microsoft has taken a step by introducing “Microsoft Quantum Development Kit”, that will help in making quantum programming and algorithm development more accessible. Quantum programming is a distinct art from classical programming requiring very different tools to understand and express quantum algorithmic thinking. Microsoft has brought the Quantum Development tools to unlock the quantum revolution for their tasks, problems, and solutions.

Q# (Q Sharp) was designed to address the challenges of quantum information processing, it is integrated into a software stack that enables a quantum algorithm to be compiled down to the primitive operations of a quantum computer.

## CSharp: Best way to handle null values

Lets say we receive some value and it is null and we are going to use that in our code

var divident=null;
var value=divident / 2;

Above line will throw a null exception.
To avoid that one might add a condition that could be

if(divident !=null)
{
var value=divident / 2;
}

a better way could be like below:

var value= (divident ?? 0) / 2;

## C-sharp : Write a webjob in a website

Many a times in our web projects we require a process to run seperate from the main thread of website. We had a scenario once to host our asp.net website on Windows Azure. Different ways to do this.

The following file types are supported:

• .cmd, .bat, .exe (using Windows cmd)
• .ps1 (using PowerShell)
• .sh (using Bash)
• .php (using PHP)
• .py (using Python)
• .js (using Node.js)
• .jar (using Java)

a- Write the code in global.asax startup method and run a timer. But that will run inside the main thread of website so it is not advisable to do that, as any sort of crash in either website or the timer thread will cause the pool to restart.

b- Write a Windows Service, this is a classic model if we have a Virtual machine in place, but if we have hosted our website as a Windows Azure Website, then this will not work.

c- If we host a Windows Azure website, which is a common scenario, Windows Azure provides an option to configure the webjob host from the control panel where we can assign different properties like Triggering [continous, manual] and scheduling.

The Windows Azure WebJobs SDK is a framework that simplifies the task of adding background processing to Windows Azure Web Sites.

Aside from the main project, create a new C# Console application.

First, we need to install “Azure WebJobs SDK”, we can add it through nuget module in our Visual Studio project.

To create a new WebJobs-enabled project, you can use the Console Application project template and enable WebJobs deployment as explained in the previous section. As an alternative, you can use the WebJobs new-project template:

• Use the WebJobs new-project template for an independent WebJobCreate a project and configure it to deploy by itself as a WebJob, with no link to a web project. Use this option when you want to run a WebJob in a web app by itself, with no web application running in the web app. You might want to do this in order to be able to scale your WebJob resources independently of your web application resources.
• Use the WebJobs new-project template for a WebJob linked to a web projectCreate a project that is configured to deploy automatically as a WebJob when a web project in the same solution is deployed. Use this option when you want to run your WebJob in the same web app in which you run the related web application.

1. Click File > New Project, and then in the New Project dialog box click Cloud > Azure WebJob (.NET Framework).
2. Follow the directions shown earlier to make the Console Application project an independent WebJobs project.
1. Right-click the web project in Solution Explorer, and then click Add > New Azure WebJob Project.

The Add Azure WebJob dialog box appears.

2. Complete the Add Azure WebJob dialog box, and then click OK.

## Deploy a WebJobs project

A WebJobs project that you have linked to a web project deploys automatically with the web project. For information about web project deployment, see How-to guides > Deploy app in the left navigation.

To deploy a WebJobs project by itself, right-click the project in Solution Explorer and click Publish as Azure WebJob….

For an independent WebJob, the same Publish Web wizard that is used for web projects appears, but with fewer settings available to change.

After it is created, in Program.cs

static JobHost Host = null;

static void Main()
{

var config = new JobHostConfiguration();

if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}

Host = new JobHost(config);

//Place Your code here if we want to execute a specific method after the job is triggered like below.

Host.RunAndBlock();

}

After we build the project, create a release.

Now from the Windows Azure panel, we can configure it using steps below.

## Create a continuous WebJob

1. In the Azure portal, go to the App Service page of your App Service web app, API app, or mobile app.
2. Select WebJobs.
3. In the WebJobs page, select Add.
4. Use the Add WebJob settings as specified in the table.

Using Steps above, Webjob will start running if its a continous trigger, other wise manually if its set as a manual trigger.

Azure WebJobs has made a potentially difficult and complex feature an easy and simple one to implement. It’s stable, scalable, and easy to modify as our needs change. If you haven’t checked out Azure WebJobs yet, you should, it can be used for a wide variety of needs.

## C-sharp Cache Image returned from asp.net webapi

Hey folks, well recently i developed some web service that return image as file from a web service method. User pass us a URL like below:

This return image of user with id=100

Lets say we list 100 users on a page, and bind this URL to image src attribute, whenever the page loads, it will make 110 calls to the service and page stays busy until all images are loaded.

To tackle this, all i did was below HIGHLIGHTED IN BOLD:

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 [HttpGet] [EnableCors(origins: "*", headers: "*", methods: "get", PreflightMaxAge = 600)] [Route("DownloadFile")] [Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)] public async Task<httpresponsemessage> DownloadFile(int FileId) { var result = Task.Factory.StartNew(() => { var regact = DownloadFileContent(FileId); //returns us the bytes of file based on Id provided. return regact; });   await result;   if (result.Result == null) { HttpResponseMessage resultNoFile = new HttpResponseMessage(HttpStatusCode.NoContent); return resultNoFile; } else { byte[] fileContent = Convert.FromBase64String(result.Result.DocumentBody);   HttpResponseMessage results = new HttpResponseMessage(HttpStatusCode.OK); var stream = new System.IO.MemoryStream(fileContent); results.Content = new StreamContent(stream); results.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(result.Result.MimeType);   results.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(259200) };   results.Headers.Add("Cache-Control", "public, max-age=259200"); return results; } } </httpresponsemessage>

[Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]

and following chunk into the code block.