Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, October 18, 2018

Cannot convert the literal 'undefined' to the expected type 'Edm.Guid'

If you get this error when working in Javascript with DynamicsCrm (or any system that uses Odata), and you get this error, then you most likely need to setup your object like this:

var request = {

    ObjectId: {guid: "E8C656B7-6AD1-E811-A967-000D3A30D5DB"}

};

Otherwise, the request that will get sent will have undefined value and the response will have an error with the following message:

message=An error occurred while validating input parameters: Microsoft.OData.ODataException: Cannot convert the literal 'undefined' to the expected type 'Edm.Guid'. ---> System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

Tuesday, August 21, 2018

Dynamics CRM–debugging when using executionContext

Xrm.Page is being deprecated and one needs to pass the executionContext to the javascript function to get at the data that was available from Xrm.Page. But, how do you test your function from the browser’s debbuger?

What I do is I create my own executionContext variable and then pass it to my js function to see how it would work.

fakeExecutionContext = {
     getFormContext: function(){return Xrm.Page;},
     context: Xrm.Page.context
}

and you would call it like this:

myTestDynamicsFunction(fakeExecutionContext);

Sunday, February 24, 2013

Javascript–Convert URLs in text to links

Was looking for some code to convert urls in strings to url anchors. Came across this post (JMRWare) and below is the extracted code for javascript:

Thursday, August 12, 2010

A simple scheme for checking for JavaScript in a browser

Do you need a simple way for detecting if JavaScript is enabled in the browser and to notify the user that JavaScript is disabled.

Here is a simple method that I came across:

It uses JQuery and CSS. The idea is to have a JSMessage div with static text that specifies that Javascript is disabled in the browser. You then use Jquery to hide the div. If Javascript is enabled the message goes away, otherwise the message is seen by the user. The CSS helps in displaying the message prominently to the user.

Below is a screen shot of the site in IE:

image

Here is the source code:

HTML, using GeSHi 1.0.8.8
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
    <title>JavaScript Browser Test Sample</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
        <style type="text/css">
                #jsMessageContainer
                {
                        text-align: center;
                        width: 100%;
                        z-index: 100;
                        position: absolute;
                        margin-top: 45px;
                }
                #jsMessage
                {
                        padding: 10px;
                        background-color: #FFFFE1;
                        width: 400px;
                        border: solid 3px #CCCCCC;
                        top: 20px;
                        margin: auto;
                        text-align: left;
                }
                #jsMessage .exclamation
                {
                        float: left;
                        margin: 10px;
                }
        </style>
</head>
<body>
    <div id="jsMessageContainer">
        <div id="jsMessage">
            <p>
                <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Error.svg/497px-Error.svg.png" width="50px" class="exclamation" />
                JavaScript is required for running this website.
                                Instructions for fixing it........
            </p>
        </div>
    </div>
    <script type="text/javascript">
        $("#jsMessageContainer").hide();
    </script>
</body>
<h1>Hello World</h1>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut tincidunt lacus odio, at commodo neque. Aliquam ac felis magna, et placerat dui. Fusce fermentum, diam et congue rhoncus, ligula erat hendrerit magna, vel molestie augue velit vel ipsum. Mauris in erat mauris. Maecenas semper, sapien quis pretium ullamcorper, felis est posuere sapien, volutpat imperdiet enim magna at tortor. Praesent a nisi enim. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam varius varius libero sit amet dapibus. Cras sed purus id sem bibendum accumsan. Mauris aliquam hendrerit aliquam. Mauris adipiscing congue nulla id pellentesque. Cras feugiat placerat quam, sed commodo lacus fringilla nec. Cras tempus lorem ut massa consequat accumsan. Suspendisse id urna nibh. Fusce mauris quam, imperdiet nec bibendum a, euismod at eros. Quisque accumsan orci vel eros bibendum id sollicitudin turpis adipiscing.
<html>

Friday, June 18, 2010

Why you cant make cross-domain XMLHttpRequest(s)

