What is Swagger for Web API?

Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.

We created Swagger to help fulfill the promise of APIs. Swagger helps companies like Apigee, Getty Images, Intuit, LivingSocial, McKesson, Microsoft, Morningstar, and PayPal build the best possible services with RESTful APIs.

Now in version 2.0, Swagger is more enabling than ever. And it’s 100% open source software.

Demo Site:



Reference: http://swagger.io/

Configure GlassFish 4.1 with JAVA 8 in Ubuntu 15.04

GlassFish is an open source application server for the development and deployment of Java Platform, Enterprise Edition (Java EE platform) applications and web technologies based on Java technology. It supports different Java based technologies like Enterprise JavaBeans, JPA, JavaServer Faces, JMS, RMI, JavaServer Pages, servlets and more. Glassfish provides a lightweight and extensible core based on OSGi Alliance standards with a web container. For ther configuration and management, it has a very good easy-to-use administration console with update tool for updates and add-on components. Glassfish has a good support for high availability clustering and load balancing.

Now, we’ll go for installing Glassfish in Ubuntu 15.04 with pretty easy steps.

1. Adding Java PPA

First of all, we’ll need to install Oracle JDK 8. As Oracle Java is not available in the repository of Ubuntu, we’ll need to add a PPA for the access of the Oracle java 8 installer. So, we’ll first install python-software-properties if not installed and add PPA into our Ubuntu 15.04 machine.

# apt-get install python-software-properties

Reading package lists… Done
Building dependency tree
Reading state information… Done
The following extra packages will be installed:
libpython-stdlib libpython2.7-minimal libpython2.7-stdlib python python-apt python-minimal
python-pycurl python2.7 python2.7-minimal
Suggested packages:
python-doc python-tk python-apt-dbg python-gtk2 python-vte python-apt-doc
libcurl4-gnutls-dev python-pycurl-dbg python-pycurl-doc python2.7-doc binutils
The following NEW packages will be installed:
libpython-stdlib libpython2.7-minimal libpython2.7-stdlib python python-apt python-minimal
python-pycurl python-software-properties python2.7 python2.7-minimal
0 upgraded, 10 newly installed, 0 to remove and 0 not upgraded.
Need to get 4,126 kB of archives.
After this operation, 17.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

Now, we’ll add the ppa for Java using add-apt-repository command as shown below.

# add-apt-repository ppa:webupd8team/java

Oracle Java (JDK) Installer (automatically downloads and installs Oracle JDK7 / JDK8 / JDK9). There are no actual Java files in this PPA.

More info (and Ubuntu installation instructions):
– for Oracle Java 7: http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html
– for Oracle Java 8: http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html

Debian installation instructions:
– Oracle Java 7: http://www.webupd8.org/2012/06/how-to-install-oracle-java-7-in-debian.html
– Oracle Java 8: http://www.webupd8.org/2014/03/how-to-install-oracle-java-8-in-debian.html

Important!!! For now, you should continue to use Java 8 because Oracle Java 9 is available as an early access release (it should be released in 2016)! You should only use Oracle Java 9 if you explicitly need it, because it may contain bugs and it might not include the latest security patches! Also, some Java options were removed in JDK9, so you may encounter issues with various Java apps. More information and installation instructions (Ubuntu / Linux Mint / Debian): http://www.webupd8.org/2015/02/install-oracle-java-9-in-ubuntu-linux.html
More info: https://launchpad.net/~webupd8team/+archive/ubuntu/java
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keyring `/tmp/tmpahw0r1nh/secring.gpg’ created
gpg: keyring `/tmp/tmpahw0r1nh/pubring.gpg’ created
gpg: requesting key EEA14886 from hkp server keyserver.ubuntu.com
gpg: /tmp/tmpahw0r1nh/trustdb.gpg: trustdb created
gpg: key EEA14886: public key “Launchpad VLC” imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)

After adding the PPA repository, we’ll want to update the local package repository index. To do so, we’ll need to run the following command.

# apt-get update

2. Installing Oracle JDK 8

After updating the repository index, we’ll want to install Oracle JDK 8 by running the following command.

# apt-get install oracle-java8-installer

Reading package lists… Done
Building dependency tree
Reading state information… Done
The following extra packages will be installed:
binutils gsfonts gsfonts-x11 java-common libfontenc1 libxfont1 x11-common xfonts-encodings
Suggested packages:
binutils-doc default-jre equivs binfmt-support visualvm ttf-baekmuk ttf-unfonts
ttf-unfonts-core ttf-kochi-gothic ttf-sazanami-gothic ttf-kochi-mincho ttf-sazanami-mincho
ttf-arphic-uming firefox firefox-2 iceweasel mozilla-firefox iceape-browser
mozilla-browser epiphany-gecko epiphany-webkit epiphany-browser galeon midbrowser
moblin-web-browser xulrunner xulrunner-1.9 konqueror chromium-browser midori google-chrome
The following NEW packages will be installed:
binutils gsfonts gsfonts-x11 java-common libfontenc1 libxfont1 oracle-java8-installer
x11-common xfonts-encodings xfonts-utils
0 upgraded, 10 newly installed, 0 to remove and 22 not upgraded.
Need to get 6,579 kB of archives.
After this operation, 20.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

3.  Setting “JAVA_HOME” Variable

Now, after installing the Oracle JDK 8, we’ll now want to set the environment variable “JAVA_HOME” as the path of the newly installed Oracle JDK 8. To set the variable, we’ll need to edit /etc/environment file using our favorite text editor.

# nano /etc/environment

After opening with the text editor, we’ll need to add the following line into the bottom of the file.


