Author Archives: jen

Generate SQL Server Reporting Services (SSRS) Report as PDF from URL with VB.NET or C#.NET

Generating an existing SQL Server Reporting Services (SSRS) report to a PDF via a web URL is a convenient way to distribute SSRS reports, invoices, or anything else from SSRS. This post focuses on an existing report; however, links to the basic set up for a report are included. The code to output an existing report as PDF are given and uses a ReportViewer control.

You can skip to the PDF Output section if your server is all set up with the ReportViewer controls.

The pieces and parts to output an SSRS report as a PDF were culled from several disparate sources. All sources are given appropriate credit for their work.

As an added bonus, VB.NET and C#.NET versions are shown.

Add Report Viewer Redistributable to Server

The ReportViewer controls need to be installed on the server and Microsoft provides the redistributable for that in their download center.

The Microsoft Report Viewer 2008 Redistributable Package includes Windows Forms and ASP.NET Web server controls for viewing reports designed using Microsoft reporting technology.

Add HTTP Handler Web Server

The server has to know what it is dealing with when it is asked to generate a ReportViewer control. To help the server out, add the appropriate handlers.

Brite Global provides some excellent instructions on how to add the handlers.

Create Report on SSRS Server

The “Who Needs SQL Server’s Reporting Services?” article by DataSprings is an excellent tutorial for getting started with your first report.

Add Generic User to Report Server

For security reasons, a generic user will need to be added to the SSRS server. These credentials will be used by the .aspx page to access the report.

Give this user “Browser – May view folders, reports and subscribe to reports” only rights.

This generic (aka anonymous) user’s credentials will be stored in a separate config file and pulled into the web.config. That way if they change, you are not mucking about in the web.config file.

Create a appSetting.config and add the following information:

<appSettings>
    <add key="SSRS" value="http://YOUR-REPORTSERVER-URL" />
    <add key="rvUser" value="GENERIC-USERNAME" />
    <add key="rvPassword" value="GENERIC-PASSWORD" />
    <add key="rvDomain" value="YOUR-REPORTSERVER-DOMAIN" />
  </appSettings>

Pop it into the web.config as such:

<appSettings file="appSettings.config">
<!-- Could have other keys here -->
</appSettings>

The authorization is handled by using the IReportServerCredentials Interface which “allows applications to provide credentials for connecting to a Reporting Services report server.”

PDF Output

Add the ReportViewer control the an .aspx page by adding an assembly reference and the control itself:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="YOUR-FILE_NAME.vb" Inherits="YOUR-INHERITS" %>

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <rsweb:ReportViewer ID="ReportViewer1" runat="server">
        </rsweb:ReportViewer>

    </div>
    </form>
</body>
</html>

The code behind page got a lot of help from Viral at Beyond Relational’s post “Generating and exporting SSRS reports programatically using Report Viewer Control” and using Microsoft’s IReportServerCredentials Interface that was mentioned earlier:

VB.NET

Imports System.Net
Imports System.IO
Imports System.Security.Principal
Imports Microsoft.Reporting.WebForms

