Category Archives: Microsoft

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

Internet Explorer 11 isn’t displaying all .htc files in JavaScript debugger part

Since I upgraded my Windows 7 developer box with Internet Explorer 11 I am very satisfied with how Microsoft upgraded developer tools. They have added new stuff and it works (well from time to time IE freezes but that might be also my problem with my JavaScript since other browsers hang/crash from time to time on my code also). But that is another story.

Today I came across small “feature” that took me few minutes to realize, what is happening.

I am using IE 11 to debug older ASP.NET WebForms app (with older I mean we are just now moving away from HTC files – Microsoft specific stuff).

IE is loading page from my local IIS with x-ua-compatible flag like described on the link provided, setting rendering core to use version 8 so behaving like IE8.

Loading my page like this results to loading just some .htc files referenced. If I set breakpoint to some code in .htc file, it will be not hit, even some objects are declared as undefined but strangely executing any method over these yields results and works as expected (so I suppose the JS core works as it should , it’s just matter of developer tools).

Quick fix to this is : just reload the page, then all files will be loaded and you can happily work as expected.

Small sample how it looks like in IE developer tools (the very same page, just loaded 2 times) :

First load:

ie11 developer tools load error

Second load:

ie11 developer tools load OK

Just in the case, version of my IE 11 :

my ie11 version

Hope this helps someone, enjoy.

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

Solution to your problem :

For some reason,  account on which you run VS on and on which VS hosts PowerShell has restricted ExecutionPolicy (you can type Get-ExecutionPolicy , select the text and hit CTRL+F8 and should see Restricted as the answer).

So the solution is simple (should be): override the settings and set it to RemoteSigned with this command :

Set-ExecutionPolicy RemoteSigned

select the text, hit CTRL+F8. Now hitting F5 should make your PS behave.

