Showing an #Angular Component in place of #LeafletJS popup dialog

In an earlier post we went over the steps to add a LeafletJS map to an Angular application. The example initialized the map to be centered over Europe and then when the user clicked on a button the map would pan over to Philadelphia, Pennsylvania USA and draw a circle marker over the city. To improve the usability of the map we are going to add a custom Angular component as the popup that appears when the user clicks on the circle. We’ll also show how to pass data to the component so it can be customized based on the marker clicks.

Starting off we’ll use the code from the original map project, angular-ivy-leaflet-map, as the base for this project. The completed solution for this post can be found on GitHub and a working demonstration can be seen on StackBlitz.

To show a custom popup we’ll create a new component that will serve as the popup dialog. From the console window generate the boiler plate code for the CustomPopup component via

ng g component CustomPopup

In the CustomPopup folder open the custom-popup.component.html file and add {{customText}} in a paragraph element that will serve as the dynamic text element that we’ll set from the calling component.

<h1>Custom Popup</h1>
<p>
An angular component rendered as a map popup.
</p>
<p>
  {{customText}}
</p>

In order to allow the parent component to set the value of the {{customText}} property we need to add it to the custom-popup.component.ts as an @Input property. This will also require adding Input as an import from @angular/core. This is no different then the normal way to pass data to a component in Angular.

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-custom-popup',
  templateUrl: './custom-popup.component.html',
  styleUrls: ['./custom-popup.component.css']
})
export class CustomPopupComponent implements OnInit {
  @Input() customText: string
  constructor() { }

  ngOnInit() {
  }
}

With the popup component complete the next step is to add code to the map component so it will use this CustomPopupComponent instead of the default LeafletJS popup.

For the Angular component to be usable by LeafletJS we need the component to be “transformed” into its final HTML and JavaScript form. Without the component in its final form, LeafletJS will have no idea what to do with component reference when it renders the popup.

Now I can’t take credit for this code that generates the usable form of the component. Credit goes to Darkguy2008 who had run into the exact same issue with LeafletJS that this post is going over. The code uses Angular’s ComponentFactoryResolver to transform the referenced component into a usable form. What follows is my understanding of how Angular renders the component on the fly.

The resolveComponentFactory() builds a model of the component based on its HTML and TypeScript definition. All external references are verified and linked to model. Then when the create() method is called it iterates through the component and builds its final form based on the model from the factory method result. Finally, the built component is attached to the view via the application reference and surround it with a div element so that no matter how the component is defined it has a single parent element for the popup.

private compilePopup(component, onAttach): any {
   const compFactory: any = this.resolver.resolveComponentFactory(component);
   let compRef: any = compFactory.create(this.injector);

   if (onAttach)
     onAttach(compRef);

   this.appRef.attachView(compRef.hostView);
   compRef.onDestroy(() => this.appRef.detachView(compRef.hostView));

   let div = document.createElement('div');
   div.appendChild(compRef.location.nativeElement);
   return div;
}

The last step is to call the compilePopup() method and pass the rendered view to the marker for the popup. We assign the generated view to the markerPopup variable and then assign it to the marker as the popup view through the bindPopup() method call. One other thing to note is the assignment of the customText variable for the CustomPopupComponent. We pass the assignment as an anonymous function that takes the component as a parameter. It then references the built instance and sets the @Input customText variable.

let markerPopup: any =
this.compilePopup(CustomPopupComponent,
(c) => {c.instance.customText = 'Custom Data Injection'});
// Generate a circle marker for this location
let currentLocation: L.CircleMarker = L.circleMarker([lat,

lng], { radius: 5})
// Add a binding for the popup to show a custom component
// instead of the standard leaflet popup
.bindPopup(markerPopup);

The final solution can be seen in action below or at StackBlitz. If you are running the project you will need to click on the Locate Philadelphia, PA button and then click on the circle marker to display the popup. To see the full project source code go to GitHub.

Generating Entity-Framework classes for .NET Core projects in a Database First scenario

