by Njål

Cancelling old S-* PayPal Subscriptions from code

2015-10-26_1408

PayPal does not support cancelling old S-* subscriptions from code/api’s. This means that either you (as a merchant) or the customer has to log in to PayPal’s API and cancel these subscriptions manually. #Pain.

Luckily – it can be automated using Phantom.js. Phantom.js is basically a rock solid webbrowser without a UI which you can program (JS) to do stuff for you. I have made a PayPal.js script which lets you input Email, Password and the old S- SubscriptionID you want to cancel.

Here’s how to use it:

  1. Download Phantom.js (2.0.0) – and Unpack it to a new folder – http://phantomjs.org
  2. Download PayPal.js and place it in the same folder
  3. Run phantomjs.exe –ssl-protocol=any paypal.js paypalemail@gmail.com MySecretPass S-123455634545234
  4. While it’s running – keep an eye on the folder. PNG screenshots will appear there providing you a peepshow of the progress.
  5. When done – your website will receive a IPN Callback from PayPal.

 

by Andreas

Aborting AJAX requests in ASP.NET applications

imageI’ve been working on a pretty extensive web application lately, build on top of the .NET framework but with around 80% client side functionality (KnockoutJS, jQuery). There’s a lot of AJAX calls back to the server (naturally.. ) and one of the challenges I faced was that ASP.NET refused to navigate away from a page until all AJAX requests were processed. I did some searching and found out that an AJAX request could be aborted by adding some functionality to the window.onbeforeunload event:

window.onbeforeunload = function() {
    if (ajaxRequest !== undefined) {
        ajaxRequest.abort();
    }
};

 

By adding some logging to console I could clearly see that as soon as I clicked a link to navigate away this event was called and processed. But still nothing happened until the request had fully been processed – which made me think this had to do with the browser. Wrong assumption, and when writing this it seems very obvious to me why but then again retrospect is an ugly thing.

A bit more research and it turned out that this was all due to ASP.NET session state (which is enabled by default). Because of the session state my site serializes all requests within the same session, so the request for a new page would not be processed until the first one had completed. Turning session state off completely was out of the question, but by changing my .ashx handler (which receives all my ajax requests) to implement the IReadOnlySessionState interface rather than IRequiresSessionState there is no lock on the current session and concurrent requests are made possible.

Something to keep in mind though is that aborting an ajax request obviously doesn’t stop the server from processing it.

by Joakim

JavaScript file missing from resource bundle (ASP.NET Web Optimization Framework)

I came across some odd behavior related to the Microsoft ASP.NET Web optimization Framework the other day, when I was creating a JavaScript resource bundle in an application I was working on. When I ran the website with optimizations enabled, the script file showed up as part of the bundle, but if I turned optimizations off the script include for the file in question was nowhere to be found.

For the application I was working on, which was only a proof of concept, I had simply copied the minified version of the JavaScript libraries I needed into the Script manually. I then included my libraries in a script bundle like so;
BundleTable.Bundles.Add(newScriptBundle(“~/bundles/jquery”).Include(“~/Scripts/jquery-1.8.2.min.js”));

If you have used this bundling functionality before, you probably know that if you include a JavaScript file in a bundle and you enable optimizations, the file will be minified and added to a single resource together with any other JavaScript files in the bundle. During the minification process the system will look for other files in the directory called exactly the same filename as the file in question only with .min.js at the end instead of only .js. If it finds a file like this, it assumes that this it is a pre-minified version of the file in question and uses it instead of minifying the original file.

However, if you add a file to your bundle that has a name that ends in .min.js (like I did) and optimizations aren’t enabled (e.g. debug is set to true in web.config and BundleTable.EnableOptimizations has not been set to true), this file will be ignored (i.e no script include will be generated for it in your html).

by Andreas

Define a #Region in javascript files (Visual Studio 2010 / 2012)

In these times of super responsive client side processing mega javascript extravaganza web applications  you’re more than likely to end up with fairly large .js files in your projects. The standard code file in Visual Studio allows you to define collapsible sections by wrapping them with the #region / #endregion blocks. In javascript files however, you are restricted to collapsible functions only (“#region” is not recognized as anything valid):

image

Well, I just found out that that’s not entirely true. By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable

image

by Njål

Force Hard Reload in Chrome

Reloading pages in Chrome can be done in a few different ways:

  • Ctrl-R (or F5) – Normal Reload
  • Ctrl-Shift-R (or Ctrl-F5) – Hard Reload

