Display AngularJs ng-template directly

Possibly save 1 hour of your time: There may be times when you want to display an Angular template directly. You can use ng-include and single quote around the path to the file:

<div ng-include src="'views/sidepanel.html'" ng-controller="SomeController"></div>

You can also specify the controller using ng-controller.

Book: AngularJS: Up and Running: Enhanced Productivity with Structured Web Apps

Advertisements

Understanding Razor Views

Possibly save 1 hour of your time: The following are some code tips on what you can do on a razor view. Razor view has a .cshtml file extension.

The following shows the use of no Layout (similar to master page concept). If you didn’t set Layout to empty, it will default to use Views/Shared/_Layout.cshtml. You can use ViewBag to pass data between controller and view.

@{
ViewBag.Title = "Map";
Layout = "";
}

The following shows how you can include a Javascript and CSS reference in the element.

@section head {
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.41.0/mapbox-gl.js'></script>
		<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.41.0/mapbox-gl.css' rel='stylesheet' />
}

Book: Instant Razor View Engine How-to

SQL Server import wizard treat blank as null instead of zero 0

Possibly save 1 hour of your time: There are times when you need to import csv file with a nullable integer column. However, when you use the SQL Server database >> Task >> Import wizard, you will notice the result shows integer 0 instead of null values when the import csv file shows blank.

There is no feature on this wizard to treat blanks as nulls. The alternative is to use SQL Server Integration Service (SSIS).

But you can do it via an SSIS package to do ETL on the data from the CSV file into a SQL Server database.

You can use Data Flow Task. Inside the Data Flow Task, you can have a Flat File Source and an OLE DB Destination.

import csv to database.png

Click on OLD DB Destination, and there is option to Keep nulls.

OLE DB Destination - keep nulls

If you don’t know SSIS, you can always use the import data feature. In the last step, there is an option to Save SSIS Package and choose File System and the next screen will ask where you want to save. After you saved, then you can load that into a SQL Server Integration Services project.

save ssis package

Book:Professional Microsoft SQL Server 2012 Integration Services

Visual Studio database project schema compare (.scmp) show delete all objects

Possibly save 1 hour of your time: If you are using schema compare in your database solution project within Visual Studio, the initial compare shows nothing on the project vs  your target database. It tells you the difference is to delete all objects such as tables and stored procedures.

The problem was that the scripts (.sql) files are added to the folder outside of Visual Studio. You need to right click on the folder and choose Add >> New Item. Then you can select under each SQL Server menu sub category and the SQL object.

sqlobject.png

Book Microsoft SQL Server 2016: A Beginner’s Guide, Sixth Edition

Sql Server database project template missing in Visual Studio

Possibly save 1 hour of your time: There is a good way to manage your database objects. You can create a solution project for your database as follows.

In Visual Studio, go to File >> New >> Project. You should see the template under Installed >> Templates >> Other Languages >> SQL Server >> SQL Server Database Project.

database project

If you cannot see the above template in Visual Studio 2015, then you need to get SSDT as follows.

Open Visual Studio (mine is 2015) >> choose Tools >> Extensions. Update Updates >> Product updates >> you may find the Microsoft SQL Server Data Tools (SSDT) update that contains the database project template. Select it and Update.

tools and extensions.png

You can see it is installing Microsoft SQL Server Data Tools v14.0.61707.300.

data tools.png

Alternatively, you can also download the tools from

https://msdn.microsoft.com/en-us/mt186501

Book: Microsoft SQL Server 2016: A Beginner’s Guide, Sixth Edition

Consume asmx API web service c#

Possibly save 4 hours of your time: There are projects where you will be consuming external data source through an API they provide. The API could be .asmx web service.

  1. Right click the project in Solution Explorer and choose Add Service Reference.

Add Service Reference.png

2. Click on Advanced at the bottom.

3. Then click on Web Reference to generate access code.

4. Next enter the URL to the external web service. Then click on the arrow icon to find the web service. Then click Add Reference.

add web service

5. Note that the Web References folder is created with the web service code.

6. Here is an example of code calling the web service:

</pre>
ExportTool.Web.org.un.data.NSIStdV20Service service = new ExportTool.Web.org.un.data.NSIStdV20Service();

var xmlData = service.GetCompactData(xmlNode);

Assert.That(xmlData, Is.Not.Null);
<pre>

Book .NET Web Services: Architecture and Implementation