Microsoft provides two command line tools in situations when there is a need to generate Entity Framework classes for a .NET Core project. Within the Package Manager console of Visual Studio you can use Scaffold-DbContext and if you are using the .NET Core CLI then the command dotnet ef is available. Details on the capabilities (migration, scaffold, update, drop, and more) as well as instructions on what needs to be installed can be found on EF Core tools reference – .NET Core CLI and Entity Framework Core tools reference – Package Manager Console in Visual Studio.

When using dotnet ef command in the .NET Core CLI you will add the scaffold argument which will allow you to generate classes for an entire database, specific tables, or schemas within a database. If you are using it against a specific set of tables then you will provide each table with the –table flag preceding the table name.

In this example the command will generate EF classes in order to interact with two common Identity tables, AspNetRoleClaims and AspNetRoles, within the dbo schema.

dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=IdentityServer;" Microsoft.EntityFrameworkCore.SqlServer --table dbo.AspNetRoleClaims -table dbo.AspNetRoles

Having the tool generate classes for a schema is just as simple. Instead of using the –table use –schema and provide the schema name.

If there comes a need to regenerate tables or add more then you will need to use the –force flag. This will allow the process to overwrite any files that already exist in the project. Make sure you include all tables or schemas that you want generated. Even if a table hasn’t changed since the earlier schema change you will still need to list it when regenerating the classes.

If you prefer to use the Package Manager console then the same command from above could be executed using only small changes. Instead of a flag for each table you will combine all tables in a space separated list within enclosing quotes.

Scaffold-DbContext -Provider Microsoft.EntityFrameworkCore.SqlServer -Connection "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=IdentityServer;" -Tables "dbo.AspNetRoleClaims dbo.AspNetRoles"

This post went over only a small portion of the capabilities that these tools provide. If you are designing a system to be a Code First approach then you’ll become very familiar with these tools as you generate initialization and migration scripts. If you are unfamiliar with with EF migrations then take a look at Managing Database Schemas to guide you through each step.

Adding maps to an #Angular application using the #Leaflet library

If you are looking to add maps to your Angular website or application a great option that I’ve used on a few projects is Leaflet.js. The library provides features like custom markers, ability to use various map sources, multiple layers, and much more. In addition to that it is also free, open source, and actively maintained. The project has been around for years and has an active community continuing to extend it with numerous plugins. The majority of documentation out there for the library focuses on using it in a vanilla JavaScript project so in this post we’re going to explore adding Leaflet.js to an Angular Ivy project.

In this application we’ll create a component that will hold the map object. It will be configured to always show Europe when it starts up but also provide a button to pan the map to a specific location. The user can change the zoom or move the map around as they wish. There will also be callbacks setup to execute when the user changes the zoom level or the center of the map. You can see the complete project on GitHub. A running example can also be seen on StackBlitz.

To start off, if you don’t already have an Angular app to add the mapping feature to, create a new one.

$ ng new leaflet-map-example

Once the project is initialized we will need to add references to Leaflet and its Typings definition to the project. This can be done by opening the package.json file and adding
"leaflet": "^1.6.0"
to the dependencies section. In devDependencies add
"@types/leaflet": "^1.5.7"

Another location that needs to be updated is the angular.json file. Under "projects" --> "demo" --> "architect" --> "build" --> "options" --> "assets" add this code that will copy leaflet assets out to the leaflet folder during the build process.

{
    "glob": "**/*",
    "input": "./node_modules/leaflet/dist/images",
    "output": "leaflet/"
}

Also, just below the "assets" section should be the "styles" section. In this section add this line so we can bring the Leaflet styles over to the application during the build.

"./node_modules/leaflet/dist/leaflet.css"

Next we’ll want to create a new component that will hold our logic for this map. From the command line run:

$ ng generate component map

We should now have a new folder in our project called map that contains three files: map.component.css, map.component.html, map.component.ts. The majority of our work will be in the TypeScript file but we still do need to add some code to the CSS and HTML files.