(Alternatively Unrestricted is also viable option, but this is considered unsafe. More on this here : http://technet.microsoft.com/en-us/library/ee176961.aspx)

More on the topic :

I wanted to create some PowerShell script and I thought there has to be something better than PowerShell ISE (sry, I am just too used to VS and debugger and all that goodness I have at my disposal) so I discovered this wonderful plugin for VS 2012 – PowerShell Tools for Visual Studio – http://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597 and all worked as expected, until (as far as I remember) I restarted OS and had this strange error in VS in my output window :

Error: File C:\users\your_name\documents\visual studio 2012\Projects\PowerShell Script Project1\PowerShell Script Project1\Script.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.

The program ‘PowerShell Script’ has exited with code 0 (0x0)
(Small side note here to make you more puzzled but this might also help you in some way : I work in a company where admins takes security seriously and our “normal” day to day accounts are restricted and don’t have access to this and that so we have another accounts to install sw, make changes to the system, etc. I need to run my VS under this account, not my own.)
Great, no what? There is a link to documentation about what execution policies are and how to set them, etc, I changed it from vanilla restricted state to RemoteSigned and the very same .ps1 file worked after I set RemoteSigned for my and my admin account. It looks like PS stores policies per user in registry. More on this here : http://dusan.kuzmanovic.net/2012/01/04/powershell-execution-policy/

 

Than I had “brilliant” idea to try PowerShell commands in NuGet Package Manager Console because it is using PowerShell under the hood, I was just looking for some prompt to query the ExecutionPolicy. And the magic happened, after query the PowerShell worked!!!! Brilliant but this is just workaround and not the solution.

 

After this the best idea seemed to contact the author so I mailed directly Adam Driscoll (apologies for distraction) which led to few discoveries like :
  • Writing some text in the .ps1 file in VS and selecting some code and right click reveals Execute selection option that is able to run your code event if it fails running it F5,
  • Adam downloaded in his spare time NuGet sources and it looks like : “NuGet sets the process scoped execution policy to RemoteSigned when it is initialized. “

So next logical step would be to try to run Set-ExecutionPolicy from VS to set it for account that VS is using to run PowerShell. And it looks like it is working.

Enjoy guys and thanks Adam for your plugin and your time.

How to split string in PowerShell with multiple delimiters

Hello world.

I just wanted to share with you one simple stupid snippet (please note, I am PowerShell newbie so have mercy and if there is any better way, please share in comments, thank you).

Because in my current work we need to parse and update some .aspx files (I will try to publish this later on my github),  I am fiddling a bit with PowerShell and Regex and such stuff.

I wanted to split a row in processed .aspx file and I wanted to use multiple delimiters while splitting. But according to this :

http://technet.microsoft.com/en-us/library/hh847811.aspx

you can’t use multiple delimiters as parameter, like say array of delimiters like I was used to in C# :

http://msdn.microsoft.com/en-us/library/vstudio/ms228388.aspx

OK so without any further  ado :

you can chain .Split in PowerShell like this :

$splittedRow = "<tag id='abcd' id2="efgh"></tag>".Split("""").Split("'")
Write-Host $splittedRow

This will return string splitted with delimiter ” and ‘.

Enjoy.

Unable to attach to the process. A debugger is already attached. – Unable to attach to IIS problem in Visual Studio.

So I came across this sweet little problem that I wasn’t able to attach to IIS 7.5 from my VS 2012 on Windows 7 and I want to share the solution with you.

I am taking part on development of larger ASP.NET WebForms 4.5 application and we are using local SQL server + local IIS 7.5 on Windows 7. From some point in time, I wasn’t able to attach to IIS w3wp.exe process.  Every other process I was able to attach however and I was puzzled. The note I had from VS 2012 was looking like this :unable to attach to the process IIS vs 2012

The problem was, that I wasn’t for some time creating any server side code (I was playing on the client) and I installed some tools and programs that might changed something. Another problem was, that I could inspect the w3wp.exe in say Process Explorer but I wasn’t able to find any tool that would tell me : what process in attached to some particular process of my interest (if you know any tool that can do this, please share, thank you). I googled and binged but most of the problems I found were about Developer Tools in IE attached to IE itself and nothing that could help me.

Today I had some time to fiddle around and the solution is simple :

I was playing with this tool from Microsoft : Debug Diagnostic Tool 1.2 which is able  (if you create a rule for that) to listen to IIS and collect exceptions. I created a rule some time ago and I forgot to deactivate it. So everytime IIS started, it attached and collected the data. I told DDT to do so. And I was second in a row. If you deactivate the running/attached rule, VS will be able to attach again.

Just don’t forget to do so.

debug diagnostic tool deactivate rule

Hope this will save you some time. 🙂 Enjoy.

IE10 developer tools – web page is not responding

I just came across nice thing with Internet Explorer 10 on Windows 7.

I was debugging JS on my dev box and I experienced problem like this :

ie10 localhost not responding

At first it seems like development tools freezed. Also IE as such freezed. What I saw was IE with page in the back and tools with note you see above. I clicked on IE icon in taskbar and saw two “windows” like this.

ie10 two debugging taskbar

In fact what happened and I didn’t realized that was :

  • I started IE,
  • I opened development tools – tools are attaching to IE and listening to events = we are debugging,
  • some JS error happened,
  • I clicked on “Do you want to debug this web page?”,

ie10 js error

  • IE opened another development tools and now we have 2 development tools windows opened like this :

ie10 two debugging windows open

Problem is, that you see only 2 windows opened under IE icon, the reality is that you have IE and 2 development tools windows. 1 is live and working, 2 is blocked by newly opened one and might be hidden behind one of these two. So beware of this fact. IE works well, but this behaviour is not expected, at least by me.

Hopefully this will save you some time. Enjoy.

AD: I found one more thing. If IE while debugging misbehaves and shows you blablabla page is not responding – same as in first picture – just hit Win key + D = shortcut to display desktop and bring IE up again and it should work 🙂

Microsoft TechDays Žilina 2013

Včera som sa zúčastnil TechDays v Žiline a preto malý krátky článoček o + / – a pár fotos. Všetky názory sú moje vlastné, hodnotím akciu z môjho uhla pohľadu ako developera, prosím berte ich len ako fakty na Žilinskej edícii. Osobne som sa zúčastnil Dev tracku a potom šiel na Azure camp, môžem teda hovoriť len o tom čo som videl tam.

V prvom rade, ak robíte s MS technológiami, alebo sa o ne zaujímate, je to viac/menej povinná jazda. Uvidíte ľudí stojacich za www.vyvojari.sk, ľudí priamo z MS ktorí Vám pomôžu/nasmerujú ak treba a prípadne nejaký ten networking s ľudmi z fachu alebo peknými študentkami, človek nikdy nevie 🙂 Každopádne je to komerčná akcia, nieje to akcia ala Barcamp. Ale to asi nik ani neočakáva.

Každopádne by som odporúčal KAŽDÉMU zamestnávateľovi ktorí to myslí vážne so svojím IT/dev/devops oddelením aby napakoval developerom auto jedlom a kávou, dal im kľúče a o deň posunul deadlines a TRVAL na tom, aby tam šli (v prípade potreby použiť aj vyhrážky), investícia do ľudí je vždy dobrá investícia (a občas im kúpte aj nejakú tú knihu, myslím o developmente, nie 50 shades of gray či čo to je).

Takže + :

  • Prezentátori prídu bližšie k Vám, ak nieste z BA,
  • Ľudia priamo zo SK alebo CZ MS,
  • MVPs alebo exMVPs ktorí poradia/pomôžu (alebo na nich dostanete kontakt, môžete diskutovať mailom),
  • Tracky pre developerov, ITpros, dizajnérov, a pod., každý si vyberie,
  • Zaujímavé témy pre široké spektrum ľudí pohybujúcich sa okolo IT,
  • Je veľmi príjemné vidieť ako vaša alma mater prosperuje a že sa jej darí a po dlhšom čase včera zo Žiliny a z fotos z KE som mal ten wow pocit, tie priestory sú už dosť dôstojné, nemusíme sa za ne hanbiť, máme kde prezentovať študentom a je tam všetko vybavenie ktoré na to treba (ak ehm funguje, viď nižšie…).
  • Zaujímavé témy pre mňa ako developera, w8, azure, EF5 a pod,
  • Na campoch sa rozdávali “darčeky” ako knihy a pod. veci, čo je super podpora pre developerov IMHO

Nejaké tie – (alebo povedzme fakty ktoré by mohli byť aj lepšie/iné) :

  • Tento rok nebol žiadny termín v Banskej Bystrici a viem minimálne o 2 ľudoch ktorí nešli len pre tento dôvod (ja som vám vravel Michal a Tomáš poďte, budú ženy… ale nie…),
  • Nebola žiadna pauza na obed, len pauzy pomedzi prednášky (ovocie, káva a bagety to istili), osobne by som asi posunul začiatok a nechal nejakú pauzu,
  • Trochu ma prekvapilo že na Azure campe bolo menej ľudí ako som osobne čakal, téma bola zaujímavá, aj speakri (vlko, slavo furman, miro kubovčík), dôvod teda netuším,
  • Dostal sa mi do ruky Microsoft Surface of Spigiho, no nedostal sa zvyšku, myslím že developeri by to ocenili (nebol som ale na Windows 8 campe, len na dev tracku),
  • Asi 2x nám vypadla elektrina, nie vždy fungovali mikrofóny a pod. drobnosti, nebola napr ani free wifi, čo nieje tragédia ale keby som bol z CZ alebo PL tak isto neplatím dátový roaming na 1 deň, načo (toto je pekne riešené free wifi napr na Barcape vo Vsetíne a je to super, ale pre úplnosť hore na Azure campe sme mali papier s name/pwd do wifi no bola asi skôr pre prezentujúcich, každopádne ja som nikde nevidel wifi pre návštevníkov),
  • Chcelo by to niečo intenzívnejšie, možno aj nejaké hands on laby KEBY bol čas na campoch, možno by to chcelo ďalší extra deň pre laby, teda 2 dňovú akciu. Chcelo by to proste prebrať viac tém v rámci campov, lenže za 4h sa nejak extra “svietiť” nedá, škoda.

Takže snáď som na nič nezabudol, pokochajte sa ešte extra kvalitnou galériou môjho mobilu a na budúci rok príďte.

http://sdrv.ms/ZSwLfr

Some paths to useful tools on Windows

Because I had to troubleshoot this weekend in total 2 notebooks (why not booting, unable to install Windows 7, etc.) I came across one useful tool that is able to log what is happening on startup (in case you are able to boot at least in safe mode) and that is :

msconfig

More on this tool here : http://www.techrepublic.com/blog/itdojo/monitor-windows-7-boot-logs-with-the-help-of-msconfig/3463

But that is not what I want to share here, its just how I got the list of tools. On the last Tools tab of his tools you can find nice list of tools that you can “extract” out as lets say shortcut on your desktop and thus speed up some tasks you do often. So here is the list :

Tool name Description Command
About Windows Display Windows version information C:\Windows\system32\winver.exe
Change UAC Settings Change User Account Control settings C:\Windows\System32\UserAccountControlSettings.exe
Action Center Open the Action Center C:\Windows\System32\wscui.cpl
Windows Troubleshooting Troubleshooting problems with your computer C:\Windows\System32\control.exe /name Microsoft.Troubleshooting
Computer Management View and configure system settings and components C:\Windows\System32\compmgmt.msc
System Information View advanced information about hardware and software settings C:\Windows\System32\msinfo32.exe
Event Viewer View monitoring and troubleshooting messages C:\Windows\System32\eventvwr.exe
Programs Launch, add and remove programs and Windows components C:\Windows\System32\appwiz.cpl
System Properties View basic information about your computer system settings C:\Windows\System32\control.exe system
Internet Options View internet properties C:\Windows\System32\inetcpl.cpl
Internet Protocol Configuration View and configure network address settings C:\Windows\System32\cmd.exe /k %windir%\system32\ipconfig.exe
Performance Monitor Monitor the performance of local or remote computers C:\Windows\System32\perfmon.exe
Resource Monitor Monitor the performance and resource usage of the local computer C:\Windows\System32\resmon.exe
Task Manager View details about programs and processes running on your computer C:\Windows\System32\taskmgr.exe /7
Command Prompt Open a command prompt window C:\Windows\System32\cmd.exe
Registry Editor Make changes to the Windows registry C:\Windows\System32\regedt32.exe
Remote Assistance Receive help from (or offer help to) a friend over the Internet C:\Windows\System32\msra.exe
System Restore Restore your computer system to an earlier state C:\Windows\System32\rstrui.exe

In case you know about some more, please share.

Enjoy.

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.