Sunday, 19 June 2016

Single Sign-on with ASP.NET Forms Authentication

Recently one of my colleague developed 2 web applications with only 1 web application has the login page and end users are required to login first before able to access to both web applications. At first he thought of sharing session values between 2 web applications, but since he's deploying to IIS under the same website with different virtual directory and uses Forms Authentication, he can achieve Single Sign-on by adding machineKey element with same value for both web applications into the web configuration file.

There are other ways to achieve Single Sign-on such as Token Based Authentication, but we will talk about that some other time. In this post, we will focus on how to achieve Single Sign-on with Forms Authentication.

Before you proceed, make sure that you know what is Forms Authentication. In case you do not know what is it, you can refer to this link as your starting point. https://support.microsoft.com/en-us/kb/301240.

Assuming you have 2 web applications with 1 of them has configured the authentication element in your web configuration file that looks like the following.

[web.config]
<authentication mode="Forms">
  <forms loginUrl="Login.aspx" name=".CookieName" />
</authentication>

Duplicate this section to your second web application's web configuration file. If you requires the website to redirect back to your first web application's login page, change the loginUrl attribute to point it to the first web application's login page. Make sure the mode attribute in authentication element and name attribute in forms element are the same for both web applications.

Next, you need to add the machineKey element into both of your web applications. The machineKey element will be as shown below.

[web.config]
<machineKey validationKey="BA36D1A3FAFEAFF8D2F78E4BC1D3EBEC6925124C9B56464E113EAFC90101942453D46DE50B6C22FCA62661B5CAEA4E3E9DEB0B21DE1B3D96850132EFEA8A43A9"
      decryptionKey="2C615FEDED6AEE0C38464A15B5452E4D103BD947B9C665E4"
      validation="SHA1"
      decryption="AES"/>

You may be wondering where do the values come from or how to generate it. Well, there are few ways to generate it and I will only show you 1 of the methods, in which can be done through IIS Manager.
1) Open up IIS Manager.

2) On the left pane, click on either one the nodes named with machine name, Sites, any websites or any virtual directories.

3) On the middle pane, under ASP.NET section, click Machine Key,

4) Select your desired Validation method, Encryption method and leave the rest as default.

5) On the right pane, click Generate Keys.

6) On the middle pane, the text boxes under Validation key and Decryption Key will be filled with random text. Copy them and add it to your machineKey element.

Note: Do not click Apply, which is located at the right pane as we do not need to save the settings in IIS Manager.

Once you have done, publish both of your web applications into the same website with different virtual directory. Log in to your web application and you will be able to access both applications. If you have implement logout features on both of your applications, logging out on either one of the applications will prevent end users to access both web applications until they have log in again.

You may refer to the sample project here. https://1drv.ms/u/s!Aj2AA7hoIWHmgmjgFt4GXfd6JFVf




Saturday, 18 June 2016

[Visual Studio] Get Unit Test Code Coverage Including Services with .testsettings File

Code Coverage is used to check how much of the code you have written is being tested with your unit test. So to measure your code coverage, just click on "Analyze Code Coverage for All Tests" under "Run..." in "Test Explorer" window. By doing so, visual studio will execute all your unit test and automatically open up "Code Coverage Results" window, in which will shows how much of your code is being covered in percentage.

But what if you have a unit test method that calls the service (WCF, WEB API, etc) and need to measure the code coverage for the services. By clicking on "Analyze Code Coverage for All Tests", the visual studio will only show you the code coverage result for projects that are directly referenced by your unit test project. So, for visual studio to display code coverage for your services, some extra settings and steps need to be done and will need to rely on .testsettings File.

To create a new Test Settings file, right click on a solution folder, hover to "Add" and click "New Item..." (create 1 in your solution if you do not have it). A Test Settings window will be prompted. This window is where you need to do some configuration to enable code coverage.

The following are the steps to be done to configure the Test Settings file:
1) On the left pane of this window, click "Data and Diagnostics".
Test Settings Window
Test Settings
2) On the middle pane under "Data and Diagnostics for selected role:", click on "Code Coverage (Visual Studio 2010)"'s check box to enable it.
Test Settings - Data and Diagnostics
Data and Diagnostics
3) In case "Code Coverage (Visual Studio 2010)" deselected after tick the checkbox, select it again and click Configure. A window titled "Code Coverage (Visual Studio 2010) Detail" will be prompted.