In map.component.html we’ll add two <div> tags, one to encompass the HTML for the page and another to hold the map. At the bottom of the page we will have a button that calls a function in the TypeScript code to pan the map on a specific location.

<div class="map-container">
  <div id="map"></div>
  <br />
  <button (click)="centerMap(39.95, -75.16)">Locate Philadelphia, PA</button>
</div>

Next we’ll add some CSS to define the size and add a border to the map in map.component.css.

#map{
  border: 2px solid black;
  height: 400px;
  width: 100%;
}

With the scaffolding in place we can now focus on map.component.ts to add the code which will instantiate and customize the actual map. The first line of code we’ll add is to import the Leaflet library at the top of the file.

import * as L from "leaflet";

Within the class definition add a variable to hold the map object.

map: L.Map;

We’ll setup the actual actual initialization of the map object and tie it to the HTML DOM in the ngOnInit() function.

The map object will be configured to center the map on a latitude and longitude over Europe. We’ll have the zoom level set to 4 and restrict the permitted zoom levels to be between 1 and 10. Besides those properties the most important part of the initialization is the first parameter, 'map'. This value matches up to the ID field in one of the map.component.html <div> elements and tells Leaflet to use that element to render the map.

// Initialize the map to display Europe    
this.map = L.map('map',
 {
      center: [49.8282, 8.5795],
      zoom: 4,
      minZoom: 1,
      maxZoom: 10
});

Before anything can be displayed we also need to let Leaflet know where to retrieve the tiles for the map. If you aren’t familiar with tiles they are the background image that is displayed. These can be road maps, start charts, or any other image. In this example the tiles are pulled from the OpenStreetMap.org repository. We’ll do this by creating a Tile Layer and then add that layer to the map object.

const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 10,
  attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});

tiles.addTo(this.map);

In the HTML for the component there is a button that calls a centerMap() function, passing it latitude and longitude values. When called, this function will pan the map over to the new center coordinates, draw a circle marker on that location, and zoom to a specific level.

centerMap(lat: number, lng: number): void {
this.map.panTo([lat, lng]);
// Generate a circle marker for this location
let currentLocation: L.CircleMarker =
L.circleMarker([lat, lng], {
radius: 5
});
currentLocation.addTo(this.map);
// Wait a short period before zooming to a designated level
setTimeout(() => {this.map.setZoom(8);}, 750);
}

With the definition of the map component completed we need to add the component to the app.component.html file so that we can actually see it in the applicaiton.

<app-map></app-map>

There is one last piece of the puzzle that we need to add in order for the maps to be displayed correctly. We need to reference the Leaflet CSS code in the project’s styles.css file. Without the reference we won’t be able to pull the styles into the project.

@import "~leaflet/dist/leaflet.css";

If you forget this piece you’ll see a partial map appear on the site. A few squares of the map will be visible and if you look in the Console window you won’t see any errors reported. The fact that you missed the styles file isn’t obvious so be sure to include it.

At this point we should be able to run the project and see the map displayed similar to the below image.

$ ng serve

Then when you click on the Locate Philadelphia, PA button it will pan the map over to the city and draw a marker on the city.

If there is a need to take actions when the user changes the zoom level of the map or drags the map to a new location it can be achieved by adding listeners to the "zoomlevelschange" and "moveend" events. In this example we’ll add them during the initialization of the map.

// Initialize the map to display Europe
this.map = L.map('map', {
center: [49.8282, 8.5795],
zoom: 4,
minZoom: 1,
maxZoom: 10
}) // Create a callback for when the user changes the zoom
.addEventListener("zoomlevelschange", this.onZoomChange, this)
// Create a callback for when the map is moved
.addEventListener("moveend", this.onCenterChange, this);

From these callbacks you can grab the new center, zoom level, or map boundaries by accession the map object referenced via the this object. You can see examples of these in the map.component.ts file.