Once, the line is added, we’ll need to reload file.

# source /etc/environment

After installing and setting the Oracle JDK 8, we’ll run the following command to check and confirm.

# java -version

java version “1.8.0_45”
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

If we see the output as shown above, it is confirmed that we have Java 8 installed in our machine.

4. Installing GlassFish 4.1

After our Java is installed correctly, we’ll now march towards installing Glassfish 4.1 which is the latest version till date. We can even download the older versions from the GlassFish official download page https://glassfish.java.net/download.html .

# cd /tmp
# wget ‘http://download.java.net/glassfish/4.1/release/glassfish-4.1.zip’

–2015-05-26 05:53:22– http://download.java.net/glassfish/4.1/release/glassfish-4.1.zip
Resolving download.java.net (download.java.net)…
Connecting to download.java.net (download.java.net)||:80… connected.
HTTP request sent, awaiting response… 302 Moved Temporarily
Location: http://dlc-cdn.sun.com/glassfish/4.1/release/glassfish-4.1.zip [following]
–2015-05-26 05:53:22– http://dlc-cdn.sun.com/glassfish/4.1/release/glassfish-4.1.zip
Resolving dlc-cdn.sun.com (dlc-cdn.sun.com)…,
Connecting to dlc-cdn.sun.com (dlc-cdn.sun.com)||:80… connected.
HTTP request sent, awaiting response… 200 OK
Length: 107743725 (103M) [application/zip]
Saving to: ‘glassfish-4.1.zip’

glassfish-4.1.zip 100%[===============================>] 102.75M 78.7MB/s in 1.3s

2015-05-26 05:53:23 (78.7 MB/s) – ‘glassfish-4.1.zip’ saved [107743725/107743725]

Now, we’ll want to extract the downloaded zip package of the latest GlassFish 4.1 . To do that, we’ll need to install unzip and then extract the package into /opt directory.

# apt-get install unzip
# unzip glassfish-4.1.zip -d /opt

5. Setting GlassFish PATH

Now, we’ll want to setup PATH variable for GlassFish so that the GlassFish executable files will be accessible directly from any directory. To do that, we’ll edit ~/.profile file and add the PATH to the directory where GlassFish is extracted.

# nano ~/.profile

Then add the following lines into it.

export PATH=/opt/glassfish4/bin:$PATH

# source ~/.profile

6. Starting GlassFish server

Finally, after installing Oracle Java 8 and GlassFish 4.1 in our Ubuntu 15.04 machine. We’ll want to start the GlassFish server. To do so, we’ll run asadmin as follows.

# asadmin start-domain

Waiting for domain1 to start …………
Successfully started the domain : domain1
domain Location: /opt/glassfish4/glassfish/domains/domain1
Log File: /opt/glassfish4/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.

A domain is a set of one or more GlassFish Server instances managed by one administration server. The default GlassFish Server’s port is 8080 and administration server’s port is 4848 with the administration user name as admin with no password. We can visit http://ip-address:8080/ to check the homepage of GlassFish Server and http://ip-address:4848/ to get the admin login page in our web browser.

GlassFish Home Page

GlassFish Login

7. Enabling Secure Admin

Now, inorder to access the administration panel remotely via webpage, we’ll need to enable secure adminusing asadmin by running the following command.

# asadmin enable-secure-admin

Enter admin user name> admin
Enter admin password for user “admin”>
You must restart all running servers for the change in secure admin to take effect.
Command enable-secure-admin executed successfully.

This will ask us the username and password we want to set.

Note: If you get this error “remote failure: At least one admin user has an empty password, which secure admin does not permit. Use the change-admin-password command or the admin console to create non-empty passwords for admin accounts.” you’ll need to run as admin change-admin-password and enter a new password for the admin then retry above command.

# asadmin change-admin-password

Enter admin user name [default: admin]>admin
Enter the admin password>
Enter the new admin password>
Enter the new admin password again>
Authentication failed for user: admin (Usually, this means invalid user name and/or password)
Command change-admin-password failed.

After setting, we’ll need to restart the domain.

# asadmin restart-domain

Successfully restarted the domain
Command restart-domain executed successfully.

After enabling the secure admin, we are able to access the administration panel by pointing our web browser to http://ip-address:4848 . Then, access the admin panel by entering the credentials entered above.

GlassFish Administration Panel

8. Deploying WAR on GlassFish

Now, after we have successfully installed GlassFish and running the server, we’ll want to deploy a WAR application into the GlasFish. Here, in this tutorial we’ll deploy hello.war for the test of the server. So, first we’ll download hello.war from the official sample page of GlassFish using wget command.

# wget https://glassfish.java.net/downloads/quickstart/hello.war

–2015-05-26 06:46:19– https://glassfish.java.net/downloads/quickstart/hello.war
Resolving glassfish.java.net (glassfish.java.net)…
Connecting to glassfish.java.net (glassfish.java.net)||:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 4102 (4.0K) [text/plain]
Saving to: ‘hello.war’

hello.war 100%[===============================>] 4.01K –.-KB/s in 0s

2015-05-26 06:46:19 (36.7 MB/s) – ‘hello.war’ saved [4102/4102]

After downloading the war file, we’ll now deploy the war file using asadmin command.

# asadmin deploy hello.war

Enter admin user name> admin
Enter admin password for user “admin”>
Application deployed with name hello.
Command deploy executed successfully.

This will ask us to enter the username and password for the application deployment.

As the war application has been deployed, we can check it by visiting http://ip-address:8080/hello using our web browser.

GlassFish Hello Deploy

9. Undeploying and Stopping Server

