Make a smaller randomised list from another list

A part of the quiz app I’ve been working on requires that the user chooses how many questions they want to answer from a pool of questions represented by integers in ascending order. That pool of questions is a large list whose elements are copied into a temporary list, the latter having its elements shuffled into a random order. Then the number of questions specified by the user is trimmed off from the start of the temporary list and assigned to the smaller list.


private List<int> yourlargelist;
private List<int> yoursmalllist;
private int numberofelementsforsmalllist;
List<int> yourtemporarylist = new List<int>(yourlargelist);
Random rand = new Random();
int n = yourtemporarylist.Count();
while (n > 1)
{
n–;
int k = rand.Next(n + 1);
int value = yourtemporarylist[k];
yourtemporarylist[k] = yourtemporarylist[n];
yourtemporarylist[n] = value;
}
yoursmalllist = yourtemporarylist.Take(numberofelementsforsmalllist).ToList();

So the process occurs like this:
numberofelementsforsmalllist: 4
yourlargelist: 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60
yourtemporarylist: 56, 60, 52, 55, 57, 53, 50, 54, 51, 58
yoursmalllist: 56, 60, 52, 55

I came up with this by combining two solutions from StackOverFlow.

http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp

http://stackoverflow.com/questions/3428242/how-do-i-truncate-a-list-in-c

Special thanks to grenade and Tim Robinson.

Find all decimals with the same integer

To retrieve all decimal values in a column that share the same integer value as another specified decimal value, use the floor() function as shown below:

Generic example:


select columnofdecimals
from yourtable
where floor(columnofdecimals) = 10.0;

Applied example:

The example I have provided comes from a quiz app that I’m still working on to help me study toward my Microsoft certifications. You can find many such websites and Google Play apps that do what I am making. Some of them will not have many questions, most likely because of copyright issues, in the sense that the questions which the apps were made for were based on official publications. Mine is too if you look closely at the screenshot further down.

If you go through the Training Kits for Microsoft certifications, you will find that they provide overall objective and sub-objective numbers. The former have no questions but the latter do.