Cannot write XML declaration. WriteStartDocument method has already written it.

Possibly save 1 hour of your time: I was calling an api service that returns xml. I have to pass in a xmlNode element. For some reason, I get the error:

Cannot write XML declaration. WriteStartDocument method has already written it.

Solution: pass in DocumentElement instead of FirstChild

var doc = new XmlDocument();

doc.LoadXml(queryMsg);
var xmlNode = doc.DocumentElement; // instead of doc.FirstChild

ExportTool.Web.org.un.data.NSIStdV20Service service = new ExportTool.Web.org.un.data.NSIStdV20Service();

var xmlData = service.GetCompactData(xmlNode);

Book XML in a Nutshell, Third Edition

Resharper nunit unit test – Could not find a part of the path

Possibly save 1 hour of your time: There are times when your unit test depends on input file. To access the file when using nunit 3.8.1, you can use TestContext.CurrentContext.TestDirectory.

[Test]
public void LoadFileInUnitTestProject()
{
var doc = new XmlDocument();

doc.Load(TestContext.CurrentContext.TestDirectory + "\\Services\\CountryProfile\\population.query.xml");

Assert.That(doc, Is.Not.Null);

}

Book ReSharper Essentials

Using Ninject for dependency injection

Possibly save 4 hours of your time: If you follow best practice, you may already know about dependency injection. It has many benefits but I won’t talk about it here. You can wikipedia it. I often build ASP.NET MVC and WebAPI applications and in the controller you may create different helper or service class to get your model. Instead of new ‘ing a class, you can create your controller constructor to take in those helper or service class as parameters. Then you can access it directly to retrieve your model. A big benefit is the ability to write unit tests for your controller layer only and mock the helper or service class.

In the example below the controller gets injected an instance of yourService at runtime by Ninject. There are different scopes. By default, it is in Transient scope and it means a new instance is always created. You can read more on different type of scopes here.

Example of api controller:


namespace YourProject.Web.Controllers
{
 [RoutePrefix("api")]
 public class SomeNameController : ApiController
 {
 private readonly IYourService yourService;
 public SomeNameController(IYourService yourService)
 {
 this.yourService = yourService;
 }

 [Route("getproduct/{productId}")]
 [HttpGet]
 public SomeViewModel Get(string productId)
 {
 try
 {
 var model = new SomeViewModel();
 model.Values = yourService.GetValues();
 return model;
 }
 catch (Exception ex)
 {

throw new HttpException(500, ex.Message);
 }
 }
 }

}

I will now talk about how to set up Ninject. Open your web solution. I installed the following from Visual Studio >> Tools >> NuGet Package Manager >> Manage NuGet Packages for solution:

  • Ninject (3.3.3)
  • Ninject.MVC5 (3.3.0)
  • Ninject.Web.Common (3.3.0)
  • Ninject.Web.WebApi (3.3.0)
  • WebActivatorEx (2.2.0)

 

Second, you need to add this static class for NinjectWebCommon.cs.


using System;
using Ninject;
using Ninject.Web.WebApi;
using Ninject.Web.Common;
using System.Web.Http;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourProjectName.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourProjectName.Web.App_Start.NinjectWebCommon), "Stop")]

namespace YourProjectName.Web.App_Start
{
 public static class NinjectWebCommon
 {
 private static readonly Bootstrapper bootstrapper = new Bootstrapper();

/// <summary>
/// Starts the application
/// </summary>
 public static void Start()
 {
 bootstrapper.Initialize(CreateKernel);
 }

/// <summary>
/// Stops the application.
/// </summary>
 public static void Stop()
 {
 bootstrapper.ShutDown();
 }

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
 private static IKernel CreateKernel()
 {
 var kernel = new StandardKernel();
 try
 {
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);

RegisterServices(kernel);

// Install our Ninject-based IDependencyResolver into the Web API config
 GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

return kernel;
 }
 catch
 {
 kernel.Dispose();
 throw;
 }
 }

 /// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
 private static void RegisterServices(IKernel kernel)
 {
kernel.Bind<IYourService>().To<YourService>();
 }
 }
}

When running the app I got the following error. This means your Ninject is not setup properly.

Error: 

An error occurred when trying to create a controller of type YourTypeName. Make sure that the controller has a parameterless public constructor.

Type ‘YourTypeName’ does not have a default constructor

Mastering Ninject for Dependency Injection