Subscribe

Saturday 27 February 2010

WordPress And Javascript

This is going to be a short post and a bit off-topic yet I found it a quite interesting.
I have another blog using WordPress and I wanted to incorporate a page from my earlier web-site which gave user's the opportunity to listen to music online. The page is quite simple, it has a bunch of radio buttons with different radio station links and all you got to do is click on one of them and the javascript will take care of the rest.
Nifty isn't it, therefore I created a wordpress page and copied my HTML.Javascript onto that page. Easy..... unfortunately when I previewed the page it did not work, the page and the options showed all right yet the javascript refused to work. When I went back to check the code of my page, lo behold there were

tags all round my javascript lines and no way out.
A little research later realized that I have to put the javascript in a separate file and then link it with the page
Here is the example (assume my script is called radioScript.js)
<script type="text/javascript" src="/radioScript.js"></script>
That's it and now you can call any function written in the file. I have created the page and is online if you care to have a look at it please click here or go to http://best-news-site.com/radio-2
Very soon I will post again showing you how to create a simple widget for WordPress
See you, don't forget to subscribe to my feed for the latest updates

Friday 26 February 2010

How To Create Widgets Part3 RSS Feed



Hi there everybody, today's topic has been written about quite extensively and yet I have taken it up because of the way Yahoo Konfabulator handles it. Say for instance you have a favourite site maybe news or blog and while working on your desktop you would like to get the updates from this site quickly without having to install any third party software or toolbars etc.
With widgets this job becomes quite easy. First I will go into a bit of theory and then dive into the real coding part.


XMLHTTPRequest

To begin with we all know what can be done with this object called XMLHTTPRequest, unfortunately though, due to severe restrictions on cross domain request originating from the client side, it is impossible to have a standalone javascript. This object has to be used in conjunction to PHP or ASP.net sort of scripts.
Say I dont know PHP yet I want to have my news on my desktop.....?
Yahoo provides an object similar to the original XMLHTTPRequest but it is a standalone you do not require to understand or know the working of any server side script, Yahoo will take care of all that and more.
Lets see what Yahoo reference says about this object

"The  XMLHttpRequest  object is very much like the  URL  object that has existed in the Widget Engine since very early on.  XMLHttpRequest  is, however, a de facto standard for doing XML over HTTP in web browsers, so its addition here is to provide people with an easier migration path when moving AJAX code over to the Widget Engine, as well as simply trying to adhere to standards so developers find it more approachable."

A list of functions and attributes are provided here for reference

Attributes
XMLHttpRequest.autoRedirect
XMLHttpRequest.onreadystatechange
XMLHttpRequest.readyState
XMLHttpRequest.responseText
XMLHttpRequest.responseXML
XMLHttpRequest.status
XMLHttpRequest.statusText
XMLHttpRequest.timeout
Functions
XMLHttpRequest.abort()
XMLHttpRequest.getAllResponseHeaders()
XMLHttpRequest.getResponseHeader()
XMLHttpRequest.open()
XMLHttpRequest.send()
XMLHttpRequest.setRequestHeader()


Web



The web block in the XML file defines the initial placement and event handlers for an HTML rendering 
surface,




web objects can also be created and destroyed dynamically with the JavaScript engine.






In laymans term this this is the container where you can put all those pretty HTML codes, to make your widget look fab. If you are from a programming background it is quite similar to web browser object provided to you by VB.





Implementation

Lets build ourself a news feed,

News Feed To be used is http://feeds2.feedburner.com/NdtvNews-TopStories
We will bring the top news from my favourite news channel NDTV.

I want to refresh the feed every 12 hours
(To keep things simple in this post you are not allowed to change the widget preference, we will develop this concept further in later posts)

Firstly I will design my background which in this case is a simple semi-transparent black png of the size 400*300 pixel as shown below, if you are an accomplished designer please go nuts and do all the fancy things you ever wished for with your image editing software. I will stick to the basic.



Because most of this face will be covered by your web object we need someplace from where we can drag. Like the title bar of a window.(Objects inside the widget do not let you drag the window automatically). therefore I decided to make another image called winTitle to make it look like a window title bar


Lets just create window first nothing else


<?xml version="1.0" encoding="UTF-8"?>
<widget minimumVersion="4.5">
<window id="mainWin">
<name> RSS1</name>
<title>My First Widget</title>
<width>400</width>
<height>300</height>
<visible>true</visible>
<image>
<src>Resources/widget.png</src>
</image>
<image>
<src>Resources/wintitle.png</src>
<voffset>-1</voffset>
</image>
</window>