In my app, I’ve included both objective numbers with and without a decimal value (e.g. 8.0). The aim was that in a dropdown box (combobox in C#), the user could select the overall objective number (e.g. 8.0) and be tested on all the questions for the sub-objectives (i.e. 8.1 and 8.2).

sqlfloorfunction-1

So the SQL code would be something like:


declare @dropdownselection as decimal
set @dropdownselection = 8.0
select q.QID
from Questions as q
where floor(q.ObjNum) = @dropdownselection
order by q.QID;

This blog was inspired during a webinar promoting FireBootCamp by Marlon from SSW that I was online for earlier today. He basically said that if you solve a problem, you should blog about it.

As rudimentary as this problem is, I hope it does help someone, because I was way off trying to find a non-existent wildcard for decimals. Remember to always check for existing SQL functions.

Install Android Studio on Windows 7 VirtualBox machine

This post covers how to install Android Studio on a Windows 7 guest on VirtualBox. I’ve incorporated the virtual machine element because Android Studio updates may get problematic, and rolling back to a previous step during installation when failures occur is much faster than troubleshooting, or worst-case scenario, starting installation from scratch.

I recommend taking a virtual machine snapshot at the end of each step to prevent headaches.

Step 1.    Install VirtualBox and the VirtualBox Extension Pack
https://www.virtualbox.org/wiki/Downloads

It is very important that the version number for VirtualBox and the Extension Pack are the same (or close enough). Check for compatibility on the Virtualbox site e.g. VirtualBox-4.3.20-96997-Win.exe and Oracle_VM_VirtualBox_Extension_Pack-4.3.20-96996.vbox-extpack.

The extension connects the virtual machine to the host-connected Android device. To install the extension from VirtualBox, go to File > Settings > Extensions > then click the Add package button.

androidstudio-01

Create a virtual machine in VirtualBox with Windows 7 64-bit, over 40GB space, and over 6GB RAM. Then install the Oracle Guest Additions by clicking Devices > Insert Guest Additions CD image…

androidstudio-02

If the executable doesn’t automatically start, just check the VM’s disk drive.

androidstudio-03

Step 2.    Install the latest Java Development Kit
http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html

androidstudio-04

It is very important to match the installer (whether x86 or x64) to your system.
Do not attempt to install JDK x86 on Windows x64. I did this with an earlier version of Android Studio and it failed to run properly.

Create a new environment system variable named JAVA_HOME and set its path for the JDK e.g. C:\Program Files\Java\jdk1.8.0_40.

androidstudio-05

Step 3. Install Android Studio
https://developer.android.com/sdk/index.html#top

androidstudio-06

Make sure to be logged in using an Administrator account before running the installer. During the installation, do not set the Android SDK Location to anything other than the default i.e. leave it as C:\Users\AdministrativeUserAccount\AppData\Local\Android\sdk. Attempting to change this to a directory like C:\sdk\ will cause the application to fail.

androidstudio-10

Ensure your host and guest PCs are connected to the Internet before running Android Studio for the first time or proceeding with the next step, otherwise the following “Unable to access Android SDK add-on list error will appear.

androidstudio-17

Step 4.    Run Android Studio and install APIs
When running Android Studio for the first time, it will connect to the Internet and run Android SDK Manager. I personally recommend not installing the most recent API, as this tends to be beta and may force you to do a bit of tinkering.
Install the API that matches or is above your Android device’s build.

Be careful with the tick boxes because ticking those already indicated with “Installed” status will remove them.

androidstudio-21

Step 5.    Create a new Android Studio project
Just follow through using the defaults.

androidstudio-24

If Windows Security Alerts appear, simply untick the boxes or click Cancel.

androidstudio-28
androidstudio-29

Depending on your VMs processing speed, the rendering and indexing may take several minutes.

androidstudio-30
androidstudio-31

The Android Studio interface should appear similar to this when ready:

androidstudio-32

As a side note, I tried installing API 22 in the previous step, but it produced the following errors after creating a new project.
Problem 1: When trying to open activity_main.xml, the preview panel fails to load and returns the error: “Rendering Problems Exception raised during rendering: action_bar”
androidstudio-33

Problem 2: The following classes could not be instantiated;
– android.support.v7.widget.Toolbar
– android.support.v7.internal.widget.ActionBarContextView
androidstudio-34

To solve Problem 2, I just restarted Android Studio, but for Problem 1, I rolled back my virtual machine and chose not to install API 22. Though I imagine the problem will be resolved in future updates.

Step 6. Test guest OS connection to USB host-connected Android device
Connect the Android device to the host PC. While the virtual machine is running, go to Machine > Settings > USB > then click the USB icon with the green cross.

androidstudio-35

Take note that the guest OS will always attempt to find the device on the same USB port you have it connected to using this option.

androidstudio-36

Click the Android device and it will appear on the USB Device Filters list.

androidstudio-37

If the guest OS does not detect the Android device, shut down the VM and turn it back on. Log into the guest OS, then pull out and plug back in the Android device, making sure that the device’s screen is unlocked. You should now be able to view the devices contents via the guest OS Windows Explorer.

androidstudio-38

Step 7.    Set up Android device for USB debugging
From your device, go to Settings > About phone > then tap Build number 7 times. Turn on Developer options and turn on USB debugging.

Step 8.    Install device’s USB driver to test apps on
For a full list of OEMs, go to http://developer.android.com/tools/device.html. The drivers are expected to be executables that install files into your C:\Program Files folder.

Double-check that your device driver was properly installed by going to Device Manager. If the device is listed under Other Devices, the driver did not install successfully. If the device appears under Universal Serial Bus Controllers, the installation was successful.

Step 9. Open the HelloWorld project in Android Studio
Unplug then replug the Android device. A prompt should appear on the device: “Allow USB debugging”, then click OK on the device.

Open the Android Device Monitor (Android-shaped icon beside the help icon) and the device will appear as “Online”.

androidstudio-41

Click the green play button to run the app.

androidstudio-40

A prompt will appear, click Choose a running device and select your device, then click OK.

androidstudio-39

Congratulations, hopefully you now have the HelloWorld app running on your device.

Excel VBA ActiveSheet.Paste error

This post covers a small Excel VBA problem, where it was believed that a recent Windows update somehow disabled the proper working of the ActiveSheet.Paste method.

One of our finance people wrote VBA macro code that ran fine for years until today.

A small snippet of the error-inducing code merely involves copying the values from one sheet to another:


Sheets("First sheet").Select
Cells.Select
Selection.Copy
Sheets("Second sheet").Select
Range("A1").Select
ActiveSheet.Paste

When the code executes via an Excel UI button, the application returns a “Microsoft Excel has stopped working” prompt and simply hangs from there, thus forcing us to kill it off with Task Manager.

vbaactivesheetpaste1

Stepping through the code, the error occurred at ActiveSheet.Paste, wherein the VBA Editor threw a similar prompt, but with problem details:

vbaactivesheetpaste2

Finance assumed that it was due to a recent Windows update, but various Excel forums show that this error has occurred for people as far back as 2009 and with no solid solution.

I worked around the problem by rewriting the code so that it copied the sheet under a new name instead of copying the values, which made more sense anyway. Fortunately for me the first sheet being copied did not contain any formatting nor formulae to be concerned about:


Dim wb As Workbook
Set wb = ThisWorkbook
Application.DisplayAlerts = False
Dim ws As Worksheet
For Each ws In wb.Worksheets
If (ws.Name Like "Second Sheet*") Then
ws.Delete
End If
Next
Application.DisplayAlerts = False
Sheets("First Sheet").Copy after:=ThisWorkbook.Sheets("First Sheet")
ActiveSheet.Name = "Second Sheet"

view raw

gistfile1.vb

hosted with ❤ by GitHub

After I sent the amended code to Finance, I did a bit of experimentation. I tested the original hanging code in VMs running fresh Windows 7 & 8, i.e. without Windows Updates, and across Excel 2007, 2010, and 2013. In all those cases ActiveSheet.Paste worked, but on machines that had recently run Windows Update, the macro froze Excel.

Unfortunately, I have not yet been able to identify what fix or update triggered the error, if this is the case. Since there does not appear to be a ruckus over it on the MSDN forums, I am chalking this one up as something that can be easily coded around anyway.

But if I do manage to find anything out, I will follow up here.

SQL Server Data Tools Table Import Wizard error

This post covers an error that occurs during the Table Import Wizard for SSAS tabular projects. It’s a small problem I remember being mentioned back when I did an SQL Server for BI short course hosted by UTS and SSW.

When creating your first OLAP cube, an “OLE DB or ODBC error: Login failed for user…” error may appear during the data import.

mssqldatatools-1

In the second screen of the Table Import Wizard, the user authentication specified is used to log on, but not conduct the actual data import.

mssqldatatools-2

On the third screen titled Impersonation Information, choosing Service Account is where the error occurs, because by default the Service Account for SSAS tends to be NT AUTHORITY\NETWORK SERVICE and generally it does not have database permissions. One way to “amend” this may be to add the Service Account to the Security Logins of the database instance and to the database being imported, though it isn’t what I would normally do.

Adjusting built-in accounts defeats the notion of segregation of duties. Rather than the previous method, specifying a Windows user name and password seems to be the better option. In a personal sandbox you can use your own login and for production you can have a Windows account created specifically for the SSAS work. It is simply more prudent.

mssqldatatools-5

This separation of user credentials for different purposes may trip up beginners. For further reading about Impersonation Information:
https://msdn.microsoft.com/en-us/library/gg492180.aspx
https://msdn.microsoft.com/en-us/library/ms187597.aspx

Using VBA to password protect Excel files

In this post I describe my VBA solution which involves bulk password protecting Excel files in nested folders.

At a previous job, one of my tasks was to open dozens of workbooks in different subfolders and click a macro button in each, which password protected them. Although it was only an occasional task, it was unnecessarily time-consuming. Had I known about VBA back then, I certainly would have done something about it. This post is my solution to such a problem.

Of course, there are countless tools available to hack Excel’s built-in password protection, but it’s possible for whatever reason, that businesses out there are still insistent on using it.

Context:

excelvbapwdsf-1

The base folder C:\Statistics\ has subfolders each representing a marketing area in NSW e.g. Inner West, North Shore, North West etc. Each subfolder contains the target Excel files to be password protected. Those folders also each have an archive folder where the Excel files from the previous month will be moved to.

The Excel files themselves are generated from another system with their file names suffixed with the appropriate year and month. The macro code itself is stored in the macro-enabled Excel file named “Password Protection” in the base folder. When run, this code can password protect 14 Excel files of the current month and move 14 from the previous month into their respective archive folder in about 30 seconds.

Code:


Option Explicit
Public Sub PasswordProtectStatFiles()
Dim Path As String
Dim Subpath As String
Dim Folders As New Collection
Dim File As String
Dim Item As Variant
Dim Wbk As Workbook
Dim cMonth As Date
Dim tMonth As String
Dim lMonth As String
Dim pswrd As String
Dim fsoWbk As Object
Dim wPath As String
Dim aPath As String
Dim pCount As Integer
Dim mCount As Integer
Path = "C:\Statistics\"
Subpath = Dir(Path & "*", vbDirectory)
cMonth = Date
tMonth = Format(cMonth, "yyyymm")
lMonth = Format(DateAdd("m", -1, cMonth), "yyyymm")
pswrd = InputBox("Please type a password.")
pCount = 0
mCount = 0
Do While Not Subpath = ""
Select Case Subpath
Case ".", "..", "Statistics.xlsm"
Case Else
Folders.Add Item:=Subpath, Key:=Subpath
End Select
Subpath = Dir()
Loop
Application.DisplayAlerts = False
For Each Item In Folders
On Error Resume Next
wPath = Path & Item & "\"
aPath = Path & Item & "\archive\"
File = Dir(wPath & "\*.xls*")
Do While File ""
If InStr(File, tMonth) > 0 Then
Set Wbk = Workbooks.Open(Path & Item & "\" & File)
Wbk.Password = pswrd
Wbk.Save
Wbk.Close
pCount = pCount + 1
Else
If InStr(File, lMonth) > 0 Then
Set fsoWbk = CreateObject("scripting.filesystemobject")
fsoWbk.CreateFolder (aPath)
fsoWbk.MoveFile Source:=wPath & File, Destination:=aPath
mCount = mCount + 1
End If
End If
File = Dir()
Loop
Next Item
Application.DisplayAlerts = True
MsgBox "Process complete. " & pCount & " files password protected and " & mCount & " files archived."
End Sub

view raw

gistfile1.txt

hosted with ❤ by GitHub

Discussion:

I have to give credit to HansV from the Microsoft forums. The Do While Not loop that collects the subfolder names came from here.

I was a bit iffy about having workbook passwords hard-encoded into a macro, so I put a prompt in for the user to designate one instead. The On Error Resume Next was necessary to deal with any non-relevant files that could have been mistaken as subfolders. I did consider using proper error handling to report those files, but it probably would get annoying for users if they deliberately wish to leave files there for whatever reason.

Since I’m new to VBA, I’d appreciate any advice for a better approach or for making the code more efficient, so please feel free to comment.

Microsoft Excel VBA at USYD

webcomic01

Today was my 3rd and last class for Microsoft Excel VBA hosted by the University of Sydney’s Centre for Continuing Education and instructed by John Cummings.

This introductory programming course concentrates a lot on how to think like a programmer and covers basic object oriented concepts through simple VBA exercises. Practical areas covered include familiarity with Excel’s VB editor, the Excel Object Model, how to write functions and macros, and basic debugging.

John Cummings himself is a serious and honest instructor. On Day 2 he warned us that in a hypothetical room of programmers proposing their languages to solve a business solution, anyone who dares mention VBA would from thereon be ignored by every other programmer in that room. Hence the little comic I drew at the start of this post.

John warned us that VBA is notorious for poor implementations due to faults in the legacy VB language, and the existence of “developers” who use the macro recorder to do all their work. He further cautioned that whenever we propose to use VBA in such a situation, to always add that VBA “…can be programmed in an industrial way”.

Overall the course is a great introduction to VBA and programming in general, and the college facility itself is excellent. But I strongly caution to veteran developers or those looking for a specific work solution that this course would not meet such immediate needs. Having done a bit of Java and C# in the past, I admit the conceptual how-to-program content felt like slow-going revision, but the Excel VBA tips and gotchas taught along the way were very informative.

Install .NET Framework 3.5 on Windows Surface Pro 3

This is a tutorial on how to install the .NET Framework 3.5 on a Windows Surface Pro 3 running Windows 8.1.

My department purchased Surface Pro 3 slates for management late last year, but we found that some of our in-house applications stopped working properly. After trying various things such as the Backward Compatibility Wizard (which failed), I realised that it was simply because Windows 8.1 did not have .NET 3.5 installed by default, which the applications were originally compiled on.

However, using Windows Features alone to install .NET 3.5 kept causing an error in my case. After ticking .NET Framework 3.5 (includes .NET 2.0 and 3.0) and clicking OK,
dotnet35install-02
Windows Features attempts to search for the required files,
dotnet35install-03
but ends up offering to download files from Windows Update.
dotnet35install-04
When I accepted it and attempted to download the needed files,
dotnet35install-05
it errors with Error code: 0x800F0906
dotnet35install-06
In my case this error appeared regardless of whether I attempted to run Windows Update before or after trying to install .NET Framework 3.5.
dotnet35install-07

To install .NET Framework 3.5 on Windows 8.1 via Windows Features, I found in one forum (I’ll credit if I ever find it again) that an adjustment to Group Policy needs to be done to change the way that Windows Features pulls the necessary files.

Step 1. Enable Group Policy Objects
Open Microsoft Management Console by pressing the Windows key and typing mmc.
Click File, then Add/Remove Snap-in…
dotnet35install-09
Highlight Group Policy Objects from the list of Available snap-ins, click Add >, then OK
dotnet35install-10
A Select Group Policy Object prompt should appear. Just accept the defaults as shown and click Finish.
dotnet35install-11

Step 2. Adjust Windows Update download settings via Local Computer Policy
From Microsoft Management Console, expand the Local Computer Policy icon in the left panel, then Administrative Templates. Click on the System folder, then in the middle pane, scroll down and double-click the Specify settings for optional component installation and component repair option.
dotnet35install-12
By default, component installation and repair is disabled, so click the Enabled radio button, which should permit changes in Options at the bottom right. Tick Contact Windows Update directly to download repair content instead of Windows Server Update Services (WSUS). Click OK.
dotnet35install-14
A prompt will appear requesting to Save console settings to Console1. Click Yes.
dotnet35install-15
You can just save it onto the desktop.

Step 3. Install .NET Framework 3.5 via Windows Features
From Control Panel, navigate to Windows Features and tick .NET Framework 3.5 and all its subcomponents. When prompted, click Download files from Windows Update.
dotnet35install-17
The files should now download successfully,
dotnet35install-18
and changes should be applied.
dotnet35install-19
Hopefully, you should reach the Windows completed the requested changes as I did.

JSON for Windows 8 and IIS

This is a tutorial on how to install JSON onto Windows 8.1 using IIS for development purposes. It is similar to and sort of follows on from my previous post for setting up PHP and MySQL.

I’ve posted this because I have been following the JSON tutorials by Adam Khoury, a cool web development YouTuber. In his JSON tutorials he says you can’t run JSON off of your local machine, but it is possible to configure via IIS for Windows. Guessing he just didn’t know how to at the time of filming.

Step 1. Enable Internet Information Services IIS
Open the Control Panel, click Programs, click Turn Windows features on or off. Tick Internet Information Services, then expand that folder and the nested Web Management Tools, then tick IIS Management Console.
Next expand the nested Application Development Features folder, then tick ASP, CGI, and Common HTTP Features. This may require a computer restart when clicking OK.
jsoniisinstall-0

Step 2. Configure JSON for IIS Manager
Open IIS Manager as administrator.
In the Connections panel to the left, expand the server tree, the Sites folder, and click Default Web Site.
In the Features View panel in the centre, double-click MIME Types.
jsoniisinstall-02
Click Add…
Set MIME Type as follows:
jsoniisinstall-03
Click OK
jsoniisinstall-04
Return to the Features View panel, double-click Handler Mappings
jsoniisinstall-05
In the Actions panel to the right, click Add Script Map…
Fill in the form as follows:
jsoniisinstall-06
If an Add Script Map error prompt appears, just click Yes.
jsoniisinstall-07
The new mapper handling should now appear in your list
jsoniisinstall-08

Step 3. Test JSON
The following JavaScript code was appropriated from Adam Khoury’s YouTube tutorials. If you are looking to learn web development, his channel is great, especially if going through 600 page books is not your cup of tea.

Navigate to C:\inetpub\wwwroot\
Create a new html file named jsontest.html and paste the following code in it:


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "jsontestlist.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data) {
results.innerHTML += "ID: " + data[obj].code + " codename: " + data[obj].alterego + " species: " + data[obj].species + " identity: " + data[obj].alias + "</br >";
}
}
}
hr.send(null);
results.innerHTML = "requesting…";
}
</script>
</head>
<body>
<br>
<h3>This shows how to parse a JSON file</h3>
<div id="results">
<script type="text/javascript">ajax_get_json();</script>
</div>
</body>
</html>