XMLHttpRequest method is an important part of any AJAX enabled website. But if you ever try to get data from a web-service that is hosted on a different server using XmlHttpRequest, you will quickly learn that this will not work.

For the longest time, I just knew that this would not work, but I could not give a specific reason as to why this was the case. Finally, I decided to spend a little time and learn the why behind this restriction and here is the answer:

Basically it is because of what is known as the “Same Origin Policy” and its a policy that is enforced by the browser which do it because of a W3C standard for XmlHttpRequest. (“The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP”)

There is a lot more in-depth information available on this issue from the Mozilla developer site: https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript. This page also talks about what constitutes a cross domain request.

So are there ways around this: the answer is Yes. But some are more hacky then others and the best solution is dependent on your specific circumstance. (example: http://www.nathanm.com/ajax-bypassing-xmlhttprequest-cross-domain-restriction/)

The solutions that I lean towards are: If the web-service can return a special JSON object called JSONP object – then this is probably the easiest solution. A lot of publicly consumable web-services today expose this format. But what if the returned data is XML or cannot be converted to JSONP? In this case the next best solution is to write server side code that acts as a proxy to the original web-service. Your javascript code, calls a web-service on your server, which in turn calls the original web-service. Obviously for this to work you need to be able to write server side code (PHP or WCF, etc…)

Now you know!

More info:

Same Origin Policy: http://en.wikipedia.org/wiki/Same_origin_policy

JSONP: http://en.wikipedia.org/wiki/JSON#JSONP

Ajaxian: JSONP: JSON With Padding

Inside RIA - What in the heck is JSONP and why would you use it?

Monday, April 12, 2010

What every .Net developer ought to know about JavaScript

  1. Every JavaScript object is a dictionary.
  2. Every JavaScript function is an object.
  3. Every JavaScript object references a prototype object.

A good post by Scott Allen : http://odetocode.com/Articles/473.aspx

ASP.Net: Referencing root-relative paths (~/) in javascript

The “~/” specifies a root-relative path in ASP.Net. ASP.Net uses the ResolveUrl and ResolveClientUrl to determine the logical path that a path containing the “~/” points to.

If you need to use a root relative path from within a JavaScript method running within an ASP.Net page, then here is what the code looks like:

<script type="text/javascript">
    function OnSuccess() {
              window.open('<%=Page.ResolveClientUrl("~/newWindow.aspx")%>', 
                'mywindow', 
                'width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
      }
</script>

And here is a useful site with information on ASP.Net Paths - http://www.west-wind.com/weblog/posts/132081.aspx

Sunday, February 28, 2010

Use the 404 page to find missing children

Scott Hanselman blogged about an excellent idea that he had seen where a PHP developer had created a 404 page that displayed a list of missing children.

In my opinion this is a great idea – as people always end up seeing a 404 page and by displaying a list of missing kids – who knows, we might just be able to find a missing kid. Scott created a 404 page using only Javascript (the original used server side PHP). Scott’s implementation uses the ASP.Net AJAX Library and specifically uses the DataView control.

I wanted to make a few modifications to Scott’s implementation of the 404 page:

  1. Make the page so that it is a lot more easier for someone to download the code and reuse it.
  2. Use only JQuery
  3. Geolocate the user using their IP address.

The reason I wanted to use only JQuery was that I didnt think it was necessary to download an extra javascript library just to display the data, when JQuery could do it all. (In addition, I used direct references to jQuery – instead of the $, as it makes it easier to include on a DotNetNuke site).

The biggest improvement in my opinion is the use of the client’s IP address to geo-locate them. By geo-locating the end user, I can customize the list of children to the state from where the user is. This in my opinion increases the probability of finding missing children as the list is smaller and more relevant to the user.

For geo-locating the user, I use two techniques. Because JQuery is loaded using Google’s content delivery network I can use Google’s API to try and determine the location of the user. If this fails (and it does many times), I use IPInfoDB’s webservice to try and geo-locate the user.

image

Here is where you can take a look at my implementation of the 404 page with geolocation capabilities: http://www.aggregatedintelligence.com/404.html

Note:

As I use the Google API, you will need to generate a Google API key to use the code on a webserver (if you are testing – you dont need to do anything). To get the key go to : http://code.google.com/apis/ajaxsearch/signup.html. Once you generate the key, plug it into the file at line: 33 (or search for “YourGoogleApiKeyHere” to find the location).

Download the 404 page from: Google Docs FileShare

Wednesday, February 03, 2010

Monday, February 01, 2010

Javascript – a quick and robust check for NotANumber (NAN)

Javascript provides the NaN property that returns a value that represents NotANumber (NAN).
eg: Number.NaN

But you cannot use the following check to test for a variable containing a NaN:
(someValue == Number.NaN)

The reason is because Number.NaN != Number.NaN by definition of the IEEE standards.

This inequality can be used to your advantage by using the following check:
(someValue != someValue)
The only time the above check will fail is that if someValue contains a NaN value.

Or you can use the global function isNaN(someValue).

note: the (someValue != someValue) is a check that works in many other languages (eg: c, c++, SQL, etc) which is why it is a useful idea to brush into the recesses of your memory.

Monday, January 25, 2010

JQUERY – getJSON with failure callback

If you have used the JQUERY function $.getJSON, you will soon realize that there is no way to assign a function to be called on a failure.

Instead one needs to use the $.ajax method (which is what $.getJSON uses under the covers). And here is what the function would look like

function makeAjaxCall(ajaxUrl, functionSuccess, functionFailure){
        $.ajax(
        {
            type: "GET",
            url: ajaxUrl,
            contentType: "application/json; charset=utf-8",
            data: {},
            dataType: "json",
            success: functionSuccess,
            error: functionFailure
        });
    }

The above function would be called like so:

makeAjaxCall("http://api.twitter.com/1/rockyMtnRajah/lists/ccd-twitters/statuses.json?callback=?", loadTwitterListFeed, loadTwitterListFeedFailed);

loadTwitterListFeed would be implemented like so: (Where parseTwitterJSON would be responsible for loading the JSON data (per element) into the page)

function loadTwitterListFeed(data)
{
    $.each(data, parseTwitterJSON);
}

loadTwitterListFeedFailed is the method that is called when an error is encountered while making the AJAX call to the provided URL.

Important Cross-Site Ajax information when using Twitter API.

If you use the Twitter API to extract your feed as a JSON request, you will find that if you use the Twitter specified url (which will look like this: “http://api.twitter.com/1/rockyMtnRajah/lists/ccd-twitters/statuses.json”) with the makeAjaxCall method, you will get data back in Internet Explorer but not in FireFox and Chrome. The reason is that FireFox and Chrome will not allow you to make cross-site AJAX calls. To get around this issue, Twitter provides you with a way to specify the call-back method. You do this appending “?callback=?” to the URL. Once you do this – your code should work in all 3 of the browsers. (JQuery takes care of setting the correct callback name – for some reason I could not get “callback=loadTwitterListFeed” to work)

Thursday, December 17, 2009

JQuery Print Plugin

Just found the Jquery print plugin “JQuery Print Element” by ErikZ – works great.

http://plugins.jquery.com/project/printElement

Demo: http://erikzaadi.github.com/jQueryPlugins/jQuery.printElement/Sample

Only thing that I had to change was the use of $ symbol in the JS code (as in my environment it conflicts with some other JS APIs that I use).

Monday, October 12, 2009

jQuery UI Dialog and Positioning

Sometimes the default and automatic center positioning of a jQuery dialog upon opening does not work.

jQuery("#dialogDiv").dialog({ height: 'auto', modal: true, width: 400, autoOpen: false, position: 'center' });

I found the following code works to position the jQuery UI dialog in the center of the screen:

var x = document.body.clientWidth / 2;
var y = document.body.clientHeight / 2;
var dlg = jQuery("#dialogDiv");
dlg.dialog('option', 'position', [x, y]); //dlg.dialog('option', 'position', 'center');
dlg.dialog('open');

Friday, October 09, 2009

JQuery – Attribute Filters

JQuery attribute filters make it easy to select and modify particular attributes in your HTML DOM.

For example: if you wanted to hide all links in a page, here is what you need to do

$("a[href]").toggle();

But what if you need to hide only some of the links on your page?

Maybe the one that links to “http://www.ai.com/”

$("a[href='http://www.ai.com/']").toggle();

Maybe all the ones that have google in the href….

$("a[href*='google']").toggle();

(the key to above filter is the “*” – which matches anywhere in the attribute’s value)

Maybe all the ones that end with org

$("a[href$='org']").toggle();

(the key to the above filter is the “$” – which matches to the end of the attribute’s value)

Maybe all the ones that begin with http://doc

$("a[href^='http://docs']").toggle();

(here the the key is the “^” character – which matches only to the beginning of the attribute’s value)

Here are important points to remember:

  1. The filters are case sensitive. (I dont think there is a way to make them case-insensitive)
  2. Unlike regular RegEx expressions – you do not need to escape characters (such as “/” and “&”)
  3. This was true as of JQuery 1.3.2

Sunday, September 13, 2009

Accessing properties in code-behind class from java-script

If the code-behind class has a property called MySampleProperty and if it returns a string value, then this is how you can access it in your javascript:

   1: <script type="text/javascript">
   2: function onAppLoad() 
   3: {
   4:    var vSampleProp = '<%=MySampleProperty%>';
   5:    alert(vSampleProp);
   6: }
   7: </script>

Realize, that I am saying “access” and not call. Because, what happens here is while the ASP.Net is building the web-page to send down to the browser, it sees the code inside <%…%>, calls the property, fills in the value and then sends it down to the browser.

If you need to “call” a method on the server then you need to look at web-services. (Basically you will need to use AJAX, to get the server to send your data asynchronously).

Monday, June 22, 2009

iPhone GeoLocation in Safari

iPhone GeoLocation in Safari uses the Safari’s new geoLocation api to retrieve the current location and in turn gets address information using Google Maps geoCoding api.

photo

var geocoder;

function initialize() 
{
    geocoder = new GClientGeocoder();
    findLocation();
}

function findLocation()
{
    if (navigator.geolocation != null)
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
    else
        document.getElementById("map_canvas").innerHTML  = 'Browser does not support geoCoding';
}

function foundLocation(position)
{
    getAddress(new GLatLng(position.coords.latitude,position.coords.longitude));
}

function noLocation()
{
    document.getElementById("map_canvas").innerHTML  = 'Could not find location';
}
 
function getAddress(latlng) 
{
  if (latlng != null) 
  {
    geocoder.getLocations(latlng, showAddress);
  }
}

function showAddress(response) {
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } 
  else 
  {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    var locData = 
    '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
    '<b>Status Code:</b>' + response.Status.code + '<br>' +
    '<b>Status Request:</b>' + response.Status.request + '<br>' +
    '<b>Address:</b>' + place.address + '<br>' +
    '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
    '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode;
    document.getElementById("map_canvas").innerHTML  = locData;
  }
}

Wednesday, March 04, 2009

Consuming Blogger web-service using JSON

Blogger, which hosts my blog, started publishing its web-services using JSON in addition to the traditional XML type. I was intrigued by a Chris Coyier’s social home page and wanted to use it to learn about consuming JSON as well as create a similar “Social Home Page” for myself.

Chris Coyier’s sample site is an excellent starting point, as it uses 3 very basic web-services (Flickr, Twitter and ScrnShots) and in addition it uses JQuery to retrieve the JSON data and write it to the web-page. The first thing that I did to convert it into my own web-site was to retrieve my Flickr ID. The simplest way to do this is to use the idGettr page (I just could not find a page on Flickr from where I could retrieve my flickr id).

The Flickr web-service URL is: http://api.flickr.com/services/feeds/photos_public.gne?ids=YOUR_FLICKR_ID_HERE&lang=en-us&format=json&jsoncallback=? (The format query parameter tells Flickr to respond to your request using JSON).

The URL is provided as a parameter to JQuery’s $.getJSON method. In addition, you provide $.getJSON a method that is used to process the returned JSON.

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?ids=YOUR_FLICKR_ID&lang=en-us&format=json&jsoncallback=?", function(data){
      $.each(data.items, function(index, item){
        $("<img/>").attr("src", item.media.m).appendTo("#flickr")
              .wrap("<a href='" + item.link + "'></a>");});
    });