Now, if we have done our task with the GlassFish Server and the deployed application, we can simply undeploy the application and stop the GlassFish server.

To undeploy a running application, we can simply run asadmin undeploy with the application name we want to undeploy.

# asadmin undeploy hello

Enter admin user name> admin
Enter admin password for user “admin”>
Command undeploy executed successfully.

To stop the running GlassFish domain, we can simply run asadmin stop-domain .

# asadmin stop-domain

Waiting for the domain to stop .
Command stop-domain executed successfully.

Creating a password file

If you are tired of entering the username and password everytime you deploy or undeploy an application, you can simply create a file named pwdfile with a text editor and add the following lines into it.

# nano pwdfile


Now, after that file is created, we can just add –passwordfile flag pointing the pwdfile and then deploy the war application as shown below.

# asadmin –passwordfile pwdfile deploy hello.war

Application deployed with name hello.
Command deploy executed successfully.

Now, the prompt for username and password won’t appear further.


GlassFish is an awesome open source application server that implements Java EE. We can install GlassFish with different methods like ZIP Package, Self-Extracting Bundle and Full Platform or Web Profile Distribution. Here, in this tutorial we’ve used full platform with zip package. The latest GlassFish version 4.1 includes new support for Java API for JSON Processing (JSON-P) 1.0, Java API for WebSocket 1.1, Batch Applications for the Java Platform 1.0, Concurrency Utilities for Java EE 1.0, Java Message Service (JMS) 2.0, Java API for RESTful Web Services (JAX-RS) 2.0 and many updated JAVA EE Standards. GlassFish has made the deployment of war java application very fast, secure and easy. If you have any questions, suggestions, feedback please write them in the comment box below so that we can improve or update our contents. Thank you ! Enjoy 🙂

Reference: http://linoxide.com/ubuntu-how-to/setup-glassfish-4-1-java-8-ubuntu-15-04/

SMS and email Two-Factor Authentication in ASP.NET MVC 5

Create an ASP.NET  MVC app

Start by installing and running Visual Studio Express 2013 for Web or  Visual Studio 2013 .  Install Visual Studio 2013 Update 3 or higher.

Warning: You should complete Create a secure ASP.NET MVC 5 web app with log in, email confirmation and password reset before proceeding. You must install Visual Studio 2013 Update 3 or higher to complete this tutorial.
  1. Create a new ASP.NET Web project and select the MVC template. Web Forms also supports ASP.NET Identity, so you could follow similar steps in a web forms app.
  2. Leave the default authentication as Individual User Accounts. If you’d like to host the app in Azure, leave the check box checked. Later in the tutorial we will deploy to Azure. You can open an Azure account for free .
  3. Set the project to use SSL .

Set up SMS for Two-factor authentication

