Archive

Author Archive

ASUS U36SD windows experience index score

October 5th, 2011

After getting my new laptop, an ASUS U36SD, weighting only 1,7 KG, replacing the HDD with an SSD and upgrading the RAM to 8 GB (I can’t believe how cheap ram is these days.) I ran the windows experience index test. These are the results I came up with.

I think that is pretty good for a laptop of this size and price.

Martin Uncategorized

Format your json with userscript

September 8th, 2011

I have created a very small userscript for opera (might work ok with other browsers) that formats /indents/ beautifies the JSON data in a document if it’s only JSON there.

For opera to open the JSON by itself and this to work (the default is to present it as a download), you will have to enable that in opera. Go to preferences -> advanced -> downloads -> Add

Mimetype: application/json
Select open with opera

That will result in your JSON looking like this in the browser:

// ==UserScript==
// @name 		   JSON formatter
// @version        1.0
// @description	   Formats JSON if the document only contains JSON
// @compability    Only tested with Opera, might work with others
// @author		   Martin Hansen
// @website        http://martinhansen.no
// ==/UserScript==
(function(){
	var indentation = 4;//Change this to vary the indentation

	var pre = document.querySelector('body pre:only-child');
	if(!pre) return; //Don't do anything if this don't seem to be a json only document
	try{
		pre.innerHTML = JSON.stringify(JSON.parse(pre.innerHTML), null,indentation);
	}
	catch(e){
		console.log(e);
	}
})();

Either save the sourcecode directly from here, or get it from userscripts.org

Martin Javascript, opera, web

Text selection mode off in opera

June 13th, 2011

A nice feature in opera is to turn off text selection when dragging on the web page. For instance when using opera on an iPad over remote desktop to your pc. This allows you to drag the page as you would in the native browser on the iPad.

To enable this, right click any toolbar and press customize – apperance – buttons – browser view. Then drag the button “text selection on” to any toolbar of your choice. Then whenever you want to activate the mode, click the button.

Martin Uncategorized

Getting the bearing/heading betweet 2 coordinates

April 14th, 2011

Thanks to rjsteward with his answer over at stackoverflow.com I have now a simple function for getting the bearing between to coordinates:

The function is meant to be used with google maps, so the parameters are google.maps.LatLng objects

function getBearing (from, to) {
            var lat1 = from.lat() * Math.PI / 180;
            var lon1 = from.lng();

            var lat2 = to.lat() * Math.PI / 180;
            var lon2 = to.lng();

            var dLon = (lon2 - lon1) * Math.PI / 180;
            var y = Math.sin(dLon) * Math.cos(lat2);
            var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);

            var bearing = Math.atan2(y, x) * 180 / Math.PI;
            if (bearing < 0) {
                bearing = bearing + 360;
            }
            return bearing;
        }

This allows you to easily set the heading in the streetview, between your “streetviewman” and the actual position you are trying to see. So that you are looking to that direction from the street.

map.getStreetView().setPov({ heading: getBearing(streetViewManPosition, myLocationPosition), zoom: 1, pitch: 0 });

Resulting in something like this:

Martin Javascript , , , ,

How to return clean JSON from EF object with data attributes

April 4th, 2011

Returning JSON is very simple in ASP.NET MVC:

 return Json(Person,  JsonRequestBehavior.AllowGet);

(Person is an Entity Framework object)

The problem with this is if Person have related objects, like e.g. Friends. Then the serializer will throw an error because it will get a circular reference when tying to serialize Person.

So one common solution is to just create a new anonymous object on the fly like so:

 return Json(new {Name = Person.Name, Age = Person.Age},  JsonRequestBehavior.AllowGet);

A second solution is to create a Poco class that you fill with data from the entity object.

A third solution is to “tag” your model members with Attributes. But you cannot do this with an EF class, since the codefile is autogenerated, and if you change the code then your changes will be overwritten the next time you use the designer.

The following code demonstrates how to make this work anyway.

public class PocoAttribute : System.Attribute
{
}

[MetadataType(typeof(PersonMeta))]
public partial class Person
{
}

public class PersonMeta
{
    [Poco]
    public string Name { get; set; }
    [Poco]
    public int Age { get; set; }
}

This is the same approach used to add data annotations to members in your EF objects. (See http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs)

Now we need a way to automatically return a JsonResult with only the properties we have given our attribute to. For this we can create an extension method:

public static Dictionary<string, object> GetPocoDictionary(this EntityObject obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();
    var pocoMembers = properties.Where(d=> d.GetCustomAttributes(typeof(PocoAttribute), true).Count() >= 1).ToArray();

    var metadataAttribute = (MetadataTypeAttribute)obj.GetType()
    .GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();

    var metaClassMembers = metadataAttribute.MetadataClassType.GetProperties()
    .Where(d=> d.GetCustomAttributes(typeof(PocoAttribute), true).Count() >= 1).ToArray();

    var combinedPoco = pocoMembers.Union(metaClassMembers);
    var allMembers = from propall in properties
                     join combined in combinedPoco on propall.Name equals combined.Name
                     select propall;

    var dict = new Dictionary<string, object>();
    foreach (var item in allMembers)
    {
        dict.Add(item.Name, item.GetValue(obj, null));
    }
    return dict;
}

This will take any EF object and return a dictionary with only the members that we have given the attribute to.
Now to use it:

 return Json(Person.GetPocoDictionary(),  JsonRequestBehavior.AllowGet);

That’s it!

Martin asp.net, c# , , ,

jQuery checkbox/radiobutton dependence plugin

March 29th, 2011

I have made a small jQuery plugin that enables you to have checkboxes and radiobuttons that depends on each other in a nested way.

