Category Archives: Microsoft

How to run StyleCop as opt-in feature with msbuild from command line

The tool :

So everyone knows wonderful tool from Microsoft, named StyleCop. StyleCop is a tool that runs against C# code (not against IL assemblies – already build code) and based on rules saved either per machine, or per project (we will show us how to save them per project) gives you feedback , if you violated some of these rules. StyleCop started on codeplex (MS take on similar portal like github) and currently moved to GitHub – https://github.com/StyleCop. If you see closely, on GitHub we have two projects :

We will go down the free path and take a look at first option. There are two plugins I will speak about today :

(please note that in StyleCop repo there is a note about recommendation to use Roslyn based StyleCop from https://github.com/DotNetAnalyzers/StyleCopAnalyzers repo)

So, you can add NuGet StyleCop.MSBuild package and now running msbuild from command line will trigger analysis. Which is what we want on CI server, but not for builds from Visual Studio. You can try to run build from VS and see what happens.

How to turn off StyleCop.MSBuild for VS builds :

After some search on the interwebz I found out, that there is a property StyleCopEnabled in StyleCop.MSBuild.Targets that is set to true if nothing is specified, which we need to set to false as default. So you need to edit your .csproj (or any other .proj file) and insert

<StyleCopEnabled>false</StyleCopEnabled>

in some PropertyGroup.

This will enable you to do following thing :

  • run msbuild to trigger just plain old build
  • run msbuild  /p:StyleCopEnabled=true to pass parameter to msbuild that will do the analysis after the build.

If you guess that the first will be “used” when building from VS and second to get analysis on your CI server, you are right 🙂

And if you questioned yourself, “why not to pass  /p:StyleCopEnabled=false” from VS build, then AFAIK from VS also in 2017 we cant just pass parameters to msbuild. Shame, I know.

How to handle async functions inside constructors in TypeScript

In this post we will discuss some options you have with calling async functions in constructor of your TypeScript classes.

So, first of all – why would you do this? Well, maybe you need some data from a web API to fill the object with data, or you need some input from user, or some API in code from a colleague is async. Reasons may vary, but the problem is still the same :
in TypeScript, you can’t have await statement in constructor, because constructor returns instance of object, not Promise<yourObjectType>. (All of this indeed is tied to current version of TypeScript 2.2. maybe in future with native async/await keywords in JS, things will change).

So, possible solutions depend on what happens in your async functions and if you need results from this call / calls at the time you return the object.

Solutions :

1. Try to avoid async stuff in constructor. As said earlier, constructor is a function, that should initiate the object in some way and return it immediately, not return a promise that has to be awaited. That is considered a bad practice and TypeScript doesn’t allow this. More on this problem here

http://stackoverflow.com/questions/11856778/asynchronous-constructor

http://stackoverflow.com/questions/24398699/is-it-bad-practice-to-have-a-constructor-function-return-a-promise

http://stackoverflow.com/questions/36363278/does-async-await-will-allow-us-to-be-used-on-constructors

So in some sense, need for async stuff in your constructor might be considered code smell, you are doing too much in constructor. Refactor your code.

2. If you want your async code to stay in constructor for some reason, do you need results from async calls? If not and you want to call them and let them just execute, you might consider calling async functions without await. In this way you will unfortunately be unable to receive (await) the result from these calls (values passed back via resolve).
Please note, that this might result in some non deterministic issues because of how JS handles async code and I really don’t recommend this. Also another downside is, that if you would wrap everything inside constructor with try, promises that would be rejected (analogy with throwing exception in async sense will be not caught but become unhandled exceptions).

Your constructor might then look like this :

class SomeClass1 {
  constructor() {
    getConfirmAsync("1 - 1");
    getConfirmAsync("1 - 2");
    getConfirmAsync("1 - 3");
  }
}

Sample with try/catch block might look like this :

class SomeClass2 {
  constructor() {
   try {
     delayAsync(3000);
     delayAsync(2000);
     delayAsync(1000);
   } catch (e) {
     console.log(e);
   }
  }
}

No awaits means that code will continue to run and your constructor will finish and hand over new instance of your class sooner than code triggered from constructor will finish its execution. Scary, right? Don’t do it!!!!

Another take on this same approach is to leave an async self executing function in constructor like this :

class SomeClass3 {
  constructor() {
    console.log("SomeClass3 - entry");
      (async () => {
        try {
          await delayAsync(3000);
          await delayAsync(1000);
          await delayAsync(2000);
        } catch (e) {
          console.log(`catch triggered with exception ${e}`);
        }
      })();
      console.log("SomeClass3 - exit");
  }
}

Again, object would return from constructor but it would still lack calls to all async functions but this time, with proper async function, await and try/catch will work. So if for some reason first function would throw, all the others will not be hit (you can try to change the first call from 3000 to 2999 and see the results). Again, this is not recommended!

3. Simple “factory” function :

This is a way you might potentially want to go because it’s the safest one. All calls will be awaited and instance of you class will be in the state it should be.
All logic from constructor would have to be removed and stored in function that will have the logic of preparing object to the right shape. But, it is OK to separate the logic of creation from class to different function/files that knows what to do to make the object “right”?
Also you might want for safety reasons to “hide” somehow the class itself to prevent from instantiation without the factory function.
This could be done by exporting (from module) only interface of the object and “factory” function and not the class itself. Downside is, that all functions that are called in “factory” function need to be also public because “factory” function is not inside the class itself, but it is a separate function.

//exporting interface so we can work with the object outside
export interface ISomeClass {
	stringPublic: string;
	numberPublic: number;
}
 
//not exported = not visible
class SomeClass implements ISomeClass {
	public stringPublic: string;
	public numberPublic: number;
 
	private somePrivateFn() {
		console.log("this is private fn");
	}
}
 
export async function createSomeClassAsync(): Promise<SomeClass> {
	let res = new SomeClass();
 
	await delayAsync(1000);
	await getConfirmAsync("1");
	await delayAsync(3000);
	await getConfirmAsync("2");
	await delayAsync(2000);
	res.numberPublic = 1;
	res.stringPublic = "aa";
	// res.somePrivateFn(); since we are not inside function this would fail
 
	return res;
}

This is TS that has export and import statements, but in my examples on GitHub I have this implemented without export and import. I can make a sample for you that is using modules (like the one above) but I decides to cut complexity for my readers and not use any bundling tool like webpack or browserify (I recommend webpack over browserify but that is just a matter of taste).
5. You want to hook a browser event inside the constructor , like some ready event or some other that will trigger some async functions once it happened.

Your constructor might look like this :

function ready(fn) {
    if (document.readyState !== "loading") {
        fn();
    } else {
        document.addEventListener("DOMContentLoaded", fn);
    }
}

class SomeClass {
    constructor() {
        console.log("SomeClass5 - entry");
        ready(async () => {
            try {
                await delayAsync(3000);
                await delayAsync(1000);
                await delayAsync(2000);
            } catch (e) {
                console.log(`catch triggered with exception ${e}`);
            }
        });
        console.log("SomeClass5 - exit");
    }
}

I am using a helper function from http://youmightnotneedjquery.com/ to avoid adding jQ to the project, but you get the point.

If my samples doesn’t make sense for you, please to to my GitHub repo, you can find all the code I made as examples can be found there : https://github.com/rostacik/asyncTsCtorSolutions .

If  you have TypeScript installed as global npm package, just type

tsc

in the root. If you dont have TypeScript installed, you just need to do to install npm packages :

npm install

and run TypeScript compiler to build all .ts files :

 "node_modules/.bin/tsc.cmd"

Feel free to ask or discuss in the comments 🙂

How to filter particular TypeScript errors in build result

Hi interwebz.
I just want to share this short poor man’s fix when migrating TypeScript to filter out some particular errors in TypeScript build.

Why the hell you (might) need it?

So what would be the common use case , why to bother mask/mute errors on build? Compile is the first test our code need to undergo, like first pass of “unit tests”.

Our situation : currently we have a lot of .js files that let’s say most of the time worked and we need to iterate on way to migrate fully from JavaScript only to TypeScript only. So we rename .js to .ts and then we ran into errors like (among others) :

  1. error TS2365 Operator ‘>=’ cannot be applied to types ‘string’ and ‘number’.
  2. error TS2365 Operator ‘==’ cannot be applied to types ‘string’ and ‘number’.
  3.  error TS2345 Argument of type ‘number’ is not assignable to parameter of type ‘string’.

Yes indeed these are against the “logic” of TypeScript – bring types to JavaScript. But I know I want it there for some short timespan. Just to test. I don’t want to wade through 1500 same errors I know I will have to fix, but among them TypeScript also tells me big and real problems, but buried under many same errors about types.

We are not alone in this, more ppl write about it here :
https://github.com/Microsoft/TypeScript/issues/6114

https://github.com/Microsoft/TypeScript/issues/4094

https://github.com/Microsoft/TypeScript/issues/9448

and also here https://github.com/Microsoft/TypeScript/issues/11051

Solution :

So the solutions vary from custom branch of TypeScript as such to stupid grep on the command line output. And since I am on Windows 10 (my dev box) , I chose to stick with PowerShell so this is snippet that should do the job.

Lets say we want to mute TS2365 and TS2345 errors and your TS build gulp task has name someTSBuildTaskName.

PS script – output to some file :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345" | Out-File "grepts.txt"

PS script – output just to console (just drop the last part after pipe) :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345"

PS: I am calling here the gulp task without gulp installed with -g flag (global) so you can just call

gulp someTSBuildTaskName

with globally installed gulp and you are also good to go.

Found any better solution? Pls let us know in comments! 🙂

AD: you can also use this console log parser on Jenkins:

Regular Expression :

([\w\\\.]+)\((\d+),\d+\):\s+\w+\s+((?!TS2365|TS2345)\w+):\s+(.*)$

Mapping Script :

import hudson.plugins.warnings.parser.Warning

String fileName = matcher.group(1)
String line = matcher.group(2)
String category = matcher.group(3)
String message = matcher.group(4)

return new Warning(fileName, Integer.parseInt(line), "TS Error", category, message);

and plug this into your build pipeline.

How to disable building of TypeScript files in Visual Studio 2015

If you would like to disable building TypeScript files in your solution for some reason (you want different build workflow, you just work on .cs files and don’t touch .ts files), you had to search for some kind of ifs or comments out to the project file in previous version of Visual Studio.

The problem as such is not new and solution was requested for some time from TypeScript team.

After digging in some articles I found this not much hyped solution :
add node

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

to the first

<PropertyGroup>

element in .csproj file.

For me, it worked.

More on the problem here :
https://github.com/Microsoft/TypeScript/issues/2326
https://github.com/Microsoft/TypeScript/issues/2294

One small note : if you have an error in the .ts files and compilation is disabled, build will not fail in Visual Studio 2015. But you can still see all errors in Error list tab. And you will still have IntelliSense.

Microsoft.Web.Infrastructure was not found while building on CI server

tl;dr story:
Just add HintPath node to Microsoft.Web.Infrastructure Reference node that points to where NuGet package is.

The full story:
I just would like to share with you problem I ran into. Basically we have a ASP.NET project that I updated with some NuGet packages. One of these packages installed as dependency Microsoft.Web.Infrastructure library. As usually, everything worked on my machine (dev box with VS 2013 and all other goods).

But the build failed on our CI server. With error like this (since we run German language mutation of Windows server, msbuild.exe was also in German) :
console build error

So, I checked if the package is installed correctly and it was :

mswebinfa package installed

Folder in packages subfolder was present :

mswebinfa subfolder in packages

I looked where the reference is pointing to and it was strange :

mswebinfa wrong path

it should point to packages folder like this :

antlr path in packages

OK, time to check the .csproj file.

Antlr reference looked like this :

antlr csproj reference

however Microsoft.Web.Infrastructure entry was missing the HintPath node, so I fixed it like this :

infrastructure fixed csproj reference

and after loading full solution, stuff started to work again :

mswebinfa correct path

and here we can see happy msbuild.exe in its natural habitat :

console build happy

Hope this helps.

BTW similar (but different) problem was solved here : http://stackoverflow.com/questions/13149851/could-not-load-file-or-assembly-microsoft-web-infrastructure

How to force types in Array with TypeScript’s union types

From TypeScript 1.4 we can do nice stuff with types now, with help of feature called Union Types : https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#union-types which will let you do also this sweet stuff :

ts union types

You can see this in action on this link :

http://www.typescriptlang.org/Playground

Sample snippet here :

module ArrPlayground {
    export function fn() {
        var arr: Array<boolean|string> = [];
        arr[0] = "aaa";
        arr[1] = false;
        arr[2] = 987;

        return arr;
    }
}

Basically you can now limit types that could be used in Array (all only at compile time, same rules apply as for other type checking features of TypeScript).

Enjoy.

Adding .JS file generated by TypeScript in Visual Studio 2013 to markup

Note to self :

If you want to add .js file generated by TypeScript from .ts file under Visual Studio 2013, you don’t need to click Show All Files, than search for file you wanted to add and then disable Show All Files (because by default, .js and map files are not part of project). You can just drag and drop .ts file to .html or .aspx markup and Visual Studio 2013 is intelligent enough to include .js file. Fast, simple, obvious. Not for all however 🙂 .

How to convince Internet Explorer to show more pages with untrusted cerificates in one tab (iframed)

Funny article name you say and I can only agree, yes 🙂 most of the time you run like hell when you see page with broken certificate. But I will explain why one might need this 🙂

My girlfriend is a tester and at her current work she is testing web apps. Since majority of these apps use SSL and she is using staging versions, she has to accept certificate errors and if you know what you are doing, than everything is OK and fine (you see errors because of self signed certificates).

Yes there are more ways how to get over this problem :

but if you don’t want to do this/you cant do this on your box then you just have to live with basic temporary exception and you will click Continue to this website :

ie certificate error

And now comes the problem part/our edge case. Most of the time you are accessing one URL on one server and everything works.

But lets say you have your testing URL with self signed certificate where is a page with IFRAME to different URL with different certificate on different server. Now what? You have to add two different exceptions.

The problem lies in how IE (tested in IE11) displays another page. You just don’t have any option how to add another exception, you just see that the iframed page has invalid certificate, nothing more…

The FireFox solution :

The FireFox way is more common and most of people know it (so just small recap):

you can open new tab with IFRAMEd URL, access it, see error and add permission. Than on another tab access hosting page, add second exception and you are done, all of the later visits to hosting page share the same exception. Which is nice, because you can close the tab and open different one later and you don’t need to add exception to IFRAMEd URL over and over again.

The IE (I suppose because of the architecture – more on this here – http://blogs.msdn.com/b/ie/archive/2008/03/11/ie8-and-loosely-coupled-ie-lcie.aspx ) behaves little bit differently.

The IE solution :

In IE the exception for IFRAMEd page isn’t shared between tabs/shared for whole browser instance so you have to :

  1. Access the IFRAMED URL and add exception and then on the very same tab
  2. Access the hoster URL and add second exception

and everything should work now also for IE the way expected 🙂 but once you close the tab with exceptions, you have to do the same thing again…

Decision which way is better/safer is up to you….

Hope this helps 🙂 Tested on latest versions of Windows 7 + IE11.

JavaScript Visual Studio snippet for is object defined check

Since I write a lot of JavaScript currently in Visual Studio these days, I lack one of the very common checks in JavaScript and that is testing if object exists.

I mean this check :

if (typeof (someObject) !== 'undefined') {

someJSCodeHere();

}

If you want to use this code but not type it each time over and over again and speed your work up you probably thought a snippet that would save your keystrokes would come handy, but there is none in vanilla VS. So, you can use my snippet ,just import it to Visual Studio from Code Snippet Manager window (in VS 2013 – CTRL + K + B) and use it with typing def and then tab (or use CTRL + K + X and pick one).

Enjoy your speedup while working with JavaScript.

PS : do you know you can share snippets with your team mates?

http://blogs.msdn.com/b/zainnab/archive/2010/08/19/sharing-snippets-with-your-team-vstiptool0075.aspx

http://blogs.msdn.com/b/saraford/archive/2007/12/14/did-you-know-how-to-share-code-snippets-with-your-team.aspx

PS2: If you want to edit snippets in you VS, this plugin might be a good idea : http://snippetdesigner.codeplex.com/

How to drop VS2013 Browser Link requests from you Fiddler debugging session – filter for specified host name and port

The short story:

Filter out only hosts and ports you need. Apply the filter, enjoy.

Complete story with more help:

Visual Studio 2013 gave us awesome thing, Browser Link – http://blogs.msdn.com/b/webdev/archive/2013/06/28/browser-link-feature-in-visual-studio-preview-2013.aspx , but essentially, what is happening is, it’s using SignalR to inject some JS to let VS 2013 communicate with browsers. So it can happen, that you are debugging something on the localhost and suddenly you see something like this :

browser link

How to filter this noise away? First thing I was using process filter :

fiddler process filter

but this will only filter out process, so you will see only IE (in this case, or anything you choose), but how about filtering only domain? It’s in another place, but it’s there, just hidden a bit :

fiddler filters

Here you can filter more, than you need to click on the Actions button and Run Filterset now, this will apply filters to what you already have + all future events.

And the last part of puzzle is, you need to filter for (this applies only for me in this particular case), localhost:80 , because to filter only for localhost would yield also all requests to all localhost ports, what we dont need.

Another option could also be to : ban particular host:port , depends on your needs 🙂

Hope this helps,

Dušan