4) Click "Add Assembly..." button. A window titled "Choose Assemblies to Instrument" will be prompted.
Test Settings - Data and Diagnostics - Code Coverage (Visual Studio 2010) Detail Window
Code Coverage (Visual Studio 2010) Detail
5) Browse for the necessary DLLs used/generated by your services project & the unit test project's DLL. Make sure those DLLs contain .pdb file reside in the same folder. Click "Open" button once you are done.
Test Settings - Data and Diagnostics - Code Coverage (Visual Studio 2010) Detail - Choose Assemblies to Instrument Window
Choose Assemblies to Instrument
6) Make sure those DLLs that you have browsed earlier are shown under "Select artifacts to instrument" and are ticked. Click "OK" button once you have verified.
Test Settings - Data and Diagnostics - Code Coverage (Visual Studio 2010) Detail Window
Code Coverage (Visual Studio 2010) Detail with DLLs
7) On the left pane of "Test Settings" window, click "Test Results Names". It is optional whether you want to change the name. But if you leave it as default, please remember how the name is being defined as shown on the "example". This is important as you will need to navigate to the folder later.
Test Settings - Test Results Names
Test Results Names
8) Click "Apply" button and click "Close" button.

Once you have done configure the Test Settings file, the file need to be included with your Unit Test. To do so, click "TEST" menu, which is located on top of your visual studio. Hover to Test Settings and click "Select Test Settings File". Browsed for the Test Settings file that you have created and configured earlier.

Before running the unit test, make sure your services is up and running and the "Code Coverage Results" window is shown on your visual studio. In case you can't locate it, just initiate a code coverage test and the "Code Coverage Results" window will appear. Once you are ready, click "Run All" or "Run Selected Tests" (depend on whether you want to get code coverage for all tests or just measure the specific test).

After all the unit tests have been executed, the result of the code coverage will be generated into a file named "data.coverage" and placed in "TestResults" folder located in your own project. So to show the result on "Code Coverage Results" window in your visual studio:
1) Click "Import Results" icon button.
Visual Studio - Code Coverage Results Window
Code Coverage Results Window
2) On the "Open Coverage File" window, open "TestResults" folder.
Visual Studio - Code Coverage Results - Open Coverage File WIndow
Open Coverage File Window
3) Open the latest generated folder and the folder name must based on the option you defined on the step 7th earlier.
Visual Studio - Code Coverage Results - Open Coverage File - Latest Folder
Select Latest Folder with Name as Defined in TestSetttings File
4) Open "In" folder and navigate deep in until you see the file "data.coverage".
Visual Studio - Code Coverage Results - Open Coverage File - Latest Folder - data.coverage File
data.coverage File
5) Choose the file and the result will be shown on "Code Coverage Results" window.
Visual Studio - Code Coverage Results Window
data.coverage File's Result
Refer to the following link for the sample demo project. https://1drv.ms/u/s!Aj2AA7hoIWHmgmdSKO6YHPcACD5j. This sample is being developed in layered based on this link. http://serena-yeoh.blogspot.com/2014/03/layered-architecture-solution-guidance.html

Saturday, 11 June 2016

[LocalDB] Connecting to LocalDB failed for Web Application Hosted in IIS [Error Code 50]

In my previous blog post http://jaryl-lan.blogspot.my/2014/08/localdb-connection-to-localdb-failed.html. If you deploy your application to a client machine or server without installing the local database runtime, you will hit with an error of not able to access your local database file. But what if your application is a web based application that are hosted in IIS, you might hit with another error as shown below,

Unable to access SQLLocalDB: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. )

Based on the above error message, it will be tough to identify what is going wrong but at the bottom of the message specifies that you can get more information in the Windows Application event log. So open up the event viewer and navigate to Application log, you will notice a few duplicate events shown as follows.

Event 1:
Windows API call SHGetKnownFolderPath returned error code: 5. Windows system error message is: Access is denied.
Reported at line: 422.

Event 2:
Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.

Event 3:
Unexpected error occurred while trying to access the LocalDB instance registry configuration. See the Windows Application event log for error details.

From the events, the keyword here is "user profile is not loaded". So to get the user profile loaded, do the following:
(1) Open IIS Manager.
(2) On the left pane, navigate to Application Pools.

IIS Manager - Application Pools