Using JQuery, makes it extremely easy to display the data on the web-page. In the above example, the JSON data is passed to the method, where the $.each iterator is used to iterate over each of the items in the JSON object. Another method, then processes the information in the item property and appends it to the div with class “flickr”. The code might seem very hard to understand at first, but if you download the example and step through it, it will make sense.

Next, I updated the twitter URL to point to my Twitter account. This too uses a scheme that is similar to how Flickr was consumed on this page.

Finally, I decided to get rid of the ScrnShots data on the page and instead use the new Blogger API that returns a JSON object. This took me a while as the API seems to be in beta and does not have a lot of documentation.

Here is how I did it.

For consuming the JSON version of the Blogger API, I decided to use a different approach (instead of using $.getJSON). This is the method that is documented on the Blogger blog and calls the web-service via the script element.

1. Create a method that will be used as the call-back method. I made my method extremely simple and all it does is, it captures the returned JSON object:

<script type="text/javascript" >
    var myBloggerJson = null;
    function handleJson(json) {myBloggerJson = json;}
</script>

2. Next call the web-service using the URL: http://YOUR_BLOGGER_BLOG_URL.blogspot.com/feeds/posts/default?alt=json-in-script&callback=handleJson. The important elements are the query parameter “alt” which is set to “jason-in-script”, which instructs blogger to return the data as a JSON object and the “callback” query-parameter, which holds the name of the method that will be called back with the JSON data.