This tutorial provides instructions for using either Twilio or ASPSMS but you can use any other SMS provider.

  1. Creating a User Account with an SMS provider

    Create a Twilio or an ASPSMS account.

  2. Installing additional packages or adding service references

    In the Package Manager Console, enter the following command:
    Install-Package Twilio

    The following service reference needs to be added:



  3. Figuring out SMS Provider User credentials

    From the Dashboard tab of your Twilio account, copy the Account SID and Auth token.

    From your account settings, navigate to Userkey and copy it together with your self-defined Password.

    We will later store these values in the web.config file within the keys "SMSAccountIdentification" and"SMSAccountPassword".

  4. Specifying SenderID / Originator

    From the Numbers tab, copy your Twilio phone number.

    Within the Unlock Originators Menu, unlock one or more Originators or choose an alphanumeric Originator (Not supported by all networks).

    We will later store this value in the web.config file within the key "SMSAccountFrom".

  5. Transferring SMS provider credentials into app

    Make the credentials and sender phone number available to the app. To keep things simple we will store these values in the web.config file. When we deploy to Azure, we can store the values securely in the app settingssection on the web site configure tab.

          <add key="webpages:Version" value="" />
          <!-- Markup removed for clarity. -->
          <!-- SendGrid-->
          <add key="mailAccount" value="account" />
          <add key="mailPassword" value="password" />
          <add key="SMSAccountIdentification" value="My Identification" />
          <add key="SMSAccountPassword" value="My Password" />
          <add key="SMSAccountFrom" value="+12065551234" />
    Security Note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple. See Best practices for deploying passwords and other sensitive data to ASP.NET and Azure .
  6. Implementation of data transfer to SMS provider

    Configure the SmsService class in the App_Start\IdentityConfig.cs file.

    Depending on the used SMS provider activate either the Twilio or the ASPSMS section:

    public class SmsService : IIdentityMessageService
        public Task SendAsync(IdentityMessage message)
            // Twilio Begin
            // var Twilio = new TwilioRestClient(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"]);
            // var result = Twilio.SendMessage(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            //   message.Destination, message.Body
            // );
            // Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
            // Trace.TraceInformation(result.Status);
            // Twilio doesn't currently have an async API, so return success.
            // return Task.FromResult(0);
            // Twilio End
            // ASPSMS Begin 
            // var soapSms = new MvcPWx.ASPSMSX2.ASPSMSX2SoapClient("ASPSMSX2Soap");
            // soapSms.SendSimpleTextSMS(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"],
            //   message.Destination,
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            //   message.Body);
            // soapSms.Close();
            // return Task.FromResult(0);
            // ASPSMS End
  7. Update the Views\Manage\Index.cshtml Razor view: (note: don’t just remove the comments in the exiting code, use the code below.)
    @model MvcPWy.Models.IndexViewModel
       ViewBag.Title = "Manage";
    <p class="text-success">@ViewBag.StatusMessage</p>

    Change your account settings

    [ @if (Model.HasPassword) { @Html.ActionLink("Change your password", "ChangePassword") } else { @Html.ActionLink("Create", "SetPassword") } ]
    External Logins:
    @Model.Logins.Count [ @Html.ActionLink("Manage", "ManageLogins") ]
    Phone Number:
    @(Model.PhoneNumber ?? "None") [ @if (Model.PhoneNumber != null) { @Html.ActionLink("Change", "AddPhoneNumber") @:  |  @Html.ActionLink("Remove", "RemovePhoneNumber") } else { @Html.ActionLink("Add", "AddPhoneNumber") } ]
    Two-Factor Authentication:
    @if (Model.TwoFactor) { using (Html.BeginForm("DisableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() Enabled type="submit" value="Disable" class="btn btn-link" /> } } else { using (Html.BeginForm("EnableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() Disabled type="submit" value="Enable" class="btn btn-link" /> } }
  8. Verify the EnableTwoFactorAuthentication and DisableTwoFactorAuthentication action methods in the ManageController have the [ValidateAntiForgeryToken] attribute:
    // POST: /Manage/EnableTwoFactorAuthentication
    public async Task<ActionResult> EnableTwoFactorAuthentication()
        await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
            await SignInAsync(user, isPersistent: false);
        return RedirectToAction("Index", "Manage");
    // POST: /Manage/DisableTwoFactorAuthentication
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> DisableTwoFactorAuthentication()
        await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
            await SignInAsync(user, isPersistent: false);
        return RedirectToAction("Index", "Manage");
  9. Run the app and log in with the account you previously registered.
  10. Click on your User ID, which activates the Index action method in Manage controller.
  11. Click Add.
  12. The AddPhoneNumber action method displays a dialog box to enter a phone number that can receive SMS messages.
    // GET: /Account/AddPhoneNumber
    public ActionResult AddPhoneNumber()
       return View();

  13. In a few seconds you will get a text message with the verification code. Enter it and press Submit.
  14. The Manage view shows your phone number was added.

Enable two-factor authentication

In the template generated app, you need to use the UI to enable two-factor authentication (2FA). To enable 2FA, click on your user ID (email alias) in the navigation bar.

Click on enable 2FA.

Log out, then log back in. If you’ve enabled email (see my previous tutorial), you can select the SMS or email for 2FA.

The Verify Code page is displayed where you can enter the code (from SMS or email).

Clicking on the Remember this browser check box will exempt you from needing to use 2FA to log in when using the browser and device where you checked the box. As long as malicious users can’t gain access to your device, enabling 2FA and clicking on the Remember this browser will provide you with convenient one step password access, while still retaining strong 2FA protection for all access from non-trusted devices. You can do this on any private device you regularly use.


Reference: http://www.asp.net/mvc/overview/security/aspnet-mvc-5-app-with-sms-and-email-two-factor-authentication

How to Choose A Right Passive UHF RFID Antenna?

We will discuss these factors below to help you better understand UHF RFID passive antennas.


Each country has regulations that specify the frequency ranges for UHF RFID transmissions within that country. The three most prevalent frequency ranges for UHF RFID antennas are:

  • 902-928 MHz (US/FCC)
  • 865-868 MHz (EU/ETSI)
  • 860-960 MHz (Global)

When choosing an RFID antenna, be sure to select the frequency range that is right for your region.


Gain and beamwidth are grouped together because they are both electrical components of an antenna and are distinctly related. The higher the gain, the narrower (or smaller) the beamwidth. Higher gain creates a narrower area of coverage, but the beam will travel a longer distance. Beamwidth and gain are analogous to the beam of a flashlight. Check out the diagram below to see how differences in gain can drastically affect the antenna’s beamwidth.


Beamwidth is determined by gain – the higher the gain, the more focused the beam.

The ideal beamwidth and gain will depend on your specific application. If you have many tags a short distance away, then you most likely don’t need a high gain antenna; it would be more advantageous to use a wide beamwidth antenna with relatively low gain as represented by the third image above.


Most UHF RFID passive antennas are either linearly or circularly polarized. Linearly polarized antennas send RF waves in a single plane either horizontally or vertically. Circularly polarized antennas send RF waves in a circular motion either clockwise or counterclockwise. When the waves rotate clockwise, the antenna is a left-hand circularly polarized (LHCP) antenna; when the waves rotate counterclockwise, the antenna is a right-hand circularly-polarized antenna (RHCP).

When you have a setup where antennas are facing each other, it’s important to know if you have a LHCP or RHCP antennas. When antennas face each other and emit waves in the same direction, waves will create null zones where the two sides meet. If you choose LHCP and RHCP when you have two antennas facing each other, it creates a more effective read zone then if you use two LHCP antennas.


One exception to the rule above is when using a bistatic system. If you use a bistatic system in a portal arrangement (antennas facing each other), the antenna that transmits the RF wave will need to be the SAME polarization as the antenna that receives the RF wave. So if a LHCP transmits the wave, the antenna that receives the RF wave will need to be LHCP in order to receive it most efficiently.

If all the tags in your application will be read the same orientation and at the same height, then it may be best to use a linearly polarized antenna. The main advantage to circularly polarized antennas is that they are better for applications where you cannot predict tag placement or orientation.


Reference: http://blog.atlasrfidstore.com/choose-right-rfid-antenna


Create and Populate Date Dimension for Data Warehouse

Date dimension plays an important role in your data warehouse designing, it provides the ability to study behavior and trend of your data over a period of time.

You can study your data by grouping them using various fields of date dimension.

For example:

If I want to analyze my data of total sales by each month of the year, or show total sales by each quarter of the year, or show me on which days total sales takes place more in the entire year or month.

After implementing the complete solution in data warehouse, the relationship of date dimension gives you all this facility to do slice and dice of your data.

So as an initial step, you need to design your date dimension, time dimension and populate them with range of values.

For designing of time dimension, you can refer to my other tip posted on CodeProject, “Design and Populate Time Dimension with 24 Hour plus Values”.

This date dimension will have values of date stored as per various date formats used across the world, like “dd-MM-yyyy” is used in Europe, UK, India, etc. while “MM-dd-yyyy” format is used in US.


--Specify Start Date and End date here
--Value of Start Date Must be Less than Your End Date 

DECLARE @StartDate DATETIME = '01/01/2013' --Starting value of Date Range
DECLARE @EndDate DATETIME = '01/01/2015' --End Value of Date Range

--Temporary Variables To Hold the Values During Processing of Each Date of Year
	@DayOfWeekInMonth INT,
	@DayOfWeekInYear INT,
	@DayOfQuarter INT,
	@WeekOfMonth INT,
	@CurrentYear INT,
	@CurrentMonth INT,
	@CurrentQuarter INT

/*Table Data type to store the day of week count for the month and year*/
DECLARE @DayOfWeek TABLE (DOW INT, MonthCount INT, QuarterCount INT, YearCount INT)

INSERT INTO @DayOfWeek VALUES (1, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (2, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (3, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (4, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (5, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (6, 0, 0, 0)
INSERT INTO @DayOfWeek VALUES (7, 0, 0, 0)

--Extract and assign various parts of Values from Current Date to Variable

DECLARE @CurrentDate AS DATETIME = @StartDate
SET @CurrentMonth = DATEPART(MM, @CurrentDate)
SET @CurrentYear = DATEPART(YY, @CurrentDate)
SET @CurrentQuarter = DATEPART(QQ, @CurrentDate)

--Proceed only if Start Date(Current date ) is less than End date you specified above

WHILE @CurrentDate < @EndDate
/*Begin day of week logic*/

         /*Check for Change in Month of the Current date if Month changed then 
          Change variable value*/
	IF @CurrentMonth != DATEPART(MM, @CurrentDate) 
		UPDATE @DayOfWeek
		SET MonthCount = 0
		SET @CurrentMonth = DATEPART(MM, @CurrentDate)

        /* Check for Change in Quarter of the Current date if Quarter changed then change 
         Variable value*/

	IF @CurrentQuarter != DATEPART(QQ, @CurrentDate)
		UPDATE @DayOfWeek
		SET QuarterCount = 0
		SET @CurrentQuarter = DATEPART(QQ, @CurrentDate)
        /* Check for Change in Year of the Current date if Year changed then change 
         Variable value*/

	IF @CurrentYear != DATEPART(YY, @CurrentDate)
		UPDATE @DayOfWeek
		SET YearCount = 0
		SET @CurrentYear = DATEPART(YY, @CurrentDate)
        -- Set values in table data type created above from variables 

	UPDATE @DayOfWeek
		MonthCount = MonthCount + 1,
		QuarterCount = QuarterCount + 1,
		YearCount = YearCount + 1

		@DayOfWeekInMonth = MonthCount,
		@DayOfQuarter = QuarterCount,
		@DayOfWeekInYear = YearCount
	FROM @DayOfWeek
/*End day of week logic*/

/* Populate Your Dimension Table with values*/
	INSERT INTO [dbo].[DimDate]
		CONVERT (char(8),@CurrentDate,112) as DateKey,
		@CurrentDate AS Date,
		CONVERT (char(10),@CurrentDate,103) as FullDateUK,
		CONVERT (char(10),@CurrentDate,101) as FullDateUSA,
		DATEPART(DD, @CurrentDate) AS DayOfMonth,
		--Apply Suffix values like 1st, 2nd 3rd etc..
			WHEN DATEPART(DD,@CurrentDate) IN (11,12,13) _
			WHEN RIGHT(DATEPART(DD,@CurrentDate),1) = 1 _
			WHEN RIGHT(DATEPART(DD,@CurrentDate),1) = 2 _
			WHEN RIGHT(DATEPART(DD,@CurrentDate),1) = 3 _
			ELSE CAST(DATEPART(DD,@CurrentDate) AS VARCHAR) + 'th' 
			END AS DaySuffix,
		DATENAME(DW, @CurrentDate) AS DayName,
		DATEPART(DW, @CurrentDate) AS DayOfWeekUSA,

		-- check for day of week as Per US and change it as per UK format 
		CASE DATEPART(DW, @CurrentDate)
			WHEN 1 THEN 7
			WHEN 2 THEN 1
			WHEN 3 THEN 2
			WHEN 4 THEN 3
			WHEN 5 THEN 4
			WHEN 6 THEN 5
			WHEN 7 THEN 6
			AS DayOfWeekUK,
		@DayOfWeekInMonth AS DayOfWeekInMonth,
		@DayOfWeekInYear AS DayOfWeekInYear,
		@DayOfQuarter AS DayOfQuarter,
		DATEPART(DY, @CurrentDate) AS DayOfYear,
		DATEPART(MM, @CurrentDate)) + '/1/' + CONVERT(VARCHAR, _
		DATEPART(YY, @CurrentDate))) AS WeekOfMonth,
		(DATEDIFF(DD, DATEADD(QQ, DATEDIFF(QQ, 0, @CurrentDate), 0), _
		@CurrentDate) / 7) + 1 AS WeekOfQuarter,
		DATEPART(WW, @CurrentDate) AS WeekOfYear,
		DATEPART(MM, @CurrentDate) AS Month,
		DATENAME(MM, @CurrentDate) AS MonthName,
			WHEN DATEPART(MM, @CurrentDate) IN (1, 4, 7, 10) THEN 1
			WHEN DATEPART(MM, @CurrentDate) IN (2, 5, 8, 11) THEN 2
			WHEN DATEPART(MM, @CurrentDate) IN (3, 6, 9, 12) THEN 3
			END AS MonthOfQuarter,
		DATEPART(QQ, @CurrentDate) AS Quarter,
		CASE DATEPART(QQ, @CurrentDate)
			WHEN 1 THEN 'First'
			WHEN 2 THEN 'Second'
			WHEN 3 THEN 'Third'
			WHEN 4 THEN 'Fourth'
			END AS QuarterName,
		DATEPART(YEAR, @CurrentDate) AS Year,
		'CY ' + CONVERT(VARCHAR, DATEPART(YEAR, @CurrentDate)) AS YearName,
		LEFT(DATENAME(MM, @CurrentDate), 3) + '-' + CONVERT(VARCHAR, _
		DATEPART(YY, @CurrentDate)) AS MonthYear,
		RIGHT('0' + CONVERT(VARCHAR, DATEPART(MM, @CurrentDate)),2) + _
		@CurrentDate) - 1), @CurrentDate))) AS FirstDayOfMonth,
		(DATEADD(MM, 1, @CurrentDate)))), DATEADD(MM, 1, _
		@CurrentDate)))) AS LastDayOfMonth,
		DATEADD(QQ, DATEDIFF(QQ, 0, @CurrentDate), 0) AS FirstDayOfQuarter,
		DATEADD(QQ, DATEDIFF(QQ, -1, @CurrentDate), -1) AS LastDayOfQuarter,
		@CurrentDate))) AS FirstDayOfYear,
		@CurrentDate))) AS LastDayOfYear,
		NULL AS IsHolidayUSA,
		CASE DATEPART(DW, @CurrentDate)
			WHEN 1 THEN 0
			WHEN 2 THEN 1
			WHEN 3 THEN 1
			WHEN 4 THEN 1
			WHEN 5 THEN 1
			WHEN 6 THEN 1
			WHEN 7 THEN 0
			END AS IsWeekday,
		NULL AS HolidayUSA, Null, Null

	SET @CurrentDate = DATEADD(DD, 1, @CurrentDate)