view raw

Step3aTestJSON

hosted with ❤ by GitHub

Create a new json file named jsontestlist.json and paste the following code in it:


{
"u001": { "code":"A001", "alterego":"Superman", "alias":"Clark Kent", "species":"Kryptonian" },
"u002": { "code":"A002", "alterego":"Batman", "alias":"Bruce Wayne", "species":"Human" },
"u003": { "code":"A003", "alterego":"Wonder Woman", "alias":"Diana Prince", "species":"Amazonian" }
}

view raw

Step3bTestJSON

hosted with ❤ by GitHub

Again, characters belong to DC Comics and Warner Bros and are only used here as a data example. I’ll do Marvel next time.

Go to your browser and navigate to http://localhost/jsontest.html
Your page should look something like this:
jsoniisinstall-09

Raw MySQL and PHP for Windows 8 and IIS

This is a tutorial on how to install PHP and MySQL onto Windows 8.1 using IIS for development purposes, and without using additional software platforms like XAMPP, ZendServer, or EasyPHP etc or using tools like Microsoft’s Web Platform Installer. I’ve skimmed through over a dozen books on PHP & MySQL, and none of them show you how to install them, mostly because it’s not the typical approach given the tedious configuration.

Step 1. Download and install Microsoft Visual C++ 2012 Redistributable Package (x86) from:
http://www.microsoft.com/en-au/download/details.aspx?id=30679
mysqlphpiisinstall-01