The usage is very simple, just take a collection of radios or checkboxes and define an element they depend on. If you check an element that depends on something, the parent will be checked as well.

In the same way, if you uncheck a parent element that have children, then the children will be unchecked as well.

The plugin is designed to also work with jQuery UI buttons

$('#fruitlist>li>input').dependsOn('#fruits');
$('#citruslist input').dependsOn('#citrus');
<ul>
	<li><input type="radio" name="products" value="books">books</li>
	<li><input type="radio" name="products" id="fruits" value="fruits">fruits
		<ul id="fruitlist">
			<li><input type="checkbox">apples</li>
			<li><input type="checkbox" id="citrus">citrus fruits
				<ul id="citruslist">
					<li><input type="radio" name="citrus">lemons</li>
					<li><input type="radio" name="citrus">oranges</li>
				</ul>
			</li>
		</ul>
	</li>
	<li><input type="radio" name="products" value="pens">pens</li>
</ul>

Demo:


  • books
  • fruits

    • apples
    • citrus fruits

      • lemons
      • oranges
  • pens

Here is the code:

/* jQuery checkbox/radiobutton dependance plugin
* By Martin Hansen http://martinhansen.no
* MIT Licensed.
*/
(function($) {
  $.fn.dependsOn = function(parent) {
    // build main options before element iteration
    if(parent === undefined){ console.log('Parent is required'); return;   }        

    var opts = {parent: parent, value: null};

     //If parent is a radiobutton part of a group, make the group the parent
    if($(opts.parent).attr('type') == 'radio'){
      opts.origparent  = $(opts.parent);
      opts.parent = 'input[name=' +$(opts.parent).attr('name') +']';
    }  

    return this.each(function() {
    var caller = $(this);
    $.data(this, 'dependsOnOptions', opts);//Store the dependency options

    caller.bind('click iterate', function(event){
      var parent = (opts.origparent) ? opts.origparent : $(opts.parent);
      parent.attr('checked', true).trigger('iterate', ['Iterate', 'Event']);
      if (jQuery.ui)parent.button('refresh'); //If jquery ui is loaded try to refesh button
    });              

    $(opts.parent).each(function(i){
      var pp = $(this);
      //Do first time checks
      var checked = pp.attr('checked');
      if(checked){
        $.fn.dependsOn.check(pp, caller, opts);
      }
      //bind for change
      pp.change(function(event){
        $.fn.dependsOn.check($(this), caller, opts);
      });
    });

   });
  };     

   $.fn.dependsOn.check = function(parent, child, opts){
    if (!parent.is(':checked') || !$(opts.origparent).is(':checked')) {
      child.attr('checked', false).change(); //uncheck the checked child, and trigger the change event so that any potential grandchildren also gets updated
      if (jQuery.ui)parent.button('refresh'); //If jquery ui is loaded try to refesh button
    }
   };
})(jQuery);

On github: https://github.com/mokkabonna/jQuery-dependency

Edit:updated the code to use .is(‘:checked’) instead of .attr(‘checked’), as jQuery 1.6.3 returns ‘checked’ instead of true. Thanks to “all” in the comments for making me aware of if.

Martin Javascript

Network problems with DNS symptoms

March 14th, 2010

If you are having what seems to be DNS problems in your network, but others seem to connect without problems it might not be DNS problems at all, but something to do with your MTU setting, read more here. This solved a problem I’ve had for a long time on a friends network.

Martin Uncategorized

Harvest time tracking widget for Opera

March 14th, 2010

I’ve made a Opera widget that connects to Harvest, a time tracking/invoicing service which is great. The widget is built using only HTML/CSS/Javascript(jQuery) and since I only need to support Opera, I have used technologies like web databases, rounded CSS corners, box shadow etc. Also nice to have the ability to use CSS selectors like :last-of-type to make things easier.

Download it here

Martin Development, HTML5, Software

HowTo: Set google “I’m Feeling Lucky” as default search

October 23rd, 2009

URL’s suck.

When I want to go to Google calendar I want to type just that, or even google cal. Instead of Google dot com slash calendar. When I want to see today’s episode of Colbert report, I should be able to type that in the address bar even though the address is colbertnation dot com.

Enter Google’s “I’m Feeling Lucky” search. Below is a guide to set Google’s “I feel lucky” as default search in various browsers:

Opera:

  • Open Google.com, or your favorite Google page.
  • Right click the search field and select “Add custom search”
  • Click details, in the address field you will see something like this:

http://www.google.com/search?hl=en&source=hp&q=%s&btnG=Google+Search&aq=f&oq=&aqi=

  • Now, change btnG=Google+Search to btnI, so it looks like this:

http://www.google.com/search?hl=en&source=hp&q=%s&btnI&aq=f&oq=&aqi=

  • Finally check “Use this as default search engine”

Chrome:

  • Enter options -> Basics ->Default search section, click manage.
  • Select the already existing Google search, click edit, copy the URL.
  • Close, and add new.
  • Type a name and, leave keyword empty, and paste into the URL that which you copied and add &btnI, it should be something like this:

{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q=%s&btnI

  • Click ok, and then set as default.
  • You can still search with Google by typing  the keyword (google.com) and then you’ll see the search appear under the address bar.

Martin Uncategorized, web , , ,

Dragging and resizing windows easily

October 22nd, 2009

My absolute favourite feature of KDE on linux is the ability to move a window by holding down the Alt button and left-clicking ANYWHERE in the window, and also to hold down Alt and the right-click to easily resize the window. (Why do we need huge window edges MS?)

These features I really miss on windows, but I finally found a small program that makes that possible on windows. It has the awesome name of KDE Mover-Sizer :P

Enjoy!

Martin Uncategorized ,