I’m sure you knew this already. But here’s a new trick – you can do a Hard Reload and Clear Cache at the same time by right clicking on the Reload button. This requires that you have the developer console open (F12).

image

by Njål

String replaceAll in Javascript

imageIn Javascript the string.replace(“target”, ”replacement”) function only replaces the first occurrence of the target…

Here’s how you can add a replaceAll() metod to all Strings (similar to Extension Methods in C#).

String.prototype.replaceAll = function (orig, replacement) {
    return this.split(orig).join(replacement);
}

 

You can then write (anywhere in your code):

"a a b c".replaceAll("a","X"); //==> "X X b c"
by Andreas

KnockoutJS – how to force binding refresh / re-evaluation

Observable bindings in KnockoutJS get re-evaluated when the focus is changed in a form, for instance when you click a button or use TAB to move from one input field to the next. When KnockoutJS is used in combination with an ASP.NET panel control where a DefaultButton is defined, re-evaluation of observable bindings is not performed when the user clicks ENTER to trigger the button click event. As a result of this, a value entered in an input field that is bound to the view model will not be registered if the user doesn’t navigate (move focus) away from the field first. 

A work-around for this is to use jQuery (or pure javascript) and programmatically set the focus to a different control, for instance the button itself when the event is fired.

self.addNewTimeRegEntry = function () {
    // set focus to button control to force re-evaluation
    $("#<%= btnAddRegEntry.ClientID %>").focus();

    ... // continue as normal

The button click event is bound to the addNewTimeRegEntry function above (through the KnockoutJS framework), and by moving the focus all variables will be refreshed before further processing is done.

by Stian

Redirect page with jQuery / JavaScript

There are several different ways to do a clean redirect from one URL to another with some simple jQuery / javascript. I’ll start out here showing what in my opinion is the best way to simulate a HTTP redirect and then show a few other options that you have.

Pure javascript
// similar behavior as an HTTP redirect
window.location.replace("http://blog.degree.no");

This method is in my opinion the best, because the window.location.replace() is redirecting the page without putting the original page in the browser history.

// similar behavior as clicking on a link
window.location.href = "http://blog.degree.no";

This method works fine as well, but it will throw the user in to a back button loop if they would want to go back in history.

jQuery

My impression is that developers sometimes search for the “jQuery way” to do things and maybe you found this blog post searching for “redirect page with jQuery”? While there is a way to do this in jQuery, there is really no reason why you would want to do this as it could not be easier to with normal javascript. But since you searched for it, here it is.

$(location).attr("href",http://blog.degree.no);

 

image

by Andreas

Converting JSON date string to javascript date object

JSON dates come in a format that isn’t directly convertable to Javascript date objects (e.g. /Date(1349301600000+0200)/ ). This can cause a bit of headache, but there is a very simple way to convert this to a native date object.

After stripping off the initial “/Date” part using substr, parseInt will return only the integers and ignore the trailing “/”. The result is an integer value that can be used in the native javascript Date constructor.

This is what goes on under the hood:

1. Original JSON date

/Date(1349301600000+0200)/

 

2. After substr(6)

1349301600000+0200)/

 

3. After parseInt()

1349301600000

 

Finally I am using DatePicker from the jQuery UI library to format the date to a custom JSON date:

// parse JSON formatted date to javascript date object
var date = new Date(parseInt(jsonDate.substr(6)));

// format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", date);

 

On the server side I recommend using the Json.NET framework by James Newton-King (available as a NuGet). It contains several settings for handling dates depending on what you’re running client side. If you’re using KnockoutJS for instance, the ko.toJSON method will return your date object in UTC format (which means the date might suddenly be a day off, with an offset set to +2 hours my current timezone).

My quick-fix using DateTime.ToLocalTime() will work, but I am sure there is a more elegant way of getting your local time directly in the Json deserialization process:

// parse JSON
var timeRec = JsonConvert.DeserializeObject<JSONTimeRecord>(jsonString, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// convert date to local time
updatedRecord.Date = timeRec.Date.ToLocalTime();

 

At least that works fine – for now..

by Njål

console.log and Internet Explorer

imageWhen coding/debugging JS I usually work with Chrome and console.log works like a charm. But when you test the same page in Internet Explorer you’ll get a javascript error.

If you then open Developer Tools in IE and hit refresh – the page will work 100% – since IE now has a console object (the developer tools window) it can log to.

The solution is to either remove all console.log statements – or add this at the top of your js file:

 

if console === undefined {
    console = { log : function(){}};
}