Find In Database Objects

It searches the text of triggers, UDFs, stored procedures and views for a particular substring, 
returning the name and type of those database objects that match. 
DECLARE @Search varchar(255)
SET @Search='[]'

SELECT DISTINCT AS Object_Name,o.type_desc
FROM sys.sql_modules        m
INNER JOIN sys.objects  o ON m.object_id=o.object_id
WHERE m.definition Like ‘%’+@Search+’%’


Font Awesome – Get Started


Pick your Icon:



Add Font Awesome + Bootstrap into your website with two lines of code. You don’t even have to download or install anything!

  1. Paste the following code into the <head> section of your site’s HTML.
    <link href="//" rel="stylesheet">
    <link href="//" rel="stylesheet">

    Want to use Font Awesome by itself without Bootstrap? Just don’t include the first line.

  2. Pat yourself on the back for your scalable-vector-icons-on-the-website judo solution in two lines of code.
  3. Check out the examples to start using Font Awesome!

EASY: Default CSS

Use this method to get the default Font Awesome CSS with the default Bootstrap CSS.

  1. Copy the font-awesome directory into your project.
  2. In the <head> of your html, reference the location to your font-awesome.min.css.
    <link rel="stylesheet" href="path/to/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
  3. Check out the examples to start using Font Awesome!

PRO: Custom LESS

Use this method to customize Font Awesome and Bootstrap 2.3.2 using LESS.

  1. Copy the font-awesome directory into your project.
  2. Open your project’s bootstrap/bootstrap.less and replace
    @import "sprites.less";


    @import "path/to/font-awesome/less/font-awesome.less";
  3. Open your project’s font-awesome/variables.less and edit the @FontAwesomePath variable to point to your font directory.
    @FontAwesomePath:   "../font";

    The font path is relative from your compiled CSS directory.

  4. Re-compile your LESS if using a static compiler. Otherwise, you should be good to go.
  5. Check out the examples to start using Font Awesome!

Start using it

After you get up and running, you can place Font Awesome icons just about anywhere with the <i> tag:

<i class="icon-flag"></i> icon-flag

You can also do

  • Inline Icons

  • Larger Icons

  • Bordered & Pulled Icons

  • Buttons image

  • Button Groups image

  • Button Dropdowns image

  • Bulleted Lists image

  • Navigation image

  • Prepended & Appended Form Inputs image

  • Animated Spinner image

  • Rotated & Flipped image

  • Stacked Icons image

Self-Host ASP.NET WebAPI 2 using OWIN


1. Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

2. Create a new class Startup.cs to configure the WebAPI

public class Startup
    public void Configuration(IAppBuilder appBuilder)
        // Configure Web API for self-host.
        HttpConfiguration config = new HttpConfiguration();
            name: “DefaultApi”,
            routeTemplate: “api/{controller}/{id}”,
            defaults: new { id = RouteParameter.Optional }



3. Add a Controller derived from ApiController valuescontroller.cs

public class ValuesController : ApiController
    // GET api/values
    public IEnumerable<string> Get()
        return new string[] { “value1”, “value2” };

    // GET api/values/5
    public string Get(int id)
        return “value”;

    // POST api/values
    public void Post([FromBody]string value)
    {     }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {     }

    // DELETE api/values/5
    public void Delete(int id)
    {     }


4. Start the Owin Host (Console App or a Windows Service)

static void Main()
    string baseAddress = “
    Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress);
    Console.ReadLine(); // Prevent Exit

5. Calling the WebAPI


GET http://localhost:9000/api/values HTTP/1.1
Host: localhost:9000
Accept: application/json


HTTP/1.1 200 OK
Content-Length: 19
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0



Calling WebAPI using HttpClient


What is HttpClient?

  • A WebAPI REST friendly client.
  • An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
  • You can issue as many requests as you like through a single HttpClient instance.
  • HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance. i.e. no CORS restriction.
  • You can derive from HttpClient to create specialized clients for particular sites or patterns
  • HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.