Hopefully this post helps get you on your way adding Leaflet maps to your Angular project. Besides a few behind the scenes updates of files the process is straight forward. In a future post I’ll go over adding markers and custom popup dialogs.

Easy #Angular #Authentication and #Authorization setup using #DOTNETCORE

For the last few months I’ve been struggling to find an authentication and authorization setup that felt right for one of my projects. My requirements were basic. Have a system that I could use to limit access to my API endpoints and front-end components based on the roles of a given user. The back-end was to be written in C# using .NET Core 3.1 and the front-end in TypeScript and Angular.io. The system would also be self-contained, i.e. no external login providers.

Initially I used the default template from Visual Studio for generating an ASP.NET Core Web API project that uses a SPA framework for the front-end and IdentityServer 4 (IS4) to handle the authentication and authorization. It was a nice setup which makes it easy to tie in outside providers (i.e. Google, Microsoft, Facebook, etc) so users can signup using their login from another site. If you aren’t familiar with IS4 then reading the documentation and going through the various examples are a must. The drawbacks I saw was the complication of the system seemed greater than what my project needed and the authentication process required either a popup window, navigating away from the client site, or adding custom security headers to allow the login page to appear in a iframe.

So I went back to searching for other ways to handle authentication and authorization with .NET Core and reading up on the core concepts. Honestly reading the IS4 documentation was also a great way learn. After a few weeks I found a great write-up by Ankit Sharma titled Policy-Based Authorization In Angular Using JWT. Not only was the post well written, if you download the code from their GitHub repository it actually works!

The author goes through the process of creating a new ASP.NET Core 3.1 Web API project and a separate client app using Angular.io 8.3. The client will receive a JSON Web Token(JWT) that includes some basic information about the user, including the roles associated with the account. With this data the client can enable routes and features with basic checks and route guards.

The implementation is well thought out which makes conceptualizing how you could add new features easier. Some of the features that one might want to add are incorporating an auto-refresh of the token while the user is on the site, changing the credentials and auth data storage from in-memory to a database, adding password changes, logging out all active sessions for a user, or registering new users.

Yes, the author didn’t go over these but they did provide a solid foundation to start experimenting. Now if you do need all of these options then maybe revisiting IdentityServer 4 is a good idea since it provides a ready built framework to build a full-fledged identity management system. But for a simpler setup, the write-up by Ankit Sharma is a great starting point.

Adding a #D3.js line chart to an #Angular.io project

D3.js (Data Driven Documents) is a powerful JavaScript library. At a basic level you can transform data into interactive charts and graphics that are easy to digest by your visitors. If you aren’t familiar with the library then take a look at their site for examples. I’ve also added a few links to other sites that showcase the capabilities.

While D3 provides documentation on the API and tutorials they also recommend looking at the examples from other developers to see how it all works. If you are looking for an example to show you how to get a basic line chart then you can use this post or look at their Line Chart example for a pure JavaScript implementation.

The example I’ve built for this post displays three different types of weather information for Philadelphia, Pennsylvania, Tempareture, Dewpoint, and Visibility. The example also has a button that the user can click on to change the displayed weather information. The data for the chart is stored in a JSON file in the assets directory of the project but it could have just as easily been an HTTP request to an API. To see the code for the example take a look at my GitHub repository angular-d3-line-chart-demo. If you’d like to see the chart in action then head over to Stackblitz.com for a running example. The rest of the post will go over the implementation as a technical discussion with references back to the code in the repository.

Adding D3.js to the Angular project requires adding the D3 core logic package and it’s associated Types files to the project. You may also need to add these other packages: d3-array, d3-axis, d3-scale, and d3-shape. Keep these packages in mind if you run into errors mentioning those packages. While I didn’t need them in my personal project, it is in Angular.io 8, I did need them when I was building this example on Stackblitz.com which is in Angular.io 9.

npm install --save d3
npm install --save-dev @types/d3