(3) Select the Application Pool used by your application, right click on it and click "Advanced Settings...". A window titled "Advanced Settings" will be prompted.

IIS Manager - Application Pools - Advanced Settings


(4) Look for Load User Profile under Process Model section and set its value to True.

IIS Manager - Application Pools - Advanced Settings - Load User Profile

(5) Recycle your Application Pool.

IIS Manager - Application Pools - Recycle

Once done, rerun your web application and it will be able to access the localdb. If you noticed that your application loads very slow on the first load, it is due to the localdb instance has not fully started yet. To identity which instance launched by your web application, navigate to Details tab in Task Manager, locate the instance sqlservr.exe with the username is same as your application pool's name (That is if your application pool identity is set to ApplicationPoolIdentity).

Source: https://blogs.msdn.microsoft.com/sqlexpress/2011/12/08/using-localdb-with-full-iis-part-1-user-profile/

Friday, 18 December 2015

Pineng PN-920 20000mAh Review

Couple of weeks back I have bought the Pineng PN-920 from 11Street for a discounted price, but too bad it doesn't comes with a free pouch. It is original and can be verified at pineng official website http://pineng.com.my/Product-Verification. It is huge, bigger and heavier than most of the phones.

pineng 920 input output light pineng 920 Description pineng 920 output led light pineng 920 input led light pineng 920 torch light pineng 920 brand pineng 920 button
PN-920

The light is blue for the LCD screen on the PN-920 and it can be quite irritating and uncomfortable to the eyes due to its brightness. The LCD screen will display some information whenever you perform the following:
  • Hold the button for a couple of seconds (Display the remaining percentage with the word "OUT")
  • Double click the button (Display the remaining percentage with the word "OUT" and turn on the flashlight)
  • Charging the PN-920 (Display the remaining percentage with the word "IN")
  • Charging the phone with 5V 1A port and/or 5V 2.1A port (Display the remaining percentage with the word "OUT" and shows 5V 1A and/or 5V 2.1A)
The LCD display can be turned off by holding the button for a couple of seconds and turning off the flashlight can be done by clicking the button once. For more details about PN-920, you can check it out at http://pineng.com.my/PINENG-PN-920-20000mAh-Power-Bank-Black.

** NOTE: The following result may not be accurate due to the measurement are done through software and not dedicated hardware tools. The result is just to give you a general idea on how well it performs.

** NOTE: Using different micro usb cable may affect the charging speed. Other than that, the phone charging speed is slower when charging above 80%.

Measuring on how many times it can fully charged a phone may not be that accurate, this is due to different phones have different battery capacity and some phones consume more battery in the background. So I hope that the following test will give you a general idea on how many times it can fully charge a phone and how fast it can charge a phone with 5V 1A. To test how well PN-920 perform, the following are used:
  • Samsung Galaxy Note 5
  • Pineng PN-920
  • Micro usb cable (Pineng)
  • Battery Monitor Widget
  • Stopwatch
This test will be done in every 1 hour time frame to charge the Samsung Galaxy Note 5 while plugged on 5V 1A port on the PN-920. The phone screen, wifi, data is turned off and only the default applications and Battery Monitor Widget is running. Same micro usb cable is used throughout the test.

No. Phone Battery (%) Phone Battery (°C) PN-920 Battery (%) State
1 21 30.3 90 Charging
66 32.8 83 Unplugged
2 20 31.6 83 Charging
66 33.0 76 Unplugged
3 21 32.4 76 Charging
67 35 70 Unplugged
4 20 29.8 70 Charging
66 32.3 60 Unplugged
5 21 30.4 60 Charging
65 33 50 Unplugged
6 21 30.8 50 Charging
67 33.3 36 Unplugged
7 22 31 36 Charging
67 34.5 26 Unplugged
8 22 31.5 26 Charging
67 34.5 19 Unplugged
9 20 30.4 19 Charging
66 33.8 11 Unplugged

Based on the table above, it seems that the battery percentage on the PN-920 drop a lot when it is below 70%. In 1 hour time frame, the battery percentage increased between 44-46% for the Samsung Galaxy Note 5 with 5V 1A port. It will need more than 2 hours to fully charge the phone from 0% to 100%, which is very slow. So it is advisable to plugged to the 5V 2.1A port on the PN-920 to charge faster. But do take note that charging faster would lead to your PN-920 battery deplete faster and some of the very old phones can only accept up to 5V 1A.