Install-Package Microsoft.AspNet.WebApi.Client

using (var client = new HttpClient())
    client.BaseAddress = new Uri(“
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json“));

    HttpResponseMessage response = await client.GetAsync(“api/products/1”);
    if (response.IsSuccessStatusCode)
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine(“{0}\t${1}\t{2}”, product.Name, product.Price, product.Category);

If the status code in the response is a success code, the response body contains the JSON representation of a product. Call ReadAsAsync to deserialize the JSON payload to a Product instance. The ReadAsync method is asynchronous because the response body can be arbitrarily large.

A note about error handling: HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code.

If you prefer to treat HTTP error codes as exceptions, call the EnsureSuccessStatusCode method. This method throws an exception if the response status is not a success code:

    HttpResponseMessage response = await client.GetAsync(“api/products/1”);
    resp.EnsureSuccessStatusCode();    // Throw if not a success code.
    // …
catch (HttpRequestException e)

Uri gizmoUrl;
var gizmo = new Product() { Name = “Gizmo”, Price = 100, Category = “Widget” };
response = await client.PostAsJsonAsync(“api/products”, gizmo);
if (response.IsSuccessStatusCode)
    // Get the URI of the created resource.
    gizmoUrl = response.Headers.Location;

gizmo.Price = 80;   // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

response = await client.DeleteAsync(gizmoUrl);


Enabling CORS (Cross-Origin Requests) in your ASP.NET Web API 2 service


What is “Same Origin”?

Two URLs have the same origin if they have identical schemes, domain, subdomain, and ports. (RFC 6454)

Enable CORS in your Web API Service

1. Install-Package Microsoft.AspNet.WebApi.Cors

2. In WebApiConfig.cs ‘s WebApiConfig.Register method, add:


3. Add the [EnableCors] attribute to the Controller/Action:

[EnableCors(origins: “”, headers: “*”, methods: “*”)]
* Do not include a forward slash at the end of the origins URL.

How CORS Works

The CORS specification introduces several new HTTP headers that enable cross-origin requests. If a browser supports CORS, it sets the Origin header automatically for cross-origin request; you don’t need to do anything special in your JavaScript code. And the browser will inspect Access-Control-Allow-Origin header in the response to determine whether to return the response content to the caller or not.

Here is an example of a cross-origin request. The “Origin” header gives the domain of the site that is making the request.