Step 2. Download and install the MySQL Community Server MSI file from:
dev.mysql.com/downloads/mysql/
mysqlphpiisinstall-02

Step 3. Download the non-thread-safe PHP zip file from:
http://php.net/downloads.php

mysqlphpiisinstall-03
Extract all the contents into its own folder e.g. C:\php\
mysqlphpiisinstall-04
Add the PHP installation path to your Environment Variables path (do not forget to prefix it with a semicolon).
You get there by right-clicking your PC icon in Windows Explorer, click Properties, and under Computer name, domain, and workgroup settings click the Change settings link. Click the Advanced tab, then the Environment Variables… button at the bottom. Under the System variables section, edit the Path variable.
mysqlphpiisinstall-05
Go into the PHP installation folder and rename the php.ini-development file to php.ini.
mysqlphpiisinstall-06
A file extension error prompt appears. Just click Yes.
mysqlphpiisinstall-07
Open the file in a text editor and make the following changes:
– uncomment extension=php_mysqli.dll
– uncomment then set date.timezone = "Australia/Sydney"
– uncomment then set extension_dir = "C:\php\ext"
– uncomment extension=php_gd2.dll
– uncomment extension=php_mbstring.dll

Step 4. Enable Internet Information Services IIS
Open the Control Panel, click Programs, click Turn Windows features on or off. Tick Internet Information Services, then expand that folder and the nested Web Management Tools, then tick IIS Management Console.
Next expand the nested Application Development Features folder, then tick CGI, and lastly, tick the Common HTTP Features. This will require a computer restart when clicking OK.
mysqlphpiisinstall-08