In order to encapsulate the chart related elements I created a custom component called line-chart.component. This component holds the chart, labels and controls to show the current type of data being displayed as well as a button to change the data. The encapsulated component can now be reused on the same page to show different data while providing the same user experience.

ng g component LineChart

When the component first initializes we need to configure the element that will contain the graph. When working with D3.js charts the element is an SVG. Within the buildSVG() function you’ll see all of the initial configuration performed on this SVG.

  • Grab the SVG element owned by this component, a simple task since it is owned by the component and there is only one SVG element
  • Set the height and width of SVG based on margin calculations
  • Add text to serve as a watermark in the chart

Because the chart data is dynamic the configuring of the X and Y axis aren’t performed during the initial configuration of the SVG. Instead, once the data is retrieved we’ll transform it into a format that is easily digested by the chart and the maximum/minimum values for the axis can be extracted.

The starting point for the data selection, transformation, and update of the graph occurs in the updateGraphData() function. This function is called during the component initialization as well as when the user clicks Change Chart Data button. From here the following functions are executed that will refresh the chart with the latest information.

  • clearChartData() – finds all path elements, lines on the chart, and removes them from SVG element.
  • buildChartData() – transforms the original JSON data into a simplified object containing a value and date field for consumption by the chart logic.
  • configureYaxis() – the Y-axis is going to represent some kind of numerical data. For this we can use the d3Array.scaleLinear(). Because we don’t want to have any of the data resting on the X-axis line we reduce minimum of the Y-axis range by 1. D3.js provides a function that will retrieve the minimum and maximum values in an array called d3Array.extent().
  • configureXaxis() – the X-axis is going to represent a time series so we’ll generate a scale based on the date property of the data and using d3Array.scaleTime().
  • drawLineAndPath() – the function uses the d3Shape.line() function to configure which parts of the data will be associated with the X and Y-axis. It also defines the look of the line, i.e. color and thickness.

With all of these functions combined we are able to initialize, configure, and draw the line chart as part of an Angular.io component. Other features that could be added are line tool tips, transitions between chart drawing, and showing two sets of data at one time. As I learn more about building charts with D3.js I will add new posts to describe how to add those features.

As mentioned earlier, take a look at the GitHub repository for all of the code. I’m going to continue updating and cleaning up the project as I learn more about D3.js line charts. Because of that I didn’t include any of the code in this post. I didn’t want to leave readers with one version discussed in the blog post while a newer version exists in the repo. If you have any questions or run into problems leave me a comment and I’ll see if I can help out.

Creating an #Azure #SQLSERVER database login account

A few weeks ago I posted the steps to create a login account in SQL Server which utilized SQL Server Authentication. While the steps work perfectly for local instances of SQL Server it doesn’t work on when you are operating in Azure SQL Server. I realized this quickly when I decided to use the steps at work with no success. Luckily the differences aren’t major, which this post will go over, so without further delay, here is what you need to do.

The big difference between creating an account on an Azure based SQL Server database versus a local server is under which database you run the steps. When creating the login you’ll run under the master database. Then when creating the user you’ll need to run it once under master and then again under the database the account should be associated with.

-- Execute from master database on the server
CREATE LOGIN [DbLoginUser] WITH PASSWORD = 'Password1'
GO
CREATE USER [DbLoginUser] FOR LOGIN [DbLoginUser] 
GO

The above script creates the login which you should be able to test out immediately after running them. You won’t have access to any of the databases on the server but you should be able to log into the server. The next script will associate the login with the particular database and place it in the db_owner role.

-- Open a new query window in the database you want to create the user
CREATE USER [DbLoginUser] FOR LOGIN [DbLoginUser] WITH DEFAULT_SCHEMA = [dbo]
GO
ALTER ROLE db_owner ADD MEMBER [DbLoginUser]
GO

With the steps completed you should be able to log into the server with the new DbLoginUser account. Additionally, you have full control over the database the user was created under.

The shallow and deep end of copying #JavaScript #arrays