Accept: */*
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)


If the server allows the request, it sets the Access-Control-Allow-Origin header. The value of this header either matches the Origin header, or is the wildcard value “*”, meaning that any origin is allowed.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-8
Date: Wed, 05 Jun 2013 06:27:30 GMT
Content-Length: 17

GET: Test message


Secure ASP.NET WebAPI 2 using ASP.NET Identity membership DB with OAuth 2

Code Download.

What we will use:
  • OAuth 2.0 middleware
  • ASP.NET WebAPI 2.2
  • ASP.NET Identity 2.1 membership
  • Authentication Project Template: Individual Account
  • SPA using knockoutjs (optional)

OAuth 2.0 terminology:

  • Resource: Some piece of data that can be protected. e.g. Controller/Controller’s Action method.
  • Resource server: The server that hosts the resource.
  • Resource owner: The entity that can grant permission to access a resource. Typically the user.
  • Access token: A token that grants access to a resource.
  • Bearer token: A special type of access token which a client doesn’t need a cryptographic key to use it. For that reason, it should only be used over a HTTPS, and with short expiration time.
  • Authorization server: A server that gives out Bearer/Access tokens.
  • Client: The app that wants access to the resource. e.g. a web browser, native app.
  • OAuth 2.0 Access Token Retrieval – Grant types:
  • Authorization Code Grant
  • Implicit Grant
  • Resource Owner Password Credentials Grant – we will be using this!
  • Client Credentials Grant
  • JWT Tokens

note: A Resource server and Authorization server can be part of the same ASP.NET application.

Using Resource Owner Password Credentials Grant:




Let’s get the Bearer/Access token from Authorization Server


In StartupAuth.cs,

PublicClientId = “self”;
OAuthOptions = new OAuthAuthorizationServerOptions
    TokenEndpointPath = new PathString(“/Token”),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString(“/api/Account/ExternalLogin”),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // Note: Remove the following line before you deploy to production:
    AllowInsecureHttp = true

// Enable the application to use bearer tokens to authenticate users

The TokenEndpointPath property is the URL path to the authorization server endpoint. That’s the URL that app uses to get the bearer tokens. e.g. “/Token”

The Provider property specifies ApplicationOAuthProvider which provide access to the ASP.NET Identity membership database via the UserManager



  1. To get an access token, the app sends a request to ~/Token.
  2. The OAuth middleware calls GrantResourceOwnerCredentials on the ApplicationOAuthProvider (which implements OAuthAuthorizationServerProvider).
  3. The provider calls the ApplicationUserManager which derives from ASP.NET Identity’s UserManager to validate the credentials with the ASP.NET Identity membership db and create a claims identity.
  4. If that succeeds, the provider creates an authentication ticket, which is used to generate the Bearer token.

Sample Request/Response


var loginData = {
    grant_type: ‘password’,
    username: self.loginEmail(),
    password: self.loginPassword()

    type: ‘POST’,
    url: ‘/Token’,
    data: loginData
}).done(function (data) {
    // Cache the access token in session storage.
    sessionStorage.setItem(tokenKey, data.access_token);

Notice that we store the token in session storage, to use later when sending requests to the API. Unlike some forms of authentication (such as cookie-based authentication), the browser will not automatically include the access token in subsequent requests. The application must do so explicitly. That’s a good thing, because it limits CSRF vulnerabilities
HTTP Request

POST https://localhost:44305/Token HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 68


HTTP Response

HTTP/1.1 200 OK
Content-Length: 669
Content-Type: application/json;charset=UTF-8
Server: Microsoft-IIS/8.0
Date: Wed, 01 Oct 2014 01:22:36 GMT

  “.issued”:”Wed, 01 Oct 2014 01:22:33 GMT”,
  “.expires”:”Wed, 15 Oct 2014 01:22:33 GMT”

Log Out

Because the browser does not cache the credentials or the access token, logging out is simply a matter of “forgetting” the token, by removing it from session storage:

self.logout = function () {

Let’s get the protected Resource from WebAPI Resource Server


In the WebApiConfig.cs Register method, the following code sets up Bearer Token authentication for the Web API pipeline:

config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

The SuppressDefaultHostAuthentication method tells Web API to ignore any authentication(e.g. MVC cookies authentication) that happens before the request reaches the Web API pipeline, either by IIS or by OWIN middleware. That way, we can restrict Web API to authenticate ONLY using bearer tokens.

The HostAuthenticationFilter class enables authentication using bearer tokens.



  1. The HostAuthenticationFilter calls the OAuth middleware to validate the token.
  2. The middleware converts the token into a claims identity.
  3. At this point, the request is authenticated but not authorized.
  4. The AuthorizationFilter [Authorize] examines the claims identity.
  5. The controller returns the protected resource. Otherwise, the client receives a 401 (Unauthorized) error.
Sample Request/Response

// If we already have a bearer token, set the Authorization header.
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
    headers.Authorization = ‘Bearer ‘ + token;

    type: ‘GET’,
    url: ‘api/values/1’,
headers: headers
}).done(function (data) {

HTTP Request

GET https://localhost:44305/api/values/1 HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Authorization: Bearer imSXTs2OqSrGWzsFQhIXziFCO3rF…
X-Requested-With: XMLHttpRequest

HTTP Response
A failed one when Bearer token is missing or incorrect:

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
WWW-Authenticate: Bearer
Date: Tue, 30 Sep 2014 21:54:43 GMT
Content-Length: 61

{“Message”:”Authorization has been denied for this request.”}

A success one:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Wed, 01 Oct 2014 01:41:29 GMT
Content-Length: 45

“Hello from Action Method,”