</widget>



As mentioned earlier it will just create window and do nothing.

Javascript Request

I will create a separate JS file called RssRead.js. One of the functions will be readRSS, which is the heart of this code.


function readRSS()
{
     xmlhttp=new XMLHttpRequest();
if (xmlhttp==null)
{
alert ("Something has gone wrong!");
return;
}
}


To begin we instantiate an object of the XMLHTTPRequest type and check if the object is not null if it is so then the function exits with a warning window

As we know that XMLHTTPRequest  gives us the chance of making an asynchronous call therefore we will define an anonymous function to handle the situation when our request returns.If complete the readyState is 4


xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{}
}



The response which is returned is an xml document and we can treat it so

xmldoc=xmlhttp.responseXML;

As we all know that RSS file structure is fixed and in XML thus making our life much easier, we will just read the elements that we want and ignore all the other. For more information on RSS File Structure click on the link


if (xmlhttp.status==200 && xmldoc!=null) //just to check for error or empty XML
{
      var titles=xmldoc.evaluate("rss/channel/item/title");//first line
      var links=xmldoc.evaluate("rss/channel/item/link");//second line
      var strAnswer=""
      for(var i = 0; i < titles.length; i++)
     {
strAnswer=strAnswer + "<a href='" + links.item(i).firstChild.data + "' target='_self' style='color:white; textDecoration:none'>;"+(i+1)+ " : " +titles.item(i).firstChild.data + "</a><br/>";
     }
}



The first line gets all the title elements, we are concerned with the headlines only not the description, we want to give the user a choice to read up on the headline he wants thus the link for that headline or title is required.
The second line gets all the links for the stories
As we all know only way to put a link is an HREF tag therefore I decided to create a string which will have the title inside an href tag with the corresponding link as the src. Simply run a loop for the number of titles in the array and use the variable as an index into the array of links.
This is for returning the value but we didnot make the real call yet so lets see that


xmlhttp.open("GET", "http://feeds2.feedburner.com/NdtvNews-TopStories", true)
xmlhttp.send(null)


most of it is easy except the last argument in the open function, if we make it false then the call will be synchronous but I want it to be async therefore I passed it a true value.

Thats about it..... wait what happened to the string we created with the links, We will find in the widget the object which will show the link, in my case it will be the web element with the id rss1

var result=widget.getElementById("rss1");
result.html=strAnswer;
the complete code is follows

function readRSS()
{

var timer=widget.getElementById("rss1timer");
if(timer!=null)
{
timer.ticking=false;

}
xmlhttp=new XMLHttpRequest();
if (xmlhttp==null)
{
alert ("Something has gone wrong!");
return;
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
xmldoc=xmlhttp.responseXML;
if (xmlhttp.status==200 && xmldoc!=null)
{
var titles=xmldoc.evaluate("rss/channel/item/title");
var links=xmldoc.evaluate("rss/channel/item/link");
var strAnswer=""
for(var i = 0; i < titles.length; i++)
{
strAnswer=strAnswer + "<a href='" + links.item(i).firstChild.data + "' target='_self' style='color:white; textDecoration:none'>;"+(i+1)+ " : " +titles.item(i).firstChild.data + "</a><br/>";
}
var result=widget.getElementById("rss1");
result.html=strAnswer;
timer.ticking=true;
}
else
{
result.html="An error has occurred";
}
}

}
xmlhttp.open("GET", "http://feeds2.feedburner.com/NdtvNews-TopStories", true)
xmlhttp.send(null)

}


Lets create the web object in our kon or widget file

<web id="rss1" >
<font>Times New Roman</font>
<size>14</size>
<voffset>29</voffset>
<hoffset>20</hoffset>
<width>380</width>
<height>280</height>
<bgcolor>#ffaa55</bgcolor>
</web>

Now to give our widget a nice title

<text style="font-size: 24px">
<data>NDTV Top News</data>
<hoffset>15</hoffset>
<voffset>15</voffset>
<size>16</size>
<color>#ff4499</color>

</text>

That is all we are done except one tiny winy timer issue. We wanted this widget to upgrade itself every 12 hour. To achieve that we put in a timer object with 12*60*60 as interval. When the timer reaches that interval the onTimerFired event is raised. we just call our main readRSS function.



<timer name="rss1timer1" id="rss1timer" ticking="true" interval="43200" onTimerFired="readRSS();"></timer>

lastly the onLoad event must be handled so as we call call our main function without any need for user intervention like a click etc.


<action>
<trigger>onLoad</trigger>
readRSS();
</action>

