Tuesday, 30 April 2013

Node.js



Dive into the sea

Node.js : You must have heard about this technology. Before you start knowing about Node.js, you need to know what is the difference between Node.js and existing traditional server-side scripting environments
(for example PHP, Ruby etc).


Asynchronous Programming


In Node.js, every function is asynchronous, that is ".... everything that would normally block the thread is instead executed in the background...". This is the most important thing you should keep in mind.

As of now, lets think of a function that writes to/read from a file system. You have to specify a callback function that is executed when the read operation has completed.

In a tutorial of net.tutsplus.com, I found this sentence "Node.js is only an environment; you have to do everything yourself". So as an end result we will get a high performance web application application. 

Little Info on Modules

Node.js, uses a module architecture, which helps to simplify the creation of complex web applications. Word "Modules" can be confusing sometimes, its nothing but like libraries in C. Which contains, related functions. Take the eample of http module, its will contains functions specific to HTTP.

To include a module , use require('path to module'), which will return the reference to the module specified.

ex : var cloudServer = require('cloud');

Scope of variables/functions in a module is mostly private, so that the variables and functions in a module is accessible only inside
the module. We can use exports keyword to make it accessible outside the module.

See the sample below












 Global Scope

The global scope in Node is GLOBAL (as opposed to window in the browser), its easy to create a global variable or function.Forget var keyword when you declare a function/variable, like this:
   
gVariable = 1000;
gFunction = function () { ... };

Global variables should be avoided whenever possible. So be careful and use var keyword when ever needed.


Same old "Hello World"

Yes, the same old "Hello World", which is everyone's first step in every programming language. If you feel it should not be "Hello World",try something new like "Hello Node" or "Hello Dear" or some "blah blah blah".

Create a file, my_first.js. Type in the code shown below,

console.log('Write what ever you need!!!');

Open the terminal/command line, navigate to the folder that contains my_first.js, and execute the following command:
   
node hello.js

You should see that "what ever written in the qutes" displayed in the console.

Now to Step Two

Lets do something advanced, don't worry, its simple. Look at the code, comments will give explanation.



Type the above code and save it as helloHttp.js. Type in following command to console,

node helloHttp.js

In your browser navigate to "http://localhost:8090". You will see the text "Hello HTTP!" in the page.


One more step , Three


Here is an example code which send a parameter with the request and receives a response,



Run the application through console, then go to your browser window, type in following url

http://localhost:8090/?name=Melvin. You will see the text "Welcome : Melvin" in the page.





Friday, 4 January 2013

Controls : Basic Controls used.

Hi, once again, hope all is well. Today lets talk about some basic controls in Titanium. Mainly I am focusing on
  1. Buttons
  2. Label
  3. Text Field & Text Areas
  4. Tab and Tabgroup

Buttons

A button has four states:
  1. Normal
  2. Disabled
  3. Focused (Android only, where navigation keys are present)
  4. Selected ( pressed )
You can specify background images for each state, as well as button text and a button icon.
Buttons style is an iOS only property , it will define appearance for each state, even if no button images are set by user.

Ti.UI.createButton is the method to create a button.

When it comes to android and mobile web, a button have default appearance. User will have to specify background image or background color of each state if they need to.

As I said, iOS buttons have two special properties,

  1. style
  2. systemButton.

style :  specifies the type of button decoration.Its value can be any one of the values in Titanium.UI.iPhone.SystemButtonStyle.

iOS doesn't supply any default background images for buttons and system button styles serve this purpose.