Step 3.
Update Values of Holiday as per UK Government Declaration for National Holiday.

/*Update HOLIDAY fields of UK as per Govt. Declaration of National Holiday*/
-- Good Friday  April 18 
	UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Good Friday'
	WHERE [Month] = 4 AND [DayOfMonth]  = 18

-- Easter Monday  April 21 
	UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Easter Monday'
	WHERE [Month] = 4 AND [DayOfMonth]  = 21

-- Early May Bank Holiday   May 5 
   UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Early May Bank Holiday'
	WHERE [Month] = 5 AND [DayOfMonth]  = 5

-- Spring Bank Holiday  May 26 
	UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Spring Bank Holiday'
	WHERE [Month] = 5 AND [DayOfMonth]  = 26

-- Summer Bank Holiday  August 25 
    UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Summer Bank Holiday'
	WHERE [Month] = 8 AND [DayOfMonth]  = 25

-- Boxing Day  December 26  	
    UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Boxing Day'
	WHERE [Month] = 12 AND [DayOfMonth]  = 26	

	UPDATE [dbo].[DimDate]
		SET HolidayUK = 'Christmas Day'
	WHERE [Month] = 12 AND [DayOfMonth]  = 25

--New Years Day
	UPDATE [dbo].[DimDate]
		SET HolidayUK  = 'New Year''s Day'
	WHERE [Month] = 1 AND [DayOfMonth] = 1