Step 5. Configure PHP for IIS Manager
Open IIS Manager as administrator.
In the Connections panel to the left, expand the server tree, the Sites folder, and click Default Web Site.
In the Features View panel in the centre, double-click the Handler Mappings.
mysqlphpiisinstall-09
In the Actions panel to the right, click Add Module Mapping…
Fill in the form as follows:
mysqlphpiisinstall-10
Click the Request Restrictions… button.
Under Mapping tab, ensure “Invoke handler only if request is mapped to:” is ticked and the File radio button is selected.
mysqlphpiisinstall-11
Click OK until exited.
If an Add Module Mapping error prompt appears, just click Yes.
mysqlphpiisinstall-12
Step 6. Test PHP
Create a file named test.php with the following code:

<?
php phpinfo();
?>

Save the file into C:\inetpub\wwwroot\
Open a browser and navigate to localhost\test.php
mysqlphpiisinstall-13

Step 7. Test MySQL
Open the MySQL Command Line Client and type the following code.


CREATE DATABASE jl;
USE jl;
CREATE TABLE species (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT, description TEXT) DEFAULT CHARACTER SET utf8;
INSERT INTO species (id, name, description) VALUES (1, 'Human', 'Earth origin.');
INSERT INTO species (id, name, description) VALUES (2, 'Kryptonian', 'Super-powered alien humanoid.');
INSERT INTO species (id, name, description) VALUES (3, 'Amazonian', 'Human female with heightened combat abilities.');
CREATE TABLE justiceleaguer (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, alias TEXT, alterego TEXT, species INT) DEFAULT CHARACTER SET utf8;
INSERT INTO justiceleaguer (id, alias, alterego, species) VALUES (1, 'Superman', 'Clark Kent', 2);
INSERT INTO justiceleaguer (id, alias, alterego, species) VALUES (2, 'Batman', 'Bruce Wayne', 1);
INSERT INTO justiceleaguer (id, alias, alterego, species) VALUES (3, 'Wonder Woman', 'Diana Prince', 3);