systemButton : lets user to create a predefined system-defined button,(ex: Camera/Add buttons,which can be used in toolbar and navbars.

According to the Appcelarator docs , system buttons may be used in the following locations:
  •  Toolbar(iOS).
  •  Popover. (iPad).
  •  SplitWindow.(iPad).
  •  TextField.
  •  TextArea.
  •  Window. 
Note :
systemButton property specifies oney appearance, not behavior.

See the example below



Label

Simply label can be defined as "A text label, with optional background image."

Ti.UI.createLabel is the method used to create a label.

Below is the example,


Text Field & Text Areas

Text field is a single line text field whereas Text areas are multiline text fields with editing and scrolling capabilities.

Ti.UI.createTextField is used to create text field and Ti.UI.createTextArea is used to create a text area.


 

Tab and Tabgroup

A tab group is a tabbed group of windows.

Ti.UI.createTabGroup method is used to create a tab group.

A tab group can contain one or more Tab objects.You can add tabs to the group using the method addTab,
and setActiveTab method is used to switch to a specific.

Refer the example shown below




You can refer to the Titanium Docs for both the controls, visit the links below,

Ti.UI.Tab

Ti.UI.TabGroup

Hope everyone enjoyed it, Will see you again.

Tuesday, 1 January 2013

Windows views and navigation.

Before we start


In this article, which is first among many in my "Titanium Learning Series", we will discuss about Windows and Views, also about navigation.One more thing to remind you is, the codes used in this article are developed and tested in android(will make updates after testing in IOS devices).Sorry, IOS guys for disappointing you,but there won't be much differences in code for IOS.

Window


Simply Window can be defined as , an empty drawing surface and a top-level container which can contains
other controls.Unlike other controls windows can be opened and closed. On opening a window, window and its child views to be added to the application render stack, that too on top of any previously opened windows.

On the other hand closing a window will removes windows itself and its children from the render stack.

Following are some specialized top-level views that can manage windows:
  1.     Navigation Group
  2.     Split Window
  3.     Tab Group.

To take up the entire screen, covering any other UI, specify , fullscreen : true when creating the window.

Otherwise windows will occupy the entire screen except for the navigation bar, status bar,tab bar ( when windows contained in tab groups).Ti.UI.createWindow is the method to create a window.

Find a sample code below  which create a simple window and add a label to it, which says 'A sample label':


 

Views

A view is an empty drawing surface (or container) created by the method Titanium.UI.createView.The View is the base type for all UI widgets in Titanium. Views can contain controls or other views and they have a set of properties (such as their background color, width,height) and set of events(such as single tap or touch, double tap,swipe etc).

app.js 



Common/firstView.js




























Common/detailedView.js
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A word before I finish

Don't forget to bookmark this page, as I may update this post in future.So to keep in touch, and wait for the next post.


Monday, 17 December 2012

My experiments with Titanium


During last few months I was working with Titanium, or rather studding it.It was a bit difficult in Initial days but now I am enjoying doing code in Titanium..Here, I'm going to present you a series of blogs about Titanium. I prefer calling this a discussion rather than a tutorial, as we got lot of genius guys are out there to create some brilliant tutorials.Any way shall we start?


Just a minute, before we start

I plan to write when I get enough time to test and write the sample codes.I prefer a better written post to a fast one.

So each post might be updated to add forgotten things or to fix issues.So to keep in touch don’t forget to bookmark it.

Every code provided will be licensed under the MIT license so you will be able to use it as you wish.


What you will need?
  1. You should know Java script
  2.  Some OOPs programming knowledge will be great. Don't worry we will study it on the fly, if you    don't    know.
  3.  To develop in android you will need android sdk(use any of your favorite os, Windows / Linux or Mac)
  4.  To develop in IOS you need a mac.
I think a getting started guide is not needed.There are good tutorials that shows you this. I don't want to repeat what's already out there.

You will have to forget something.

First of all DOM because there is no DOM in there.Here we have nothing from HTML applies here.

Also forget about using a library like  jQuery , JQM or some other popular libraries , because all these libraries are DOM oriented and are used to fight with multiple browsers.

What we will discuss here?

How to post Data to a Remote Server (Cross-domain) with jQuery in PhoneGap?

            Phone-gap is a tool , as you may know, for cross platform mobile application development.
For last some months i am playing with this tool. While this time I came across lot of issues. After some days of searching attempts I have managed to finish my app.

        I am here to discuss one specific issue I faced. "How to post Data to a Remote Server (Cross-domain) with jquery in Phone-Gap?". (I will come out with lot more about this in near future, for sure.!!!)

We have two options,

1. Call jquery ajax function like this,


 $.ajax({
            url:dataUrl,
            dataType: 'jsonp',
            success:function(response){
                //success call back
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                                //error call back
                        }
            }
    });


You may ask me what is "jsonp"? So here is a link you can look at , that was a post by Remy Sharp.

Yes!!!, You are right, if you choose this option you will have to change your back edn code too. You need to mould both your request and response to handle JSONP – and in doing so, you can have cross domain JSON requests.

Your server will need to return the response as JSON, but also wrap the response in the requested call back. Tough no?

So we can try next option if you don't need to do this.But still json is very easy to handle.

2. Before the ajax request call, just add this line of code


  $.support.cors = true;


that's it guys.

Phonegap v/s Titanium

Its always a common question what is the difference between Titanium and Phone gap.

At a long distance both appear to be similar. They both are cross-platform mobile development tools. Both requires use of JavaScript , HTML and other web technologies.Added to this both are Open Source Software.

Here is the endpoint of similarities of the both. Even though both the tools helps users to develop cross platform mobile applications the method of approach is different for both the platform. 

Phone gap


Within the native application, the UI consists of essentially a single screen that contains nothing but a web view that consumes all of the available space on the device’s screen.When application starts, it loads the start-up page of web application(typically index.html; can make changes inf a developer wants)into the web view and then passes control to the web view to allow the user to interact with the web application. As the user interacts with the application content links or JavaScript code within the application can load other content from within the resource files packaged with this application or can reach out to the network and pull content down from a web or application server. This is the story behind every phone gap application