--Update flag for UK Holidays 1= Holiday, 0=No Holiday
	UPDATE [dbo].[DimDate]
		SET IsHolidayUK  = CASE WHEN HolidayUK   IS NULL _
Step 4.
Update Values of Holiday as per USA Govt. Declaration for National Holiday.

/*Update HOLIDAY Field of USA In dimension*/
 	/*THANKSGIVING - Fourth THURSDAY in November*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Thanksgiving Day'
		[Month] = 11 
		AND [DayOfWeekUSA] = 'Thursday' 
		AND DayOfWeekInMonth = 4

	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Christmas Day'
	WHERE [Month] = 12 AND [DayOfMonth]  = 25

	/*4th of July*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Independance Day'
	WHERE [Month] = 7 AND [DayOfMonth] = 4

	/*New Years Day*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'New Year''s Day'
	WHERE [Month] = 1 AND [DayOfMonth] = 1

	/*Memorial Day - Last Monday in May*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Memorial Day'
	FROM [dbo].[DimDate]
	WHERE DateKey IN 
		FROM [dbo].[DimDate]
			[MonthName] = 'May'
			AND [DayOfWeekUSA]  = 'Monday'

	/*Labor Day - First Monday in September*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Labor Day'
	FROM [dbo].[DimDate]
	WHERE DateKey IN 
		FROM [dbo].[DimDate]
			[MonthName] = 'September'
			AND [DayOfWeekUSA] = 'Monday'

	/*Valentine's Day*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Valentine''s Day'
		[Month] = 2 
		AND [DayOfMonth] = 14

	/*Saint Patrick's Day*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Saint Patrick''s Day'
		[Month] = 3
		AND [DayOfMonth] = 17

	/*Martin Luthor King Day - Third Monday in January starting in 1983*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Martin Luthor King Jr Day'
		[Month] = 1
		AND [DayOfWeekUSA]  = 'Monday'
		AND [Year] >= 1983
		AND DayOfWeekInMonth = 3

	/*President's Day - Third Monday in February*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'President''s Day'
		[Month] = 2
		AND [DayOfWeekUSA] = 'Monday'
		AND DayOfWeekInMonth = 3

	/*Mother's Day - Second Sunday of May*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Mother''s Day'
		[Month] = 5
		AND [DayOfWeekUSA] = 'Sunday'
		AND DayOfWeekInMonth = 2

	/*Father's Day - Third Sunday of June*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Father''s Day'
		[Month] = 6
		AND [DayOfWeekUSA] = 'Sunday'
		AND DayOfWeekInMonth = 3

	/*Halloween 10/31*/
	UPDATE [dbo].[DimDate]
		SET HolidayUSA = 'Halloween'
		[Month] = 10
		AND [DayOfMonth] = 31

	/*Election Day - The first Tuesday after the first Monday in November*/
	DateID int, Week TINYINT, YEAR CHAR(4), DAY CHAR(2))

		INSERT INTO @Holidays(DateID, [Year],[Day])
		FROM [dbo].[DimDate]
			[Month] = 11
			AND [DayOfWeekUSA] = 'Monday'


			, @STARTYEAR = MIN([Year])
			, @ENDYEAR = MAX([Year])
		FROM @Holidays

			FROM @Holidays

			SET @POS = 1

				FROM @Holidays
					[Year] = @CURRENTYEAR
					AND [Week] IS NULL

				UPDATE @Holidays
					SET [Week] = @POS
					[Year] = @CURRENTYEAR
					AND [Day] = @MINDAY

				SELECT @POS = @POS + 1


		UPDATE [dbo].[DimDate]
			SET HolidayUSA  = 'Election Day'				
		FROM [dbo].[DimDate] DT
			JOIN @Holidays HL ON (HL.DateID + 1) = DT.DateKey
			[Week] = 1
	--set flag for USA holidays in Dimension
	UPDATE [dbo].[DimDate]

