Category Archives: ASP.NET

How to exclude some files from TypeScript build

If you are using TypeScript nightly (and only with TypeScript 1.6 up) you can use in your tsconfig.json new property exclude which will mostly be used for node_modules like this

(more on this here : http://blogs.msdn.com/b/typescript/archive/2015/07/27/introducing-typescript-nightlies.aspx)

:

{
   "compilerOptions": {
   "out": "../../built/local/tsc.js",
   "sourceMap": true
   },
   "exclude": [
      "node_modules"
   ]
}

More on exclude property here : https://github.com/Microsoft/TypeScript/issues/3043

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

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

How to subscribe to document.ready event from multiple TypeScript files

What I needed :

I needed to subscribe from multiple TypeScript files to ready event of document, the usual event where you hook to do some initializations with jQuery, when you need it. There are more ways, to do this.

  • You can handle the ready event on the “host” page and do what you need to do there,
  • You can, if you know you are the only one just inject your anonymous function to say window.onload but there is a problem, that the last pointer wins and you can have only one function there, just try this in you page :
    <script>
             window.onload = function() {
                 console.log('1');
             };
             window.onload = function () {
                 console.log('2');
             };
    </script>
    

    There will be only one line in console, with 2.

  • Somehow subscribe to the ready event and call all pointers no matter who subscribed and will subscribe in the host page.

First of all there are some things to clarify :

How to do it :

Since TypeScript is in fact JavaScript (its superset of JavaScript), you can use it without TS (btw I don’t use any feature from TS, maybe we could change

$(document).ready(function () {
         console.log('ts 2');
});

to :

$(document).ready(() => {
         console.log('ts 1');
});

But whatever 🙂

The key is to :

  • use jQuery in your project,
  • use everywhere $(document).ready since it will subscribe your code to the jQuery ready event and essentially chain them it the order as browser parsed the .js files,
  • include jquery.d.ts definition for TypeScript to be happy (part from DefinitelyTyped project)

The snippet of subscription code can be placed after module and class definitions in each .ts file so you can do what you need. TypeScript will just copy this JS to the resulting .js file.

In case of any questions, something interesting, another take on the same problem > please share in comments, thank you.

Download link : sample app

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.

How to hook to client keyboard events with Telerik’s DropDownList

So, you have same problem as me, how to subscribe to clients keyboard events with Telerik’s DropDownList control for ASP.NET MVC? 🙂

Unfortunatelly, there is no out of box event for this yet, but it’s not that hard, we just need some jQuery magic.

This is the code :


$('#id-of-your-combobox').parent().keydown(function (e) {
alert('Handler for .keydown() called.');
});

Please be aware, that if you are using combo box in Grid (in Telerik’s MVC Grid, like I do), then you need to execute this code in OnEdit event handler, since combo box object exists only when some row is in edit state.

If you have any questions, feel free to ask.

Hope this helps, at least to save you some time.