In JavaScript, arrays are passed around by reference. What this means is that if you assign a variable so that it equals another variable which is defined as an array then a pointer to the original array is assigned to the new variable. You will now have two variables pointing to the exact same array object. This is unlike primitive types in JavaScript where when you assign them to a variable the value is copied to the new variable and allocated its own memory.

Below is an example showing the same reference being used in two different variables. It also shows what happens to the array when a new value is added to one of the variables pointing to the array.

<script>
   // Create the default array that will hold our standard names
   var defaultNames = ['Jack', 'Jill', 'James'];
   // Write all of the default names
   console.log('Default Names: ' + defaultNames.join());
   
   // Create another variable that will be initialized with default names 
   // and will hold more names
   var moreNames = defaultNames;

   moreNames.splice(0, 0, 'Jerry');
   // Write all of the more names
   console.log('More Names: ' + moreNames.join());
   // Write all of the default names
   console.log('Default Names: ' + defaultNames.join());
</script>

The result of this script is the following output:

Default Names: Jack,Jill,James
More Names: Jerry,Jack,Jill,James
Default Names: Jerry,Jack,Jill,James

Instead of the variable defaultNames remaining with its original assignment of three names it now includes the name Jerry because the reference to the array was assigned to the moreNames variable. Since both variables are pointing to the same array this is expected behavior. What we would really want is to have the values of defaultNames assigned to the moreNames variable so that we could manipulate one of the arrays without changing the other. In this post I’ll go over a few operations native to JavaScript that we can use. The first method is the slice() operation.

The slice() method goes through the array and creates a shallow copy of each element in the array. This means that if you have objects, not primitive types like numbers, then the reference to the object will be copied. The result is a new array object being created which will allow you to add and remove objects from each array without worry of impacting the other one.

So instead of doing the assignment:

var moreNames = defaultNames;

We instead use the slice() method:

var moreNames = defaultNames.slice();

This will result in the following output:

Default Names: Jack,Jill,James
More Names: Jerry,Jack,Jill,James
Default Names: Jack,Jill,James

Now the defaultNames array is not impacted when we add the name Jerry to the moreNames array.

Something new in ES6 is the spread operator […] which can be used to perform a shallow copy like the slice() method.

var moreNames = [...defaultNames];

The result will be the same as what was output when we used the slice() method. One of the neat features that I like with the spread operator is the ability to easily join of two arrays.