Partial Class YOUR_PAGE_CLASS
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetReportParameters()
    End Sub

    Private Sub SetReportParameters()
        'Set Processing Mode
        ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote
        ' Set report server and report path
        ReportViewer1.ServerReport.ReportServerUrl = _
           New Uri(SSRS)

        ReportViewer1.ServerReport.ReportPath = _
           "/YOUR-REPORT-PATH"

        Dim paramList As New Generic.List(Of ReportParameter)
        Dim pInfo As ReportParameterInfoCollection
        pInfo = ReportViewer1.ServerReport.GetParameters()

        'if you have report parameters - add them here
        paramList.Add(New ReportParameter("PARAM1-EXAMPLE", "1", True))
        paramList.Add(New ReportParameter("PARAM2-EXAMPLE", "2", True))

        ReportViewer1.ServerReport.SetParameters(paramList)

        ' Process and render the report
        ReportViewer1.ServerReport.Refresh()

        'output as PDF
        Dim returnValue As Byte()
        Dim format As String = "PDF"
        Dim deviceinfo As String = ""
        Dim mimeType As String = ""
        Dim encoding As String = ""
        Dim extension As String = "pdf"
        Dim streams As String() = Nothing
        Dim warnings As Microsoft.Reporting.WebForms.Warning() = Nothing

        returnValue = ReportViewer1.ServerReport.Render(format, deviceinfo, mimeType, encoding, extension, streams, warnings)
        Response.Buffer = True
        Response.Clear()

        Response.ContentType = mimeType

        Response.AddHeader("content-disposition", "attachment; filename=YOUR-OUTPUT-FILE-NAME.pdf")

        Response.BinaryWrite(returnValue)
        Response.Flush()
        Response.End()
    End Sub

    Protected Sub Page_Init(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Init

        ReportViewer1.ServerReport.ReportServerCredentials = _
            New MyReportServerCredentials()

    End Sub
End Class

<Serializable()> _
Public NotInheritable Class MyReportServerCredentials
    Implements IReportServerCredentials
    Public userName As String = ConfigurationManager.AppSettings("rvUser")
    Public password As String = ConfigurationManager.AppSettings("rvPassword")
    Public domain As String = ConfigurationManager.AppSettings("rvDomain")

    Public ReadOnly Property ImpersonationUser() As WindowsIdentity _
            Implements IReportServerCredentials.ImpersonationUser
        Get
            'Use the default windows user.  Credentials will be
            'provided by the NetworkCredentials property.
            Return Nothing
        End Get
    End Property

    Public ReadOnly Property NetworkCredentials() As ICredentials _
            Implements IReportServerCredentials.NetworkCredentials
        Get
            'Read the user information from the web.config file.
            'By reading the information on demand instead of storing
            'it, the credentials will not be stored in session,
            'reducing the vulnerable surface area to the web.config
            'file, which can be secured with an ACL.

            If (String.IsNullOrEmpty(userName)) Then
                Throw New Exception("Missing user name from web.config file")
            End If

            If (String.IsNullOrEmpty(password)) Then
                Throw New Exception("Missing password from web.config file")
            End If

            If (String.IsNullOrEmpty(domain)) Then
                Throw New Exception("Missing domain from web.config file")
            End If

            Return New NetworkCredential(userName, password, domain)

        End Get
    End Property

    Public Function GetFormsCredentials(ByRef authCookie As Cookie, _
                                        ByRef userName As String, _
                                        ByRef password As String, _
                                        ByRef authority As String) _
                                        As Boolean _
            Implements IReportServerCredentials.GetFormsCredentials

        authCookie = Nothing
        userName = Nothing
        password = Nothing
        authority = Nothing

        'Not using form credentials
        Return False

    End Function

End Class

C#

using System;
using System.Configuration;
using System.Net;
using System.Security.Principal;
using Microsoft.Reporting.WebForms;
partial class YOUR_PAGE_CLASS : System.Web.UI.Page
{
    public string SSRS = ConfigurationManager.AppSettings["SSRS"];
    protected void Page_Load(object sender, System.EventArgs e)
    {
        SetReportParameters();
    }
    private void SetReportParameters()
    {
        //Set Processing Mode
        //ReportViewer1.ProcessingMode = ProcessingMode.Remote
        ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
        // Set report server and report path
        ReportViewer1.ServerReport.ReportServerUrl = new Uri(SSRS);

        ReportViewer1.ServerReport.ReportPath = "/YOUR-REPORT-PATH";

        System.Collections.Generic.List<ReportParameter> paramList = new System.Collections.Generic.List<ReportParameter>();
        ReportParameterInfoCollection pInfo = default(ReportParameterInfoCollection);
        pInfo = ReportViewer1.ServerReport.GetParameters();

        //if you have report parameters - add them here
        paramList.Add(new ReportParameter("PARAM1-EXAMPLE", "1", true));
        paramList.Add(new ReportParameter("PARAM1-EXAMPLE", "2", true));

        ReportViewer1.ServerReport.SetParameters(paramList);

        // Process and render the report
        ReportViewer1.ServerReport.Refresh();

        //output as PDF
        byte[] returnValue = null;
        string format = "PDF";
        string deviceinfo = "";
        string mimeType = "";
        string encoding = "";
        string extension = "pdf";
        string[] streams = null;
        Microsoft.Reporting.WebForms.Warning[] warnings = null;

        returnValue = ReportViewer1.ServerReport.Render(format, deviceinfo, out mimeType, out encoding, out extension, out streams, out warnings);
        Response.Buffer = true;
        Response.Clear();

        Response.ContentType = mimeType;

        Response.AddHeader("content-disposition", "attachment; filename=YOUR-OUTPUT-FILE-NAME.pdf");

        Response.BinaryWrite(returnValue);
        Response.Flush();
        Response.End();
    }

    protected void Page_Init(object sender, System.EventArgs e)
    {
        ReportViewer1.ServerReport.ReportServerCredentials = new MyReportServerCredentials();

    }
    public YOUR-PAGE-CLASS()
    {
        Init += Page_Init;
        Load += Page_Load;
    }
}
[Serializable()]
public sealed class MyReportServerCredentials : IReportServerCredentials
{
    public string userName = ConfigurationManager.AppSettings["rvUser"];
    public string password = ConfigurationManager.AppSettings["rvPassword"];

    public string domain = ConfigurationManager.AppSettings["rvDomain"];
    public WindowsIdentity ImpersonationUser
    {

        //Use the default windows user.  Credentials will be
        //provided by the NetworkCredentials property.

        get { return null; }
    }

    public ICredentials NetworkCredentials
    {

        get
        {
            //Read the user information from the web.config file.
            //By reading the information on demand instead of storing
            //it, the credentials will not be stored in session,
            //reducing the vulnerable surface area to the web.config
            //file, which can be secured with an ACL.

            if ((string.IsNullOrEmpty(userName)))
            {
                throw new Exception("Missing user name from web.config file");
            }

            if ((string.IsNullOrEmpty(password)))
            {
                throw new Exception("Missing password from web.config file");
            }

            if ((string.IsNullOrEmpty(domain)))
            {
                throw new Exception("Missing domain from web.config file");
            }

            return new NetworkCredential(userName, password, domain);

        }
    }

    public bool GetFormsCredentials(out Cookie authCookie,
               out string userName, out string password,
               out string authority)
    {
        authCookie = null;
        userName = null;
        password = null;
        authority = null;

        // Not using form credentials
        return false;
    }

}

Now just run your URL in a browser (http://YOUR-DOMAIN.com/YOUR-PAGE.aspx) and the File Download warning box will pop up for the PDF.

PDF Layout Tips and Things to Look Out For

  1. Set Report PageSize to 8.5in, 11in for portrait or 11in, 8.5in for landscape.
  2. Set the Report Margins as you would like.
  3. Make sure your Report Body (white staging area in Visual Studio) does not exceed your Report PageSize minus your margins.
  4. Remove any unused white space in Report Body no matter what you set the sizes at.

Google API Offline Access Using OAuth 2.0 Refresh Token

Offline access for Google APIs is achieved through a refresh token that is issued when a user first visits the app and grants offline access. Essentially, you have to ask for offline access, Google warns them that you are asking for it, and then they have to grant it. The return contains the golden ticket refresh token.

The first time a given user’s browser is sent to this URL, they see a consent page. If they grant access, then the response includes an authorization code which may be redeemed for an access token and a refresh token.

Once a refresh token is obtained, it can be used to access Google APIs that the user has access to without re-authorizing.

See Google’s documentation on OAuth 2 for web apps for more information.

Asking for Offline Access

Parameters for Login URL

Client id and client secret are set by Google when the app is registered for api access in the Google APIs Console.

The redirect uri is a location on the server that the user is sent to after authenticating. This uri is registered in the Google APIs Console during app registration.

These values can be included as a separate file so the values can easily be swapped out on a per app basis.

$client_id = "1111111111111.apps.googleusercontent.com"; //your client id
$client_secret = "xXasdfd212312_dfdf dfxxdf"; //your client secret
$redirect_uri = "http://YOUR-SITE.com/YOUR-PATH/";
$scope = "https://GOOGLE-SCOPE-TO-ACCESS"; //google scope to access
$state = "profile"; //optional - could be whatever value you want
$access_type = "offline"; //optional - allows for retrieval of refresh_token for offline access

User Login URL

The login URL will prompt the user for permission to access their Google content via the app and a “code” request variable will be returned in the URL. See Forming the URL for more detailed information.

$loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s", $scope, $state, $redirect_uri, $client_id, $access_type);

<a href="<?php echo $loginUrl ?>">Login with Google account using OAuth 2.0</a>

Returned URL example (http://YOUR-SITE.com/YOUR-PATH/ is your redirect uri):


http://YOUR-SITE.com/YOUR-PATH/?state=profile&code=1/fFBGRNJru1FQd44AzqT3Zg

Get Access Token and Refresh Token

They said “Yes!” Initial consent received for offline access and a “code” was returned as a request parameter:

//Initial grant for access approved by user returns 'code' URL param
if(isset($_REQUEST['code'])){
    $accessToken = get_oauth2_token($_REQUEST['code'],"online");
}

The get_oauth2_token does double duty. It will return an access token for either online or offline access grants.

For the initial grant, if a refresh token is returned, the function puts the refresh token into ‘global $refreshToken’

Why not store the refresh token here instead of putting it in a var? Because there is no reference for the refresh token at this point other than the scope of the grant request. You don’t know who it belongs to. The initial access token returned with the refresh token can be used to query the API and get data to associate with the refresh token for the database.

If there is a known value (like it belongs to you) to associate with the refresh token that can be used to retrieve it later on, put a call to the database save function in here.

//returns session token for calls to API using oauth 2.0
//set global refreshToken var if refresh token is returned
function get_oauth2_token($grantCode,$grantType) {
	global $client_id;
	global $client_secret;
	global $redirect_uri;

	$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
	$clienttoken_post = array(
	"client_id" => $client_id,
	"client_secret" => $client_secret);

	if ($grantType === "online"){
		$clienttoken_post["code"] = $grantCode;
		$clienttoken_post["redirect_uri"] = $redirect_uri;
		$clienttoken_post["grant_type"] = "authorization_code";
	}

	if ($grantType === "offline"){
		$clienttoken_post["refresh_token"] = $grantCode;
		$clienttoken_post["grant_type"] = "refresh_token";
	}

	$curl = curl_init($oauth2token_url);

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$json_response = curl_exec($curl);
	curl_close($curl);

	$authObj = json_decode($json_response);

	//if offline access requested and granted, get refresh token
	if (isset($authObj->refresh_token)){
		global $refreshToken;
		$refreshToken = $authObj->refresh_token;
	}

	$accessToken = $authObj->access_token;
	return $accessToken;
}

Storing the Refresh Token

The refresh token will need to be stored for retrieval in the future. This example puts it in a MySQL database.

If a refresh token has been granted, store it in a database. Otherwise, retrieve a refresh token from the database. And, use the refresh token to set an access token for API calls.

//get name on account to use as reference in database for retrieving the refresh token
//can be done with data from primary API that is being queried

$googleUserInfoAPI = "https://www.googleapis.com/oauth2/v1/userinfo";

if (isset($accessToken)){
    //got access token, get data
    $accountObj = call_api($accessToken, $googleUserInfoAPI);
    $account_name =  $accountObj->name;
}

//refresh token handling - save to db if returned with access token
//or retrieve from db if needed for app
if(isset($refreshToken)){
    $accessToken = dbRefreshToken($account_name,$demo_scope,$refreshToken);
} else {
    $accessTokenFromRefresh = dbRefreshToken('ACCT_NAME_HERE',$demo_scope);
}

‘ACCT_NAME_HERE’ is a string that is used to identify for retrieval the refresh token you want to use.

The dbRefreshToken function for saving or retrieving from database and returning an access token:

function dbRefreshToken($name,$scope,$refreshToken = ""){
    global $serverpath;
    $path = $serverpath."/config/token_config.php";
    include_once($path);
    $path = $serverpath."/config/db.php";
    include_once($path);

    if ($conn){
	if (strlen($refreshToken)){
	//if refreshToken in param list, save to db
	    $query = "INSERT INTO tokens (name, scope, token) VALUES (:name, :scope, :refreshToken)";
	    $result = $conn->prepare($query);
	    $result->bindValue(':name', $name, PDO::PARAM_STR);
	    $result->bindValue(':scope', $scope, PDO::PARAM_STR);
	    $result->bindValue(':refreshToken', $refreshToken, PDO::PARAM_STR);
	    $result->execute();
	    $token = $refreshToken;
       } else {
        //else retrieve refresh token from db
	    $query = "SELECT token from tokens where name = :name and scope = :scope";
	    $result = $conn->prepare($query);
	    $result->bindValue(':name',$name, PDO::PARAM_STR);
	    $result->bindValue(':scope', $scope, PDO::PARAM_STR);
	    $result->execute();
	    $row = $result->fetch(PDO::FETCH_ASSOC);
	    $token = $row["token"];
        }

    mysql_close($conn);

    $accessTokenfromRefresh = get_oauth2_token($token,"offline");
    return $accessTokenfromRefresh;
   }
}

Note that config.php contains your database configuration parameter (username, password, database name) and db.php contains the actual connection string. Put them in a folder and restrict web browsing to that folder.

The table is called ‘tokens’ and the columns are name, scope, and token.

Demo

Download code

Google API Requests with OAuth 2.0 Access Token

In the Authenticating with OAuth 2.0 for Google API Access with PHP post, an access token was retrieved for calls to Google APIs for data. In this post, the user’s name will be retrieved from their account.

To do that, the access token needs to be sent as a header param or query param with the call to the userinfo Google API. See Calling a Google API for more information. The header param method is shown below.

A PHP object containing the account info will be returned by a call to “call_api” function with the access token and API URL passed in:

$accountObj = call_api($_SESSION['accessToken'],"https://www.googleapis.com/oauth2/v1/userinfo");

“call_api” calls the api and gets the data:

function call_api($accessToken,$url){
	$curl = curl_init($url);

	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$curlheader[0] = "Authorization: Bearer " . $accessToken;
	curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);

	$json_response = curl_exec($curl);
	curl_close($curl);

	$responseObj = json_decode($json_response);

	return $responseObj;
}

From the account object, the name can be accessed;

$your_name =  $accountObj->name;

echo "<p class='successMessage'>The name on your Google account is: " . $your_name . "</p>";

Demo

Download code

Authenticating with OAuth 2.0 for Google API Access with PHP

Google is leading developers to OAuth 2.0 for access to its API’s:

Given the security implications of getting the implementation correct, we strongly encourage developers to use OAuth 2.0 libraries when interacting with Google’s OAuth 2.0 endpoints (see Client libraries for more information). Over time, more features will be added to these libraries.

Steps

  1. Register the app with Google
  2. Create login URL and retrieve “code”
  3. Exchange “code” for access token
  4. Send access token with API requests (details in this post)

Google details the instructions in Using OAuth 2.0 to Access Google APIs.

Steps for registering your app can be found in APIs Client Library for PHP.

Google scope values for its API’s can be found in the OAuth 2.0 Playground.

Create Login URL and Retrieve “Code”

Parameters for Login URL

Client id and client secret are set by Google when the app is registered for api access in the Google APIs Console.

The redirect uri is a location on the server that the user is sent to after authenticating. This uri is registered in the Google APIs Console during app registration.

These values can be included as a separate file so the values can easily be swapped out on a per app basis.

$client_id = "1111111111111.apps.googleusercontent.com"; //your client id
$client_secret = "XxxXXxxXXxXXxXxXXXxXXXX"; //your client secret
$redirect_uri = "http://YOUR-SITE.com/YOUR-PATH/";
$scope = "https://GOOGLE-SCOPE-TO-ACCESS"; //google scope to access
$state = "profile"; //optional
$access_type = "offline"; //optional - allows for retrieval of refresh_token for offline access

User Login URL

The login URL will prompt the user for permission to access their Google content via the app and a “code” request variable will be returned in the URL. See Forming the URL for more detailed information.

$loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s", $scope, $state, $redirect_uri, $client_id, $access_type);

<a href="<?php echo $loginUrl ?>">Login with Google account using OAuth 2.0</a>

Returned URL example (http://YOUR-SITE.com/YOUR-PATH/ is your redirect uri):


http://YOUR-SITE.com/YOUR-PATH/?state=profile&code=1/fFBGRNJru1FQd44AzqT3Zg

Exchange “Code” for Access Token

If access type was set to “offline” in the login URL, a refresh token will be sent with the access token so the data can be accessed without prompting the user again.

//Oauth 2.0: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['code'])){
	$_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
}

//returns session token for calls to API using oauth 2.0
function get_oauth2_token($code) {
	global $client_id;
	global $client_secret;
	global $redirect_uri;

	$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
	$clienttoken_post = array(
	"code" => $code,
	"client_id" => $client_id,
	"client_secret" => $client_secret,
	"redirect_uri" => $redirect_uri,
	"grant_type" => "authorization_code"
	);

	$curl = curl_init($oauth2token_url);

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$json_response = curl_exec($curl);
	curl_close($curl);

	$authObj = json_decode($json_response);

	if (isset($authObj->refresh_token)){
        //refresh token only granted on first authorization for offline access
        //save to db for future use (db saving not included in example)
		global $refreshToken;
		$refreshToken = $authObj->refresh_token;
	}

	$accessToken = $authObj->access_token;
	return $accessToken;
}

You now have an access token to present to the Google API of your choice (specified in the scope) for data.

Demo

Download code

Jquery Datepicker with Masked Input and Current Time

Examples of using a jquery ui datepicker with masked input and current time as input values. Input is editable for manual change of date and/or time.

Help in this post can from Adding time to jQuery UI Datepicker by Derek Allard and the Masked Input Plugin 1.3 by Josh Bush.

There are two functions:

  1. getTimeAmPm – formats time for standard AM/PM display
  2. getTime24 – format time for 24-hour display (sometimes called military time)
function getTimeAmPm() {

    var date_o = new Date();

    var date_mins = date_o.getMinutes() < 10 ? "0" + date_o.getMinutes() : date_o.getMinutes();

    var date_hours = date_o.getHours() > 12 ? "0" + (date_o.getHours() - 12) : date_o.getHours();

    var date_am_pm = date_o.getHours() < 12 ?  " AM" : " PM";

    // handle midnight
    date_hours = date_hours === 0 ? 12 : date_hours;

    return "'" + date_hours + ":" + date_mins + " " + date_am_pm + "'";
}

function getTime24() {

    var date_o = new Date();

    var date_hours = date_o.getHours() < 10 ? "0" + date_o.getHours() : date_o.getHours();

    var date_mins = date_o.getMinutes() < 10 ? "0" + date_o.getMinutes() : date_o.getMinutes();

    return "'" + date_hours + ":" + date_mins + "'";
}

The datepickers concatenate on the result from one of the time format functions and they both have the mask jquery plugin function by Josh applied to them:

$(".datepicker").datepicker({dateFormat: 'yy-mm-dd ' + getTimeAmPm()});

$(".datepicker").mask("9999-99-99 99:99 aa");

$(".datepicker24").datepicker({dateFormat: 'yy-mm-dd ' + getTime24()});

$(".datepicker24").mask("9999-99-99 99:99");

The HTML just has a couple of inputs for the examples:

<input class="datepicker" type="text" /> AM / PM
<br />
<input class="datepicker24" type="text" /> 24 hour

Recommended

Demo