Category Archives: How to

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

How to “grep” for multiple strings in files on Windows with PowerShell

So you want to search for multiple strings in your files on Windows?

Sure, you can do the job several ways, but if you have PowerShell installed on your box, you might use this snippet :

get-childitem "folder_where_to_look" -include *.txt -rec | where { $_ | Select-String -Pattern 'find_me_1' } | where { $_ | Select-String -Pattern 'find_me_2' }

Basically what this snippet does this :

  • find all .txt files in supplied folder and recursively in all subfolders, pass this list to
  • first pattern search for “find_me_1 string, than pass list of matching files with this string to
  • second pattern search
  • pass result to console

Nice this is, that you can also use RegEx in patterns that will be searched for and you can also dump found files to file for later use.

Hope this helps someone.

window.showModalDialog behaves differently on IE, FireFox and on Chrome

I would like to share one small “feature” I have found on current latest browsers. By “latest browsers” I mean (I tested this behavior on IE 11, FireFox 29 and Chrome 37).

The problem:
If say for whatever reason you are using JavaScript modal dialogs with

window.showModalDialog()

like in older web app (chrome and firefox displays waring you should use

window.open()

instead, more on this here : http://stackoverflow.com/questions/20733962/why-is-window-showmodaldialog-deprecated-what-to-use-instead ) and you are passing in multiple same arguments (for whatever reason, maybe you had default values + new values as params and previously IE took second parameter, that is the mystery of legacy code and I don’t suppose majority of you will do this, but it might happen), than you will have problem on FireFox.

So given JavaScript call like this

window.showModalDialog('HtmlPage1.html', null, 'resizable:0;status:0;dialogwidth:900px;dialogheight:200px;dialogwidth:100px;dialogheight:300px');

the following will happen :

no Error will be thrown, IE and Chrome will use second pair of dialogwidth and dialogheight, FireFox will use first one and all of these popups will be styled using these values so the same code will result in different UX.

Small side note though, Chrome will make dialog really 100px and IE will hit some internal min value I suppose and Chrome’s window will not be modal (you can click away) but  everywhere the window will be opened.

Hope this might save you some time in case you run into the same problem.

How to setup post build event in Visual Studio to combine multiple TypeScript files to one JavaScript file

Hi interwebz and TypeScript users.

Just wanted to share this small idea/snippet I found on the web (the main reason to write this post was to let you skip my errors so you don’t have to find what to suffix after $(SolutionDir) and let tsc be happy with what VS is calling).

For example here : http://stackoverflow.com/questions/12926830/typescript-compiling-as-a-single-js-file

So, if you are using TypeScript and if you are wondering : “maybe I could stitch my 2-3-4 files together, that are used together in one .js file” , well that is of course possible.

Like this :

Make a post-build event, for each combined file you need to make one separate entry like this (with some sample project name and folder name here) :

tsc –out “$(SolutionDir)WebApplication1\TypeScript\Merged\two.js” “$(SolutionDir)WebApplication1\TypeScript\file1.ts” “$(SolutionDir)WebApplication1\TypeScript\file2.ts” –removeComments

Side note : Without specifying whole folder also after –out, tsc will output the combined file to bin, which is something you don’t want I presume.

And yes, you will also see errors if they happen in VS output window.

Another and maybe better take/steps would be to minify this combined .js or use Bundling and Minification built into .NET, but this is just another no code approach/tweak.

Enjoy….

AD:

I forgot to tell you about thing TypeScript added in later releases and that is , you can merge all JavaScript code to a single file in project properties here :

combined typescript js

However, I was not able to find any way to fine tweak and bind specific .ts files together so you can choose what you want in your project maybe event without any post build event. The path where VS stores the combined file is from the root of the project.

AD2: If you are using features from EcmaScript 5 in your TypeScript, than you need to pass also -t “ES5” parameter to the tsc, because otherwise build will fail. Small side note here, that ‘ES5’ doesn’t work, as they claim in help in the command line from tsc.exe itself.

AD3: You also should not forget to remove comments with –removeComments , since I presume you need this approach to minimize file size.

AD4: If you are extending some class in one of your file, you have to include this .ts file in the input files as well. (You will get exception that compiler cant find symbol – the class you inherit from, so you will know 🙂 )

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

How to reset your Kindle, if you have download stuck

I am happy owner of older Kindle Keyboard (without 3G, it should be 3rd generation of Kindle readers).  Since I have version without 3G, I am downloading everything via WiFi at home. I often read articles from our local web magazines or development articles with help of this tool : Kindle It, really good Firefox plugin.

A week ago I accidentally downloaded (well it looks like that) the same article 2 times, or maybe this isn’t the case here, but anyway one article was stuck in a way that is was still in the queue for download, with 100% completed, but it was still there in View Downloading Items menu. Hmm, now what? I found one forum with someone with same problem, the advice was to resend same thing. But the article was gone from our local news page, or it changed name but I wasn’t able to find it. 🙁 I also investigated on Amazon’s My Kindle page, nothing. The article was gone from queue (no pending articles), it looked like problem of my device. I also checked the firmware version, I have the latest… Then I found this post :

http://www.kuforum.co.uk/kindleusersforum/thread-1682.html

And this was the solution :

I had the same problem but I already had the latest software so couldn’t update. Went into menu from the home screen, clicked settings, menu again, clicked restart. Kindle went through a complete restart, loaded up, problem solved.

Thank you Jen , didn’t knew that there is this submenu. 🙂

My device rebooted, it looked like reboot after firmware update (with child reading under tree and progress bar, it took something about 30s+-), then Kindle started with clean list of books but don’t worry, it will load them all in few seconds 🙂 just wait and you will see, but the orientation was gone and maybe some other small settings that I just didn’t realized yet.

My problem is gone and hopefully yours will be too 🙂 . If you have any other way of solving this problem, please share in comments. Thank you dear reader.

Painless and easy way to JSON endpoint in Sitecore aka your own API for Sitecore in few easy steps

Welcome dear reader.

In this article I want to dive a bit into helping you decide (or at least share some thoughts) regarding quite common problem that we had on last Sitecore project and that was : there was a need to have some sort of API (yes, I am under influence of ASP.NET MVC WEB API 🙂 and I like it) or some kind of endpoint that we could access from browser (or perhaps some device in future) and use it to query data, best nicely packaged as JSON objects, ready to use. Not that big deal you say, Sitecore is WebForms ASP.NET app, we have support for exposing JSON, it is possible. Yes it is and we do have the support. But we can have a bit trouble with fact, we are using Sitecore (since it is a platform, with many things added in web.config file, etc.) and if you are lazy as me.

Sitecore from version 6.6 (as described here) supports MVC (at last) and this can help us, but I was in a situation when we didn’t decided to use MVC so introducing this change for just one thing (my API) only would be overkill and too much work. So I searched a bit and I found out that the best solution for me would be a dedicated Web Service .asmx file (oh my, I took part on bigger MVC project before and going back to files from MVC point of view just doesn’t seems right).

But there are more options, why this asmx way. Let me elaborate more on them, but please first read this GREAT article about same problem but from ASP.NET point of view :

http://johnnycode.com/2012/07/16/getting-json-from-asp-net-beautiful-good-bad-ugly/

Done with the article?

Good, so here are my thoughts :

  • Web API would be the best solution here, if you look at how the code clean is and with fact in my mind – it is built for this very thing you need right now, but sry, no MVC this time, so there also goes my evil plan for dedicated MVC controller, well… But I would advice you go this way, it has its benefits,
  • Dedicated handler? Would work, but too much low level work (setting content type??? in 2013?? now come on),
  • Static method on some dedicated page (it works, I used this approach as a “service API” for one big Web Form but that was 3y back) would also do the work, but its really not elegant and since Sitecore has something like a routing (you don’t really access files in their physical folders, but traverse the logical tree in DB more or less), I had feeling it is not the right solution to my problem,
  • So here we are with my dedicated Web Service , some .asmx file that would do the job. IMO this was just what I needed, adding one dedicated file as a endpoint we can call will not ruin anything (ehm, there will be more files as I will show you later), we have support to just return something that will ASP.NET runtime serialize to JSON without much work (I will show you some tweaks I found on the web to optimize load and more), perfect fit for my needs.

Sitecore Item Web API 1.0.0

I have to interrupt this story to make it more complete here. Before I investigated how to send some items down the drain as JSON I had a talk with guys from Sitecore about what to use, they also said that there is one thing I could use besides Web API and that is their own product : Sitecore Item Web API, that was and still is in version 1.0.0 with date 28.08.2012. This is a good thing but has it’s weaknesses (but maybe it was just me, although I have studied also documentation but maybe you can prove me wrong and this tool is what I needed) and strengths. More on them here :

  • You can (and should) use Advanced Security where you explicitly have to tell what fields you are exposing and then either query particular ones or don’t specify any and you should get all,
  • I wasn’t able to specify what branches of my Sitecore can I query so I was able to query everything. Also system parts of it. This I really regard as a security issue (or it was just me and my mistake with setting things up),
  • Not needed data were sent down the wire like ID of record, whether is has children, what database I am accessing and more. Stuff that just wasn’t needed and again was a security issue (from my point of view),
  • Desired properties were stuffed to one property of item and if property had space in the name, I had to use this approach : http://stackoverflow.com/questions/4042646/how-to-access-json-object-which-has-space-in-its-name,
  • Regarding using dedicated account with own name and pwd, that might me the way for some “hidden” app that would need API access via web, but if I would write JS code in some lib and use it, that would be the first thing where I would look if I would like to try to hack my app,
  • The final thing I had problem with was XPath query with some parameter that I had to URL encode to get it work and it worked, but then suddenly a business requirement came that would need me to query API, assemble some information, do something with it and re-query for final results. But this is business logic that isn’t supposed to be on the client (another example could be some simple JS validation logic that would make sense, but not this type + one more HTTP request = more possible delays, more hits to DB…. that just wasn’t good)

I just wasn’t fully in the control of this thing. So I decided to investigate on possibility that give enable me full control of what I send down the wire. And encapsulate some business logic that could be reused somewhere else, in code behind, etc… Client doesn’t and should have to know about relationships between objects, how I can get what from this and that. APIs are the encapsulation of some business logic, in this particular case exposing it to HTTP access via Web Service. Or at least this is my understanding of how things should work.

OK now some good advices I learned while working on the project, these are more or less generic to ASP.NET as such.

JS code

JS code could look like this :


$('#value-button').click(function () {
$.ajax({
type: 'POST',
url: '/Service/Service/CustomAPI.asmx/ComputeMeValue',
data: '{ "value" : "' + $('#value-input').val() + '" }',
//data: JSON.stringify(data), - use this if you have custom json object with properties...
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#outcome-paragraph').text(data.d);
},
error: function (data) {
alert("something bad happened, we are sorry...");
}
});
});