By the way dear reader, if you are interested in the story  of "Phone gap" just have a trip through the following link 

Wikipedia Reference about Phone gap

Phone gap Official Website

Appcelerator Titanium

When you write an app using Titanium framework,you are writing a native application using JavaScript.Yes I mean it. Just note the keyword here, "native".

As I already said, you write a titanium application in JavaScript. Titanium takes this code, combines it with the Titanium API - this API is written in the native language of targeted device.At run time , it evaluates your code with a JavaScript interpreter (runs on the device operating systems.) A JavaScript execution is created in the native code and the JavaScript is injected as an inline object paired with native objects within the run time environment.This is the total picture behind the wall.

Find some useful links here, which will help you in moving forward

Appcelerator Homepage

Appcelerator Docs

Sunday, 11 March 2012

How to send a meeting request mail using asp.net

    
        

                      A very good day to all. Through this post I would like to give you information about "how to send a meeting request mail using asp.net" . I hope you all will have an experience of sending meeting request mail form outlook or other mail clients like thunder bird. So I think you, as a Microsoft lover and a .net programmer this post will be useful in some point of your programming life.

First of all for sending mail using a C# program you need to include the following lines in your code

using System.Net.Mail;
using System.Net;
using System.Net.Mime;


I have used an external library named DDay.iCal.dll I can create icalender object easily.
You can also download this from here. So you also have to include following lines too,


using DDay.iCal;
using DDay.iCal.Serialization.iCalendar;


These are the two among other lots of namespaces we have in the DDay.iCal.dll

So lets move on now. I am presenting the solution here as two small functions
 1.Create Attachment
 2.Send mail


        /// <summary>
        /// Creates the iCalender attachment from the data specified as the parameters.
        /// </summary>
        public void CreateAttachment(string from,string to,string title, DateTime startDate, string location, string organizer, bool updatePreviousEvent, int eventId, bool allDayEvent, int recurrenceDaysInterval)
        {
            iCalendar iCal = new iCalendar(); //New instance of the iCalendar object
            //Must include this line or you can not get this mail properly in Outlook 2003
            iCal.Method = "PUBLISH";
            Event evt = iCal.Create<Event>();
            evt.Summary = title;         
            evt.Start = new iCalDateTime(startDate.Year,startDate.Month, startDate.Day,      startDate.Hour,startDate.Minute, startDate.Second);
            evt.Location = location;
            if (recurrenceDaysInterval < 0) 
            {
                RecurrencePattern rp = new RecurrencePattern();
                rp.Frequency = FrequencyType.Daily;
                rp.Interval = recurrenceDaysInterval; // interval of days
            }
            evt.IsAllDay = allDayEvent;      
            if (!String.IsNullOrEmpty(organizer))
                evt.Organizer = new Organizer(organizer);
            if (eventId != null)
                evt.UID = eventId.ToString();
            if (updatePreviousEvent)
                iCal.Method = "REQUEST";
            iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            serializer.Serialize(iCal, @"iCalendar.ics");
            mailAttachment = serializer.SerializeToString(iCal);
                 //mailAttachment is a string which is globally declaered.
            Send(from, to, title, "", false); // Send function
        }


     NB : Passing variables in this fashion is not recommended. Declare a class "Event" and pass its object to
     the function.
   
      /// <summary>
      /// Sends an email
      /// </summary>
      public bool Send(string from, string to,string subject, string body)
        {           
            MailMessage mailMsg = new MailMessage();
            mailMsg.From = new MailAddress(from);
            mailMsg.Subject = subject;
            mailMsg.Body = body;
            mailMsg.IsBodyHtml = true;

            if (this.mailAttachment != null)
            {
                System.Net.Mail.Attachment attachment = System.Net.Mail.Attachment.CreateAttachmentFromString(mailAttachment, new ContentType("text/calendar"));
                //Use full qualified name because DDay.iCal.dll also contains a namespace Attachments.
        attachment.TransferEncoding = TransferEncoding.Base64;
                attachment.Name = "iCalendar.ics";
                mailMsg.Attachments.Add(attachment);
            }
            // Smtp configuration
            SmtpClient client = new SmtpClient();
            client.Credentials = new NetworkCredential(<mail username>,<mail password>);
            client.Port = <smtp port number> ;                
            client.Host = <smtp mail host> ;
           
            try
            {
                client.Send(mailMsg);
                return true;
            }
            catch (SmtpException smtpException)
            {
                throw smtpException;
            }       
        }


NB : Replace angle brackets content with the real data.
   
Hope this will help you. Happy programming!!!

You can refer a list of some common smtp mail host  here