Protractor (Angular Testing) – Installation
Install Selenium: npm install -g webdriver-managerInstall Protractor: npm install -g protractorUpdate Selenium: webdriver-manager updateStart Selenium: webdriver-manager start http://localhost:4444/wd/hub
SharePlex Conflict Resolution
To resolve conflicts for SharePlex you need to setup the conflict resolution methods. In additions all tables involved must have a primary key. Also it is commonly a good idea for each table to have a last updated and last site field. These can be used by the replication to work out what is the […]
Force angular to refresh pages when called via the router
How to force the router in angular to always reload when the page is called again… @ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})], exports: [RouterModule], })
Post/Put
Post: Create new resources where server assigns Id. update a set of resources Will have an effect if same data issued multiple times. Put: Create a new object where the client takes the lead and assigns the Id Update a resource using an id. Will NOT have an effect if same data issued multiple times.
Angular – Route Guards
import {Injectable } from ‘@angular/core’; import {CanDeactivate } from ‘@angular/router’; @Injectable() export class PetGuard implements CanDeactivate { canDeactivate(component: PetComponent): Boolean { if(component.form.dirty) { return confirm(‘Navigate away? Your changes will be lost’); } return true; } } Remember: import the guard.. import { PetGuard } from ‘./pet-guard.service’; register the guard as a provider tie the guard […]
Angular – Routing
Defining routes… Here’s a complex route definition. You can add more using commas. This route allows an id to be passed to the route. Also a guard is setup allowing access to the controlled. The final element is the component who’s template will be activated: { path: ‘pets/:id’, canActivate: [ petsGuard], canDeactivate: [petsDeactivate], component: PetsComponent […]
Angular – Form Arrays
We can duplicate form controls or form groups using a form array. Remember to setup a div with a form group when added to the component code. build a function that creates the formgroups: buildFields(): FormGroup { return this.fb.group({ field1: ‘1’, field2: ‘2’ }); } Replace the way we were building the fields inside the […]
Angular – Reactive Forms – Transformations
List of transformations: https://GitHub.com/ReactiveX/rxjs/tree/master/src/operator Examples: debouce Time (Waits until a time before firing) throttleTime (emits a value then waits a time before emitting any further) distinctUntilChanged (Only reacts once and ignores duplicate items) We use this by adding like so: import ‘rxjs/add/operator/debounceTime’ myControl.valueChanges.debounceTime(2000).subscribe(v => this.message(message));
Angular – Reactive Forms – Change
Angular Reactive Forms can manage changes from the user via events in the code. This can enable us to change validation rules, display messages, change user interface elements or much more.. Here’s an example of adding a notification based on a value change. This one is setup from within OnInit: this.customerForm.get(‘note’).valueChanges.subscribe(value => this.setNotify(value)); We can […]
Angular – Form Validation
We can use basic validation in html… ..you can see that the field is required and must be 3 characters minimum length. This and more complex validators can be defined in the code instead making the system more flexible.. import { Component, OnInit } from ‘@angular/core’ import { FormGroup, FormControl, FormBuilder, Validators } from ‘@angular/forms’ […]
Angular – Using Form Builder
We can use formbuilder rather than declaring each component and form group new ourselves. This relies on us adding the import “FormBuilder from @angular/forms We then use this by utilizing the constructor: import { Component, OnInit } from ‘@angular/core’ import { FormGroup, FormControl, FormBuilder } from ‘@angular/forms’ export class OurComponent implements OnInit { customerForm: FormGroup; […]
Angular – Template and Reactive Forms
There are two types of form you can use with Angular “Template driven” and “Reactive” (also known as “Model driven”). Template driven forms rely on the html to deal with the majority of the form building. See below for a Template driven form. This binds a property from our component class to the value of […]
Sanitise URL
You may need to trust a URL first, otherwise the DomSanitizer will remove it (see the docs). url = sanitizer.bypassSecurityTrustUrl(‘data:image/jpeg;base64,’ + image) Then you can use that url and bind it: .
Using Mat Icons
Mat icons allow a quick way of utilising many different icons without needing to ref local files. You can find many examples on the web but here’s one of the sites you can get them from https://material.io/icons/. Here’s one way I’m using them in practice: vpn_key {{counts.DoorCount}} Doors
Using DevExpress toolkit
There a many premade Angular tools out there. For instance the DevExtreme tool kit which can be found here: https://js.devexpress.com/. Here’s an example of using it for creating a table:
XML Config File Load Angular
config.json file: This is the file we want to load information from. This needs to be globally accessible so will need to be put in a directory under assets. { “apiUrl”:”http://localhost:9000″, “readerUrl”: “http://localhost:8088” } main.ts file: This loads are new config file. import {Config} from “./app/app.config”; Config.loadInstance(‘assets/config/config.json’) .then(() => { platformBrowserDynamic().bootstrapModule(AppModule); }); app.module.ts file: This […]
SharePlex Oracle Replication
SharePlex Replication SharePlex is a potential replacement for Oracle Advanced Replication or Oracle Streams Replication. Now that both these have been removed from Oracle 12C its time to consider alternatives. Oracle Gold Gate is a possible but it’s expensive and complex. SharePlex seems to have a lot going for it in terms of simplicity and […]
Updating DB Scaffold
To update the scaffold you need to set the force flag: Scaffold-DbContext “Server=;Database=;user id=;password=;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False” Microsoft.EntityFrameworkCore.SqlServer -f -OutputDir Models note the -f
Issues with Node and NPM?
Setup NPM: If you change to the windows installation folder then you can update NPM. Otherwise it sometimes gets stuck for you. Cd\Program Files (x86)\nodejs npm install npm Reinstall angular: npm uninstall -g angular-cli npm cache clean npm install -g angular-cli@latest
Entity Framework Scaffold DBContext (ASP.NET Core)
Steps: – Install EF: Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools –Pre Install-Package Microsoft.EntityFrameworkCore.Design Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design – Add to project.json “tools”: { “Microsoft.EntityFrameworkCore.Tools.DotNet”: “1.0.0-preview3-final”, “Microsoft.AspNetCore.Razor.Tools”: “1.0.0-preview2-final”, “Microsoft.AspNetCore.Server.IISIntegration.Tools”: “1.0.0-preview2-final” }, – From “NuGet Package Manager” then “Package Manager Console” Scaffold-DbContext “Server=;Database=;user id=;password=;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models – Update appsettings.json to include the connection string.. “Data”: { “DefaultConnection”: { “ConnectionString”: […]
Angular Christmas Countdown
A quick play with some JavaScript and Angular.js to create a Christmas Counter for my Daughters The HTML: Imogen and Emily’s Christmas Counter Time Now: {{ time | date:’dd/MM/yyyy HH:mm:ss’ }} How Long to go: {{ myDays }} days, {{ myHours }} hours, {{ myMinutes }} mins, {{ mySeconds }} seconds. The JavaScript […]
Claims Based Authentication WebAPI
Create an Authorisation Attribute: namespace S3ID.PAS3.Api.AuthAttributes { using System.Security.Claims; using System.Web.Mvc; public class ClaimsAuthorizeAttribute : AuthorizeAttribute { private string claimType; private string claimValue; public ClaimsAuthorizeAttribute(string type, string value) { this.claimType = type; this.claimValue = value; } public override void OnAuthorization(AuthorizationContext filterContext) { var user = filterContext.HttpContext.User as ClaimsPrincipal; if (user != null && user.HasClaim(this.claimType, this.claimValue)) […]
Serialise and deserialise with JSON
Serialising allows objects to be converted to strings and then back. This is especially useful when dealing with sending complex objects over the wire. JSON has become the go to standard.. JSON Convert is a simple way of serialising objects to strings.. // My Class I want to serialise MyClass myClass = new MyClass(); // […]
Auto resolution and Dependency Injection
Rather than implementing a class that declares all of your dependency injection registrations you can implement a piece of code that will work through your application and automatically register any class identified by a particular interface (usually a blank interface used exclusively for this purpose. Blank interface: namespace Library.Initialisation { /// /// Interface IAutoRegisterAsTransient. Use […]
Adding a snippet in Visual Studio
Adding a snippet in Visual Studio can save time later.. Open notepad and type: Hello World C# Myself Says Hello to the world. hello System.Windows.Forms.dll System.Windows.Forms Place your code after : Save as utf-8! Copy to: C:\Users\\Documents\Visual Studio \Code Snippets\Visual C#\My Code Snippets\.snippet See: https://msdn.microsoft.com/en-us/library/ms165394.aspx My Snippet to set up a viewmodel for my project: […]
Datagrid newrecord placeholder change default value’s
How to change the datagrid so that when it allows a placeholder new row to be available it has a hint in it as default. In this case <Enter New Record Here>. This uses FallbackValue.
Datagrid row delete button with new row placeholder disable
Aim: To create a button on a datagrid to delete a row but not crash on the new row placeholder row. Method: Add a column like any other inside the datagrid but use a template type to show the button.
Changing a new datagrid row style
Changing a new datagrid placeholders row style:
WPF Commands
First Create a Delegate in ViewModel as a declaration: public DelegateCommand Deploy { get; set; } Next create the method you are going to call: //Deploy Module Clicked – This one takes ro_clientmodules_extend from my grid! private void Deploy_click(ro_clientmodules_extend obj) { } Next sort out the viewmodel constructor: public LicenseDeploymentModuleViewModel() { Deploy = new DelegateCommand(Deploy_click); […]
WPF MessageBox
To create a WPF MessageBox use: MessageBoxResult dialogResult = System.Windows.MessageBox.Show(“Are you sure you wish to delete this?”, “Delete Confirmation”, System.Windows.MessageBoxButton.YesNo); if (dialogResult == MessageBoxResult.Yes) { System.Windows.MessageBox.Show(“Delete operation Worked”); } else { System.Windows.MessageBox.Show(“Delete operation Terminated”); }
Binding a TabItem visibility in XAML
This is a quick demo of how to bind your TabItem visibility so that you can quickly change what’s visible using variable in your viewmodel code. Create a Converter in a new class file Converters: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using System.Windows; namespace ConfigurationModule.Converters { [ValueConversion(typeof(bool), typeof(Visibility))] public class BoolToVisibilityConverter […]
Concatenate two observable collections
A quick reminder how to concatenate two observable collections: DeviceList = new ObservableCollection(DeviceList.Concat(DeviceList1));
C# delegates to update the UI from a thread
The Following enables a thread to update the main UI using a delegate. In this case MyTextBox.Text has an “x” added to its text property. Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => this.MyTextBox.Text += “x”));
Apply Changes Made to a Detached Object
This allows changes to be stored based on the original object and changed object: See: https://msdn.microsoft.com/en-us/library/vstudio/bb896248%28v=vs.100%29.aspx private static void ApplyItemUpdates(SalesOrderDetail originalItem, SalesOrderDetail updatedItem) { using (AdventureWorksEntities context = new AdventureWorksEntities()) { context.SalesOrderDetails.Attach(updatedItem); // Check if the ID is 0, if it is the item is new. // In this case we need to chage the […]
Adding a PRISMPROP snippet to VS C#
This sets up visual studio to add a snippet that will put in a prism style property really quickly and easily and help set this up fast! FOLDER: Documents\Visual Studio xxxx\Code Snippets\Visual C#\My Code Snippets\ FILE: prismprop.snippet XML: <?xml version=”1.0″ encoding=”utf-8″ ?> <CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”> <CodeSnippet Format=”1.0.0″> <Header> <Title>prismprop</Title> <Shortcut>prismprop</Shortcut> <Description>Code snippet for property and backing […]
MS Silverlight Fix error 6013
MS Silverlight not working and giving error 6013 C:\ProgramData\Microsoft\PlayReady delete the file: mspr.hds
Unique ID’s in Oracle and SQL Server
Generating unique ID’s in Oracle and SQL Server.. Oracle: Select sys_guid() from dual; SQL Server: Select (newid())
SQL Server CATCH block
Just like in Oracle SQL server allows the use of a catch block which can be very useful for debugging stored procedures! First set up a transaction: IF @@TRANCOUNT = 0 BEGIN TRANSACTION B4UPDATE ELSE SAVE TRANSACTION B4UPDATE Then catch any errors and rollback if needed saving data about the issue. If you also keep […]
SQL Server to_char conversion
When converting from oracle to SQL server you may struggle with Oracle to_char() and to_date() convertions. SQL server handles this differently. You have to used fixed types or you can use some clever madness. For YYYYMMDDHH24MISS : (SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), ‘-‘, ”), ‘T’, ”), ‘:’, ”)) For DD/MM/YYYY HH24:MI:SS : (select CONVERT(VARCHAR(10), […]
XAML relative size
How to size components to fit relative to parents in the tree: Width=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=ActualWidth}” Height=”{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}},Path=ActualHeight}”
Oracle Default Password Expiry
To prevent Oracle from expiring your accounts a few short months after installation you can turn off the auto expiring feature. When there’s no need for super security the auto expiry is a major annoyance! ALTER PROFILE “DEFAULT” LIMIT PASSWORD_LIFE_TIME UNLIMITED; ALTER PROFILE “DEFAULT” LIMIT PASSWORD_VERIFY_FUNCTION NULL; ALTER profile “DEFAULT” limit FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED; alter […]
signing java applets
Signing Java Applets: No. Description Detail/Example In the Dev Environment: 1. Create a folder and place all the jar files for the application inside. Mkdir s3idcertstore 2. Open CMD and move to the jar folder from step 1. Cd\s3idcertstore 3. Create a keystore “C:\Program Files (x86)\Java\jre1.8.0_25\bin\keytool” -genkey -keystore myKeystore -alias geoff -validity 9999 4. Add […]