Reference: http://www.codeproject.com/Articles/647950/Create-and-Populate-Date-Dimension-for-Data-Wareho

Create & Populate Time Dimension with 24 Hour+ Values

A common task most of us face while setting up a new data warehouse is creating a time dimension.

This tip will especially help those people who work in Business Intelligence and whenever as a starting point they need to set new data warehouse, during this time they need to create and fill their time dimension with the necessary values.

I have searched the internet to find T-SQL script which can create and fill time dimension with 24 hour plus values. I did not find any readymade script, then I invested my time to create this script and am now sharing with all so that it can help everyone.

The given time dimension script will create table of time dimension and populate it with appropriate values. It also creates time buckets in table and fills it with group values, so that the user can perform aggregation of data using various combinations of hourly time buckets or day time buckets and they can do analysis of data using these time buckets and can do study of trend over the entire day.

CREATE TABLE [dbo].[DimTime](
[TimeKey] [int] NOT NULL,
[TimeAltKey] [int] NOT NULL,
[Time30] [varchar](8) NOT NULL,
[Hour30] [tinyint] NOT NULL,
[MinuteNumber] [tinyint] NOT NULL,
[SecondNumber] [tinyint] NOT NULL,
[TimeInSecond] [int] NOT NULL,
[HourlyBucket] varchar(15)not null,
[DayTimeBucketGroupKey] int not null,
[DayTimeBucket] varchar(100) not null
[TimeKey] ASC
/***** Create Stored procedure In Test_DW and Run SP To Fill Time Dimension with Values****/
CREATE PROCEDURE [dbo].[FillDimTime]
–Specify Total Number of Hours You need to fill in Time Dimension
–iF @Size=32 THEN This will Fill values Upto 32:59 hr in Time Dimension
Set @Size=23
DECLARE @Time30 varchar(25)
DECLARE @Hour30 varchar(4)
DECLARE @Minute30 varchar(4)
DECLARE @Second30 varchar(4)
DECLARE @HourBucket varchar(15)
DECLARE @HourBucketGroupKey int
DECLARE @DayTimeBucket varchar(100)
DECLARE @DayTimeBucketGroupKey int
SET @hour = 0
SET @minute = 0
SET @second = 0
SET @k = 0
SET @TimeAltKey = 0
WHILE(@hour<= @Size )
if (@hour <10 )
set @Hour30 = ‘0’ + cast( @hour as varchar(10))
set @Hour30 = @hour
–Create Hour Bucket Value
set @HourBucket= @Hour30+’:00′ +’-‘ +@Hour30+’:59′
WHILE(@minute <= 59)
WHILE(@second <= 59)
set @TimeAltKey = @hour *10000 +@minute*100 +@second
set @TimeInSeconds =@hour * 3600 + @minute *60 +@second
If @minute <10
set @Minute30 = ‘0’ + cast ( @minute as varchar(10) )
set @Minute30 = @minute
if @second <10
set @Second30 = ‘0’ + cast ( @second as varchar(10) )
set @Second30 = @second
–Concatenate values for Time30
set @Time30 = @Hour30 +’:’+@Minute30 +’:’+@Second30
–DayTimeBucketGroupKey can be used in Sorting of DayTime Bucket In proper Order
SELECT @DayTimeBucketGroupKey =
WHEN (@TimeAltKey >= 00000 AND @TimeAltKey <= 25959) THEN 0
WHEN (@TimeAltKey >= 30000 AND @TimeAltKey <= 65959) THEN 1
WHEN (@TimeAltKey >= 70000 AND @TimeAltKey <= 85959) THEN 2
WHEN (@TimeAltKey >= 90000 AND @TimeAltKey <= 115959) THEN 3
WHEN (@TimeAltKey >= 120000 AND @TimeAltKey <= 135959)THEN 4
WHEN (@TimeAltKey >= 140000 AND @TimeAltKey <= 155959)THEN 5
WHEN (@TimeAltKey >= 50000 AND @TimeAltKey <= 175959) THEN 6
WHEN (@TimeAltKey >= 180000 AND @TimeAltKey <= 235959)THEN 7
WHEN (@TimeAltKey >= 240000) THEN 8
–print @DayTimeBucketGroupKey
— DayTimeBucket Time Divided in Specific Time Zone
— So Data can Be Grouped as per Bucket for Analyzing as per time of day
SELECT @DayTimeBucket =
WHEN (@TimeAltKey >= 00000 AND @TimeAltKey <= 25959) THEN ‘Late Night (00:00 AM To 02:59 AM)’
WHEN (@TimeAltKey >= 30000 AND @TimeAltKey <= 65959) THEN ‘Early Morning(03:00 AM To 6:59 AM)’
WHEN (@TimeAltKey >= 70000 AND @TimeAltKey <= 85959) THEN ‘AM Peak (7:00 AM To 8:59 AM)’
WHEN (@TimeAltKey >= 90000 AND @TimeAltKey <= 115959) THEN ‘Mid Morning (9:00 AM To 11:59 AM)’
WHEN (@TimeAltKey >= 120000 AND @TimeAltKey <= 135959) THEN ‘Lunch (12:00 PM To 13:59 PM)’
WHEN (@TimeAltKey >= 140000 AND @TimeAltKey <= 155959) THEN ‘Mid Afternoon (14:00 PM To 15:59 PM)’
WHEN (@TimeAltKey >= 50000 AND @TimeAltKey <= 175959) THEN ‘PM Peak (16:00 PM To 17:59 PM)’
WHEN (@TimeAltKey >= 180000 AND @TimeAltKey <= 235959) THEN ‘Evening (18:00 PM To 23:59 PM)’
WHEN (@TimeAltKey >= 240000) THEN ‘Previous Day Late Night (24:00 PM to ‘+cast( @Size as varchar(10)) +’:00 PM )’
— print @DayTimeBucket
INSERT into DimTime (TimeKey,TimeAltKey,[Time30] ,[Hour30] ,[MinuteNumber],[SecondNumber],[TimeInSecond],[HourlyBucket],DayTimeBucketGroupKey,DayTimeBucket)
VALUES (@k,@TimeAltKey ,@Time30 ,@hour ,@minute,@Second , @TimeInSeconds,@HourBucket,@DayTimeBucketGroupKey,@DayTimeBucket )
SET @second = @second + 1
SET @k = @k + 1
SET @minute = @minute + 1
SET @second = 0
SET @hour = @hour + 1
SET @minute =0
Exec [FillDimTime]
select * from DimTime

Reference: http://www.codeproject.com/Tips/642912/Create-Populate-Time-Dimension-with-24-Hourplus-Va

Learn X++ to become Microsoft Dynamic AX developer

Do you want to be Microsoft Dynamics AX Developer? I assume you are. Learn how to develop on Microsoft Dynamics AX is not as easy as it seems, it is not as easy as learning to developer using other platforms like Microsoft SharePoint. The material provided from Microsoft is not that one will give you the full picture about the platform, it will give you only the guidelines and you have to go and search and search and search and search. It took me 2 full years to know what I knew now, it is not much but I can do many things not included in the documentations.

So I decided to write this article to make it short on new developers whom want to learn about developing with Microsoft Dynamics AX and even help whom already Microsoft Dynamics AX developers.

The Platform:

Programming Language:

Microsoft Dynamics AX is built with its programming language called X++, it is like C++, C#, or Java, it is Object Oriented, if you know one of these languages you will be familiar with X++.

IDE (Integrated Development Environment) :

Microsoft Dynamics AX has its own IDE called MorphX, you will use it during all your development tasks, it is very easy and support drag and drop to make developer life easier but from my opinion the only cons is it is not supporting multi-monitor, you need to work in one window in one monitor, it is not like Visual Studio you can drag the Toolbox bar and drop it to other monitor.

The Journey:

I started by reading the Microsoft Student Training Document you need to have access to Microsoft Partner Source or Customer Source, then start to develop and found out these documents is not enough and I need to learn something more, I started to Googling or Binging and land on small parts that are helping but you need to add yours to make it full solution, for example I need to create a Sales Order and Sales Line from the code, I found sample code to create one using job (Job in AX is small runnable code) not how to use it inside a form whether to implement it in Class, Form, or Table, and if you will implement it in Form in which level DataSource or Design, I was confused and none on web can help me in setting things together till I found this great free book called MorhpX IT it was written for AX 4.0 but it still have useful information works with AX 2012 R2 I encourage you to read it after reading Student Training Documents, I really got the full picture of the platform and now I feel like I’m understand what I’m doing.



Inside Microsoft Dynamics AX 2012


Microsoft Dynamics AX 2012 Development Cookbook

4644EN_Microsoft Dynamics AX 2012 Development Cookbook_Low

Microsoft Dynamics AX 2012 Services


Microsoft Dynamics AX 2012 Security How-To


Inside Microsoft Dynamics® AX 2009

lrg (1)

Microsoft Dynamics AX 2009 Programming: Getting Started


Microsoft Dynamics AX 2009 Development Cookbook


MorphX IT