var moreNames = [...defaultNames, ['Gina', 'Greta', 'George'];
// Now moreNames contains ['Jack', 'Jill', 'James', 'Gina', 'Greta', 'George']

This would result in moreNames consisting of all the values from defaultNames plus the values in the second array. Again, all values are shallow copied into a new array object before they are assigned to the variable.

As mentioned earlier both of those methods only perform a shallow copy of the array objects. That means if your array contains references to objects then modifying the object in the one array will also modify it in the other array. In some cases this is desired but for the cases where it isn’t a quick way to perform a deep copy is to utilize the JSON object. We can use the stringify() method to convert the array into a JSON string and then the parse() method to convert it back into a JavaScript object.

<script>
   var defaultNames = [
     {first: 'Amelia', last: 'Smith'}, 
     {first: 'Christopher', last: 'Conner'}
   ];
   var modifiedNames = JSON.parse(JSON.stringify(defaultNames));
   newNames[0].first = 'Jennifer';
   console.log('Default Names: ' + JSON.stringify(defaultNames));
   console.log('Modified Names: ' + JSON.stringify(modifiedNames));
</script>

Thanks to the array object being converted into a string and then back into its native objects the two variables have completely different references for all objects in the array. This results in the following output:

Default Names: [{“first”:”Amelia”,”last”:”Smith”},{“first”:”Christopher”,”last”:”Conner”}]
Modified Names: [{“first”:”Jennifer”,”last”:”Smith”},{“first”:”Christopher”,”last”:”Conner”}]

In this case the first name in the modifiedNames output changed from Amelia to Jennifer. Had we used the slice() or […] operations to make the copy then both arrays would have had their first element change to Jennifer. With one, possibly two if you split out the function calls you are able to create a true deep copy of the array. This simplicity of the JSON object to create a deep copy makes it a great option for most use cases.

There is always the option, and sometimes it is warranted, of rolling your own code to create copies of arrays but is it really needed? If the language is already providing you with the tools to complete the operation then use them. This will keep your code maintainable, the method calls will most likely be better documented, and there will be a much lower risk of bugs in the native operation as compared to your own.

Basic steps to create a new #SQLSERVER database account

Once or twice a year I need to create an account for a SQL Server database that utilizes database authentication.  And every time I have to do this I end up spending too much time searching for the correct steps.  So this post is to help keep me from forgetting what to do for the rest of my career.

In the example below, the database we want to create an account for is [TestDatabase].  The login that will be used for authentication is DbLoginAcct.  And the user that will grant the login access to [TestDatabase] and the [dbo] schema is DbUserAcct.

USE [TestDatabase]
CREATE LOGIN [DbLoginAcct] WITH PASSWORD=N'test', DEFAULT_DATABASE=[TestDatabase]
GO
CREATE USER [DbUserAcct] FOR LOGIN [DbLoginAcct]
GO
ALTER USER [DbUserAcct] WITH DEFAULT_SCHEMA=[dbo]
GO
-- We want this user to have full control of the database so make it a db_owner
ALTER ROLE [db_owner] ADD MEMBER [DbUserAcct]
GO

After running the script we can log into the database by using the DbLoginAcct credentials.  If this is the first account on the server using database authentication you may run into issues when authenticating.  To fix these issues take a look at  How to Fix Microsoft SQL Server Login Failed Error 18456?

Finally, two things worth noting are the difference between the LOGIN and USER objects created as part of the script.  As it relates to the server, the LOGIN is used for authentication and the USER is used for authorization.  In other words, the LOGIN gets you into the server while the USER gets you access to the specific database.

Update:  This is for a non-Azure SQL Server Instance.

Removing #MVC Form #ModelState Errors when the form data model can’t be altered #csharp

When working on .NET MVC projects you may run into a situation where you need to override the state reported by the ModelState object.  In case you aren’t familiar with what the ModelState object is, in the case of MVC controllers the ModelState object provides details on whether the data in a form sent to the controller passes all model defined attribute validation checks.  A call to ModelState.IsValid returns a boolean value to indicate the state, true for all checks passed, false for one or more errors present.  Further details on the reasons why the model is not valid can be retrieved from the ModelState.Errors collection.  In some cases it may be necessary to remove some validation errors from the ModelState before calling ModelState.IsValid.  

I recently had to do this when a complex form required a major overhaul.  Ideally we would have built new form data models but constraints on the project didn’t permit the investment.  Instead a function was created that would remove validation errors for the few form elements causing validation issues.

The function wasn’t complex.  For our needs we wanted to remove all errors against an element that contained a given name.  This was because our form would contain input elements with names like these that created a natural hierarchy and grouping:  Car.Door.Front.Passenger.Color and Car.Body.Windshield.Size.  To do this we’d check each ModelState Key to see if it contained the element name of interest.  If it did then the ModelState.Values object at the same index of the found key would have its Errors collection cleared.

public void RemoveModelStateErrors(string elementName) {
    for(var idx = 0; idx < ModelState.Keys.Count; idx++) {
        if (ModelState.Keys.ElementAt(i).Contains(elementName)
            && ModelState.Values.ElementAt(i).Errors.Count > 0) { 
            ModelState.Values.ElementAt(i).Errors.Clear();
        }
    }
}

The function could be simplified if you always know the exact element name or it could be refactored to handle a list of element names.  Either way once the function is called, any errors related to the elementName would be removed and the ModelState.IsValid call will be updated accordingly.  If the only errors were related to the elements that were just removed then it would return true for the valid model.

Setting up #TypeScript and Runtime Compilation in #VS2019 for #ASPNETCore

Last week I started a new web project to test out ASP.NET Core and Visual Studio 2019.  With all of the changes between the IDE, project configuration, and MVC boilerplate code I figured waiting until work and life slowed down a bit would be ideal.  With the end of the year near the slowdown has finally happened.

The boilerplate code setup hasn’t been difficult, and as expected, well documented.  At this point in the project I’ve setup all references to data access classes outside of the main project to utilize dependency injection.  .NET Core makes this extremely simple I and recommend all developers who are hesitant to use DI to take a look at Microsoft’s documentation.

Two areas that stumped me for a bit were areas that were relatively simple in Visual Studio 2017.  The first one was getting TypeScript to compile and build the mappings properly for debugging.  Prior to .NET Core a tsconfig.json file in the project’s Scripts directory was all that was needed.  However, ASP.NET MVC projects in .NET Core have a different setup.  The guidance is to create a scripts directory outside of the wwwroot directory in the project to hold the TypeScript files.  In order to get the JavaScript code that is generated from those files to be used in the deployed site you then need to copy the JavaScript, TypeScript, and Map files over to your JavaScript directory within wwwroot.  From what I have read, to do this you need to perform a few steps.  They are pretty basic and I encourage you to read the article on TypeScriptLang.org as it has more details on the steps needed.  What follows are the two files I had to play with to get the mappings working.

The first file to add to your project is tsconfig.json.  You can place the file at the root of your project or in the main folder holding your TypeScript files.  For the purposes of this post I’ll be putting the file in the root of my project.

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true, // Generate the source Map file connecting JS to TS
    "target": "es5",
    "typeRoots": [ // Point to NPM for typings
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",  // Folder to ignore
    "wwwroot" // Folder to ignore
  ],
  "include": [
    "scripts" // The folder to look for TypeScript files
  ]
}