<script type="text/javascript" src="http://BLOGGER_URL.blogspot.com/feeds/posts/default?alt=json-in-script&callback=handleJson"></script>

Important: the call-back method should be defined before the line where you include the script line which calls the blogger service. Otherwise, you will get an error.

In my example here, the handleJson method stores the returned JSON object in a variable called myBloggerJson.

3. Finally, I consume the Blogger JSON object using JQuery, using the following code:

$.each(myBloggerJson.feed.entry, function(index, entry){
           if (index < 8)
           {    $("#blogger").append('<div class="tweet"><p>' + "<a href='" + entry.link[4].href + "'>" +  entry.title.$t + "</a><br />" + '</p></div>');
           }
       }); 

If you look at the code, you will see that to be able to consume a JSON object, you need to know the structure of the JSON object. As this was my very first foray into using JSON and because the Blogger JSON structure is not documented, I had to figure the structure out manually. This was painfully slow as I was using the Visual Studio debugger and had to use the QuickWatch window to interrogate the object to determine its structure.

I later found out a much more easier way to determine the structure of the JSON object and this easier method uses a tool called a “JSON object inspector”. If you type in the URL to the web-service in your browser’s address bar, you will find that it returns a long string. If you copy this text and put it into the inspector you should be able to determine the structure of the JSON object. JSON Viewer, a CodePlex open source tool is one that is easy and robust to use. The following screen shot shows you the structure of the Blogger JSON structure.

image The important elements are: JSON-Object -feed --title ---$t : Blog title --entry ---entry[0]……..entry[n] : represent blog posts ------title : post title ------link : post links --------link[0]……link[4] : URLs to blog. [4] represents the friendly URL ------content : blog post content

If you now look at the code that consumes the Blogger JSON structure using JQuery, you will see that I post the latest 8 posts from my blog, using only the title, which is hyperlinked to the blog-post.

Check out the completed page at: http://www.aggregatedintelligence.com/Samples/MySocialPage/