Thus our full program will be something like this


<?xml version="1.0" encoding="UTF-8"?>
<widget minimumVersion="4.5">

<script src="RssRead.js" charset="utf-8">



</script>

<window id="mainWin">
<name> RSS1</name>
<title>My First Widget</title>
<width>400</width>
<height>300</height>
<visible>true</visible>
<image>
<src>Resources/widget.png</src>
</image>
<image>
<src>Resources/wintitle.png</src>
<voffset>-1</voffset>
</image>
<text style="font-size: 24px">
<data>NDTV Top News</data>
<hoffset>15</hoffset>
<voffset>15</voffset>
<size>16</size>
<color>#ff4499</color>

</text>
<web id="rss1" >
<font>Times New Roman</font>
<size>14</size>
<voffset>29</voffset>
<hoffset>20</hoffset>
<width>380</width>
<height>280</height>
<bgcolor>#ffaa55</bgcolor>
</web>

</window>
<timer name="rss1timer1" id="rss1timer" ticking="true" onTimerFired="readRSS();" interval="43200"></timer>

<action>
<trigger>onLoad</trigger>
readRSS();
</action>
</widget>

Please don't forget to check my youtube videos. We will develop this concept further to bring in user preferences database, registry keys etc in my future posts.

Wednesday 24 February 2010

Widget Configurations


Hello there everybody, today I am going to talking about the configuration file for you widget under Yahoo Konfabulator.
Every widget may have few properties which are more to do with configuration rather than actual code or design. The best similarity which I can think of is the web.config file of .net appllications. To give you an idea the best example will be the icon which is showed on the yahoo dock for your widget and the icon showed on the security window when you run the widget for the first time.
The picture below shows an example of the window and the dock with a custom icon which I have created for a simple widget.

the second place where you will see this icon will be on the yahoo dock on your screen. The style and placement may differ according to your machine.

From version 4.0 onward the metadata or the data about your widget is stored in a separate file called widget.xml which should be placed with your kon file on the same path. This file deals with all the metadata elements of your widget. Lets start by looking at the simple structure of this file. Please remember this is an XML file thus all the rules of XML apply.
So metadata is the root element of this document, now I will show you how to put an icon in the Dock.
Yahoo specified that the icon to be shown in the dock must be 75*70 pixel. Thus i created the icon(png image) in photoshop shown below



As you can see my designing skills are nothing to be talked about you are free to use any style of designing you wish just remember the size. Now we place the icon reference in one of the elements called image with the usage attribute as dock eg
<img src="Resources/dockIcon.png" usage="dock" />
The widget automatically looks for this file and uses it if it is present.
If you want to give your widget a proper name with copyright notice and author name etc, again this file is the best place to put these informations

<?xml version="1.0" encoding="utf-8"?>
<metadata>
<version>1</version>

<name>ModernRSS</name>

<mage usage="dock" src="Resources/dockIcon.png"/>
<image usage="security" src="Resources/dockIcon.png"/>

<author name="Sudeep Mukherjee" organization="DigitalDreams" href="http://widgetsgadgetsworld.blogspot.com/"/>

<copyright>(c) 2010-2012 sudeep.</copyright>

<description>

A simple RSS news Widget
</description>

<platform minVersion="4.5" os="windows"/>

</metadata>

You can customize all these options according to your need.
Another interesting tit-bit you might be interested in is the debug option, say you are trying out your widget and would like an option to run the widget without actually closing it and loading it again and going through the security screen each time you do it. Or you want to have a look at some variables during the execution or see some special messages while the widget executes. We all developers from time to time use these kind of facilities provided by modern compilers and IDE's. Therefore Yahoo provides a debug mode for you. To switch on the debug mode make the following changes to your kon file or main widget file

<?xml version="1.0" encoding="UTF-8"?>
<widget minimumVersion="4.5">
<settings>

<setting name="debug" value="on"/>

      </settings>
</widget>


If you have any queries please send me comments or mails, and do not forget to check my you tube video for the same.



Monday 22 February 2010


Hello there everybody, This is the part 2 of the ongoing series of tutorials which deals with the creation of widgets using Yahoo Konfabulator SDK. In my last post I had a simple widget up and running unfortunately it does not do anything. In this video I will try to teach you the most simple way of reacting to events such as button click.
If you are from a programming background then you might expect a button click event but I am going to use the mouse down event instead. The problem with this approach is, if I use the mousedown event of the windows element in my kon file then anywhere you click this event will be fired. What I want is for this event to fire only when I click inside a button. Thus we will simplify our work by creating a separate graphics for the button and using the mousedown event of that object. Confused, don’t be let us see the original file used for the background