view raw

Step7TestMySQL

hosted with ❤ by GitHub


btw Superman, Batman, and Wonder Woman are all property of DC Comics and Warner Bros, I’m just using them as a data example because they’re cool

Step 8. Test PHP connection to MySQL
Open C:\inetpub\wwwroot\test.php, then replace all its contents with the following code:


<?php
define ('dbuser', 'root');
define ('dbpassword', 'password');
define ('dbhost', 'localhost');
define ('dbname', 'jl');
$dbcon = @mysqli_connect (dbhost, dbuser, dbpassword, dbname) OR die ('Could not connect to MySQL: ' . mysqli_connect_error () );
mysqli_set_charset($dbcon, 'utf8');
$result = mysqli_query($dbcon, "SELECT justiceleaguer.alias, justiceleaguer.alterego, species.name FROM justiceleaguer LEFT JOIN species ON justiceleaguer.species = species.id ORDER BY justiceleaguer.id;");
while($row = mysqli_fetch_array($result)) {
echo $row['alias'] . " is " . $row['alterego'] . ", a " . $row['name'] . ". <br>";
}
mysqli_close($dbcon);
?>

Refresh the browser. If using Internet Explorer, a blank screen may be returned. In this case, delete your browsing history, then restart IE. Then go to localhost/test.php
mysqlphpiisinstall-14

