Thursday, April 19, 2018

Angular - Transforming Data with Pipes

Sometimes we need to transform bound properties before it is displayed. Such is the case with formatting dates, currency, decimals, etc. Pipes can be chained.

Built-in Pipes


  • date
  • number, decimal, percent, currency
  • json, slice, etc
The complete list and more information can be found here.

Examples (no parameters):

{{ product.productCode | lowercase }}
<img [src]='product.imageUrl' [title]='product.productName | uppercase'>
{{ product.price | currency | lowercase }}

Examples (with parameters)

NOTE: Parameters are separated by colons

{{ product.price | currency: 'USD' : true : '1.2-2' }}


Custom Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'myTransform'})
export class MyTransform implements PipeTransform {
     transform(value: string, customParam1: string): string { ... }
}

Add it to your module (i.e. app.module.ts) as shown here:

@NgModule({
imports: ...
declarations: [ AppComponent, MyTransform ],
bootstrap: ...
})

Use it just like the built in pipes

Angular - Property and Event Bindings

Binding with Interpolation

Use {{expression}} to pull (only one way binding) in content from the component class. The expression can have many forms.

For example:
{{propertyName}}
{{'ABC' + functionName()}}
{{'Answer is ' + 3*2}}
{{showImage ? 'Hide' : 'Show'}} Image

<img src={{product.imageUrl}}>

Notice that it does not use quotes!

Property Binding

Property Binding is one way just like interpolation.

We could use interpolation to set the src url for an image using:

<img src={{product.imageUrl}}>

or 

<img src='http://someUrl/{{product.imageUrl}}'>

We can use Property binding to do the first case, but not the second case.

<img [src]='product.imageUrl'>

The syntax for Property Binding has a two parts:
  • Binding Target - Is always in surrounded by []
  • Binding Source - Is Surrounded by '' (two single quotes).
Generally, Property Binding is preferred instead of interpolation.

Event Binding

When the user clicks something an event is generated. We can listen for these events using Event Binding. Here is the syntax.

<button (click)='doSomething()'>

The syntax for Property Binding has a two parts:
  • Target Event - Is always in surrounded by ()
  • Template Statement - Is Surrounded by '' (two single quotes).
In this example, when the button is clicked the doSomething() method in our component class is executed.


Two-way Binding

This is useful for having the component and dom in sync such as in the case of an input field on a form.

<input [(ngModel)]='someProperty'>

The Banana in a Box metaphor can be used to remember the order of the parenthesis. Imagine the [()] to have a banana as () in a box as [].

The class for the component would be something like this.
export class MyComponent {
    someProperty: string = 'abc';
}

ngModel is a keyword defined in the FormsModule. The FormsModule will need to be added to the AppModule. To do this open your app.module.ts and add to the top of the file the following:

import { FormsModule } from '@angular/forms';

Next, in the same app.module.ts file add FormsModule to the array of imports in the @NgModule().


Wednesday, April 18, 2018

Angular - Page Layout syntax

Built-in Structural Directives

*ngIf

This adds control flow to the page for hiding and showing content based on conditional logic.

<div *ngIf='someLogic()'>
      Some content to show
</div>

*ngFor

This adds control flow to the page for looping over content like a for loop.

<div *ngFor='let obj of objects'>
      <div>{{obj.PropertyHere}}</div>
</div>

Tuesday, April 17, 2018

Angular - Creating a Component in Angular

Component

A Component has 3 parts

  • Template
    • View layout
    • Created with HTML
    • Includes binding and directives
  • Class
    • Code supporting the view
    • Created with TypeScript (.ts file)
    • Properties for data
    • Methods for logic
  • CSS
    • A CSS file for the styling needed for the component
  • Metadata
    • Extra data for Angular
    • Defined with a decorator

Example

app.component.ts file


import { Component } from '@angular/core';

@Component({
  selector: 'myApp-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Hello World';
}

  • The import pulls in dependency references
  • @Component is the metadata / decorator that says the class is a component. This is similar to an [Attribute] in C#
  • export makes the class definition available for user elsewhere.
  • The selector is a unique value for this component in the application. It is suggested you prefix selectors with something that identifies it as part of your app. This is also what is used as a tag to use this component in another component. In this case it is <myApp-root><myApp-root>
  • It is common to append "Component" to the name name of the class so that it is clear that it is a component.

app.component.html

<div>
  <h1>
    Hello{{title}}!!
  </h1>
</div>

This is the HTML that defines the layout. Anything in {{...}} tags are binds to properties in the class associated with this component.

app.component.css

h1 { text-align:center }

This is a standard CSS file, except these styles will be unique to this component automatically. They will not affect other styles in the project.

Imports

Some common Angular Modules you may need to import are:
  • @angular/core (as we have done above)
  • @angular/animate
  • @angular/http
  • @angular/router

Using the Component

This is how you would use it in index.html for example:

<body>
<myApp-root></myApp-root>
</body>

Telling index.html about our Component

In app.module.ts you list what angular modules should be included in our application#

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular - Running Angular application using npm / Visual Studio Code

Assumptions

Using Visual Studio Code (on Windows)

Opening Integrated Terminal

View menu -> Integrated Terminal

Install packages

Open Integrated Terminal and type:
npm install

Launching Angular Application

Open Integrated Terminal and type:
npm start
This will build app and launch in the browser.

This also launches the web server. To stop the web server type control-c at the command prompt.

Tuesday, March 27, 2018

Setting the Timeout for the WinRM - SQL Server DB Deploy

The parameters to the WinRM –SQL Sever DB Deploy task in VSTS can be used do a backup using the inline sql script.It is a good idea to set the additional arguments  to be -ConnectionTimeout 120 -QueryTimeout 120 (for two minutes of timeout). Set the number of seconds to a reasonable value for your system.

If you don't and your backup exceeds the default timeout (90 seconds I believe), then you will get an error like this:

##[error]Microsoft.PowerShell.Commands.WriteErrorException: Deployment on one or more machines failed.
System.Exception: The running command stopped because the preference variable "ErrorActionPreference"
or common parameter is set to Stop: Timeout expired. The timeout period elapsed prior to completion
of the operation or the server is not responding.

It is actually SQL Server complaining that the time has elapsed, but it is doing so based on wht the WinRM says is the timeout.

To set the timeout open your WinRM - SQL Sever DB Deploy task in VSTS and set the Additional Arguments to  -ConnectionTimeout 120 -QueryTimeout 120.

Friday, March 16, 2018

Change Windows credentials when connecting to a database using Windows Authentication

Image you have a two accounts in Active Directory. You have one that you log into Windows (call it BasicUser1 for example). The other is one that you use for development and is the account (call it DevUser1 for example) that you need to use to access a MS SQL Server database using Windows Authentication.

Now when running SSMS (SQL Server Management Studio), LINQPad, Visual Studio, etc and trying to connect to a database that requires Windows Authentication (using DevUser1), but you are logged into Windows as BasicUser1 which doesn't have permissions to the database.

The problem is how do we impersonate DevUser1 when connecting to the database using Windows Authentication. The answer is actually pretty simple and seamless once configured.

The answer is the Credential Manager built into Windows. You can find it in the start menu, but you can also run it directly using:

control /name Microsoft.CredentialManager

It looks something like this:



Click the Add a Windows credential link.

Enter the fully qualified server name, etc AND the port for the SQL Server database (the default is 1433). The username should be in the format domain\username. The password is the password for the specified user.

Now when you connect to the database with Windows Authentication Windows will automatically pass the credentials specified in the Credential Manager, not the ones you are currently logged into Windows as.