Let us say we want the star fish thing as our button. Instead of sweating by finding the co-ordinates etc, I will create a button1.png with the same image and overlay it on my window.

Let us review our original widget file





As I mentioned earlier I will just overlay this image on top of my background.



There you have it your first event driven widget. The important line is the image tag with the button1.png as the source and the onMouseDown event as a sub-element. If you are familiar with Javascript then you must immediately recognize the web scripting aspect of the program. Simple when the object is clicked we call the alert function of javascript with the message.
I would like to emphasize that this program is not meant to do anything except show you how to use events. Some people had requested me to show them how to add JavaScript code blocks. It is quite simple. As shown in the example below

On the top of the code we define script block, declare a function, this function is called when the button is clicked or onMouseDown event of that object.
Again this post was a simple way of adding events to your widget, in the next blog I will try to put in few more functionalities. If any of you is interested in gadgets drop me a line and I will put in a post and video about gadgets.
Do not forget to subscribe to my channel in you tube to get the most updated tutorials.

My First Widget

This will be my first foray into the world of widgets. I am more of a traditional programmer and I use javascript under extreme duress. Therefore I was never attracted toward the field of widgets or gadgets for that matter.
If you want to have a look as to what are widgets please visit this site http://widgets.yahoo.com/ .
Moving on to requirements for this kind of development

  1. Widget engine, Yahoo calls it Konfabulator. (don't ask me why, I have no idea). Get Yahoo SDK Download SDK . After the download just install it and you are ready to go
  2. The secondry requirement is a good text editor, Yahoo uses XML and javascript to design widgets thus, I would suggest finding a good XML and Javascript editor. If you are confused please download the visual studio free edition, i think it will be sufficient for your requirements. On this point I am open to suggestions. 
  3. Download the reference manual from the Yahoo site. Click here to download a zip which has the manual in pdf format .
  4. Image editor, you will need a good image editor to design your widget backgrounds and the UI in general thus please buy or get an image editor which is as good as Gimp or Photoshop. The following list has been provided by my readers thus I have no idea how good these softwares are but I know that these are free.








    Beside these software's you need to have basic understanding of XML and Javascript. These tutorials will not try to teach you either of these two subjects. 
    The main file which is executed has an extension of kon. This you say is like the exe file under the windows environment. The kon file is not a standalone exe but a file which is used by the konfublator. Once the Konfabulator engine is installed on your system as soon as you double click on any kon file the engine will start and the file will be executed. All these steps will be outline in my video tommorow on the you tube. If you have any questions feel free to drop me a line

    Creating the background
    For your widget lets build a small background graphic file. I am not trying to create anything complicated to begin with thus the background file will be an image of 200*200 pixels. The base color is transparent thus it will not obstruct anything and there are three- four shapes. The name of the file is back1.png






    Creating the program

    Lets fire up our favourite text editor and create a file called helloworld.kon. The basic syntax is like a xml file. therefore it must start with the following line just like an XML file










    These files have the basic element as Therefore let us create the basic skeleton of the file












    Every widget element must have a window element inside it therefore we must define a window which would be the visible portion of your widget. As we all know every window must have a name, title, height and width in the same way we must define these attributes. Again it is upto to you if you want these as attributes of the window element or child of window element. Personally I prefer the latter.








    As you can see we have defined all the properties the last property that we must add is the image property which will show the background of the window. Lets put in the image element.










    One important point is the files should be in the same path, because we cannot be sure as to the file system of the user thus if you save your widget in a folder called mywidgets then save the image either there or make a sub-directory such as images or resources to save the image files.




    As is customary there must be a hello world message somewhere, thus lets put in the text, in yahoo widget this is also an element called text and attributes like data, color,font etc.


















    By default the text will be printed on the extreme left i.e 0,0 position. If we want to move the text we must give the voffset and hoffset values. Basically these values will move the text vertically and horizontally from the 0,0 position by the amount of pixels you specify. I have placed the text 100 pixels down and 50 pixels to the right. Lets save this and try to execute it. If everything has been installed properly and the file has been written properly, your Desktop should show this message


    Click on the use widget button and the desktop should show something like this. Please be advised I have drawn the black rectangle to emphasize the window. 

    There you have it, your first widget, if you want to close it just left click on it and choose close widget.
    Tomorrow I will show you how to  put some functionality in this widget, hopefully I will have a video ready too.


Watch the video
 
EatonWeb Blog Directory