Congratulations. You have manually installed and configured MYSQL and PHP for Windows 8 without using any third-party software. But if you are uncomfortable wioth using the MySQL Command Line to do your MySQL, you can install phpMyAdmin to make it simpler.

Step 9. Optional: Download the English phpMyAdmin zip file from:
http://www.phpmyadmin.net/home_page/downloads.php
mysqlphpiisinstall-15
Extract the folder inside phpMyAdmin-4.2.7-english.zip into C:\inetpub\wwwroot
Rename the folder from “phpMyAdmin-4.2.7-english” to “phpmyadmin”
Test the installation by going to http://localhost/phpmyadmin/
An error should appear stating “HTTP Error 403.14 – Forbidden The Web server is configured to not list the contents of this directory”.
mysqlphpiisinstall-16
Open IIS Manager, in Features view double-click Directory Browsing.
mysqlphpiisinstall-17
In Actions panel to the right, click Enable. From the Features view ensure Time, Size, Extension, and Date are ticked. Click Apply from the Actions pane. If it is greyed out, simply untick then retick one of the tickboxes in the Features view.
mysqlphpiisinstall-18a
Under the Connections panel, expand the folders nested beneath Sites until the phpadmin folder is visible, then click on it. Double-click Default Document in the Features view.
mysqlphpiisinstall-19a
In the Actions panel, click Add…, then in the Add Default Document prompt type index.php and click OK.
mysqlphpiisinstall-20
Ensure that index.php is at the top of the list.
mysqlphpiisinstall-21
In Windows Explorer navigate back to C:\inetpub\wwwroot\phpmyadmin\
Rename the file config.sample.inc.php to config.inc.php, then open it in a text editor.
mysqlphpiisinstall-22
Edit the file as follows:

$cfg['Servers'][$i]['auth_type'] = 'http';
$cfg['Servers'][$i]['host'] = '127.0.0.1';

Test the installation by refreshing your browser and go to http://localhost/phpmyadmin/.
A Windows Security prompt appears asking for username and password. Use what you configured for MySQL.
mysqlphpiisinstall-23
phpMyAdmin is now installed.
mysqlphpiisinstall-24

While trying to install these, I admit I came across a few bumps along the way. These sites helped me out.
http://www.iisunderground.com/installing-php-on-iis/
http://www.somacon.com/p108.php
http://www.wikihow.com/Install-phpMyAdmin-on-Your-Windows-PC

Honestly, this is a re-blog from one of my old sites, but I’m adding it here as reference for a blog I’ll be doing later on regarding JSON.