Category Archives: VS 2013

How to get type of object in TypeScript, when using union types and type guards for multiple types of function parameter or variable

tl;dr

When checking for primitive types in TypeScript , typeof variable === “string” or typeof variable === “number” should do the job.

When checking for HTMLElement or HTMLDivElement type of objects, variable instanceof HTMLElement or variable instanceof HTMLDivElement type of check should be the right one.

Please note that this is somewhat simplified point of view. I was only using simple objects and elements from one page. If you will run into some specialties, please read this article : http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ and write as much unit tests as possible for you scenario. There might be some scenario where using typeof and instanceof are simple not enough.

The whole story :

My beloved TypeScript 1.4 we got a while back came with a new lovely possibility of having parameters passed as object that might be of several different types. For example you can accept either string or array of strings, where if passed a plain string, you can split it and continue with array of strings or use directly passed array.

We can argue if this is a good and clean solution from architectural point of view, but if for whatever reason this will be a requirement how the function should work, than we can leverage two sweet features of TypeScript :

Both might be used also separately or with some plain var in your code (you can just define var that will be of types string | HTMLElement | number) but if used together, Type Guards are building on top of Union Types feature and giving you some sweet stuff.

So what you get is, that TypeScript now understands what are you doing, when you check for one of types that variable might be of and you can get IntelliSense for that type (I am little fast forwarding here to the function I want to show you but this is what I mean by that) :

param check intellisense

And here I am getting to the main point of this particle and that is : how can we check for HTML elements of any other object from the DOM world?

As you all know, getting the basic types in JavaScript if quite difficult if you run into edge cases or the type you check for might be also array or stuff like that. You can read great article like this one : http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript. There are many caveats. 🙁

typeof will do, for the most part :

But most of the time, for basic types we are OK with using typeof operator and comparing against “string” or “number” but what about HTMLElement or HTMLDivElement object in TypeScript? Do the exist in the vast and wild JavaScript world? Yes the do exist, but dependent on the browser age with different results. Another misleading thing is that unfortunately the typeof operator will not work we want for HTMLElement and similar types of objects, but neither will the approach create an error, because every time we would get string “object” which is OK from inheritance point of view but its not what we need.

instanceof to the rescue :

What will work here is instanceof operator.  Nice article also here : http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for. Again, there are some caveats here (like this http://stackoverflow.com/questions/472418/why-is-4-not-an-instance-of-number) when used with primitive types like string, so I advice you to stick with instanceof for instances of objects or for checking of types from the DOM side of the world.

The snippet :

And here it is ladies and gentleman, the glamorous sample snippet I wanted to share with you (for testing purposes):

export function parCheckDemo(param: string | number | HTMLElement | HTMLImageElement | HTMLDivElement): void {
    if (param instanceof HTMLDivElement) {
        console.log('HTMLDivElement');
    } else if (param instanceof HTMLImageElement) {
        console.log('HTMLImageElement');
    } else if (param instanceof HTMLElement) {
        console.log('HTMLElement');
    } else if (typeof param === "string") {
        console.log('string');
    } else if (typeof param === "number") {
        console.log('number');
    } else {
        console.log("You're not supposed to be here! - Levelord");
    }
}

Hope this helps dear reader, enjoy. If you have any suggestions to the code, please feel free to share in the comments.

PS: yes, in real life I (and you too) should probably first check if anyone passed something as param argument , this snippet is jut for demo purposes.

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

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 🙂 .

PowerShell Tools for Visual Studio 2013 – unable to run and/or debug PowerShell script – execution policies problem

The problem :

Some time ago I wrote this article :

http://rostacik.net/2013/11/13/powershell-tools-for-visual-studio-2012-problem-ps1-cannot-be-loaded-because-running-scripts-is-disabled-on-this-system-for-more-information-see-about_execution_policies

about my problems running and debugging PowerShell scripts in VS 2012 with help of http://visualstudiogallery.msdn.microsoft.com/e3f9d3bf-e630-4b3e-968a-f86ac67b836c – PowerShell Tools for Visual Studio 2012 – wonderful tool by Adam Driscoll.

Currently after switching to Windows 8.1 + VS 2013 I reopened my project and started to work with new version of PowerShell Tools for Visual Studio 2013 – http://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597

And  I was shocked! The very same problem got even worse! I wasn’t able to fix this with steps in the article. I was able to edit scripts in VS but still, I wasn’t able to debug my stuff. After some messing with other stuff I found out, that the very same problem was here some time ago and is already fixed by another people – with help of this link : http://davidfrette.wordpress.com/2011/01/20/creating-powershell-pre-build-and-post-build-events-for-visual-studio-projects/ (yes, it was the same back then in 2011)….

Solution to the problem is quite simple :

PowerShell installs in one package however there are two versions : x86 and x64 (as separate executables that I had to find on my drive) and as you might guessed correctly : they don’t share the same Get-ExecutionPolicy setting!

So you need to :

  • Find x64 version of PowerShell
  • set ExecutionPolicy

On my machine while running VS2013 as 32b executable :

vs 2013 32b

And with the starting position like this (please note that there is no difference in title bars, you only can tell what PS you are using by the path):

ps two versions

 

I Set-ExecutionPolicy to RemoteSigned like this :

ps two versions 64 fixed

 

and the output in VS 2013 changed from this :

vs ps error

 

to this :

vs ps fixed

 

No PowerShell package on my box in add/remove programs :

I have to state 1 small thing at the end, I didn’t installed PowerShell on my box as a downloaded .exe file.  If I search my installed programs, I see this (nothing) :

ps uninstall

 

While I can see PowerShell 2.0 in add/remove feature in Windows 8.1 like this :

ps feature

So your box setup may vary. If so, please comment below for others… Thank you! 🙂

Hope this helps/saves you some time….

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 build Visual Studio solution even if some of TypeScript files are not compiling

The problem :

If you are working on some ASP.NET project and you need to build it even if some files are unbuildable/will not compile (currently I apply this on TypeScript files but this solution is general) , because you for example need to change some other functionality and than continue with TypeScript work than you have a problem.  VS stops building the app and you will have only Yellow Screen Of The Death note with “Parser Error” and “Could not load type – your project name” which I suppose is caused by not generating the assembly.

So, the solutions are (among others) :

  • Exclude erroneous .ts file (which will make it not compile),
  • Say to build system to not compile particular file with something different.

The solution :

It really is simple : just set Build Action from TypeScriptCompile to None and you are done.

ts-build-actions

The strange thing is, that my Visual Studio 2013 will anyway say I have errors, but the build process is not stopped and I am able to run the app.

If you have any other solutions than feel free to post them in the comments. Thanks in advance.

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