Once this configuration file is in place any build launched will fire off the TypeScript compiler and generate the JavaScript and Map files.

The next piece of the puzzle is getting the generated files into the correct directory in the wwwroot folder of the project.  To accomplish this another file needs to be added to the project in order to use gulp.  The gulpfile.js will have a simple job, delete the old JavaScript directory and copy over the TypeScript, JavaScript, and Map files to the wwwroot directory.

gulpfile.js

var gulp = require('gulp');
var del = require('del');

var paths = {
    scripts: ['scripts/app/**/*.js', 'scripts/app/**/*.ts', 'scripts/app/**/*.map'],
};

gulp.task('clean', function () {
    return del(['wwwroot/js/**/*.js', 'wwwroot/js/**/*.map', 'wwwroot/js/**/*.ts']);
});

gulp.task('default', function () {
    gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/js'))
});

Once those files were in place the next battle was getting my project to rebuild and run any updates made while debugging the site.  I originally thought the problem resided with the IDE configuration.  Turns out this isn’t the case and what was needed were changes at the Project level and in the code.

The steps are all spelled out by Microsoft in Razor file compilation in ASP.NET Core.  To help with the code piece of the update take a look below.  In the Startup.cs file the constructor and ConfigureServices sections of code will need to be updated in a similar fashion.

Startup.cs

private IWebHostEnvironment _env { get; set; }

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
    Configuration = configuration;
    _env = env;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    IMvcBuilder builder = services.AddRazorPages();
#if DEBUG
    if (_env.IsDevelopment())
    {
        builder.AddRazorRuntimeCompilation();
    }
#endif
  ...
}

Once these changes were finally realized my project was back in a productive development state.  Visual Studio 2019 does have TypeScript compilation settings that can be set in the project Properties that could be used instead of the tsconfig.json file.  And it might be possible to not use the gulp task by having your TypeScript files within the wwwroot/js folder.   I’ve shied away from this setup for the time being since multiple articles have emphasized keeping the TypeScript code outside of wwwroot and using the tsconfig.json file makes the project more automated build friendly.