This is a small snippet from sample project I will post with this article.

I would advice you to have also error part in the JS code so once your code throws some exception, user will be notified.

If you are not posting parameters, you should still send empty {} in JS code, or send values you want on the server. Names and types have to match obviously.

Web Service code

At first, there are more approaches here. You can layer/separate you code in own project if it gets big, but for my small API I was able to get away with subdirectory for Model, where I stored POCO classes (in MVC project this could go to separate Class Library) and with separate subdirectory for service as such.

The service could be divided to

  • BLL layer that could store business logic (how to combine objects, how to create VMs – view models, what to query for what),
  • Mapping between domain objects (object we have from Sitecore API, or EF or some ORM mapper in case of MVC) and VMs we have in Model subdirectory (this could be in BLL or as separate library, or in MVC in the model project, if you don’t have BLL project),
  • MVs – View Model classes in Model subdirectory.

We could also use DI – dependency injection as we do in MVC but all this and above really depends on, if it makes sense for you or not, if it helps you or its overkill on smaller project. If you will/need unit test or not. Your project, your rules. (but unit tests are good, for you :))

Small tweaks to the code (the price to pay for Web Service .asmx approach)

Declare the type of what you return as object (I found out this on the web after few hours of pain with dynamic, that I was used to from MVC….). This has some nice side effects. First of all you can return either string, or int if something goes wrong with the query and there is nothing to send back, if you have some data to send, then just send List<User> for example. Neat thing to save bandwidth is that you can send down objects of say User and SuperUser and AdminUser that can be extended with some new additional properties and these will be just on the items that have them. You have to declare the object that will be stuffed with these different objects as List<object> and then you can add to it what you want/need. After you are finished, just return it. But you have to deal with this (different types of objects) in your JS code of course. The last thing why I would advice you to use object as return type is, that plumbing in .asmx file will send down in JSON for each object also its type, like this :

web service json sample

Just by declaring return type as object, with the very same code you will have this response :

web service json sample with object return type

Magical, right? The best time to switch to ASP.NET MVC 🙂

Another thing I wasn’t able to make work was something like ASP.NET MVC model binding. MVC has nice functionality that will turn parameters from cookies, query string, posted values, all to one object that action on controller has as parameter (matching names of values and properties on object). So you don’t end up with 30 parameters per one action. Here you have to use older approach with no binding, I am sorry.

OK so hopefully I have not forgot something, if you have any questions, just write to the comments, and here is the promissed link to small sample page for download : http://sdrv.ms/WZmVq5 enjoy.