Mobile application development using jQuery Mobile, RequireJS and BackboneJS



You will build a simple sample application step by step, learning how to:

Modularize the application using BackboneJS,jQuery Mobile and RequireJS;
Use Backbone View, Collection/Model and Routers.
Decouple the mobile view and model/collection using Backbone events.

More details: Source

Delete item from SharePoint List

In my previous post SharePoint List C# Part 1 I discussed how we can add items to SharePoint list. We also have to delete items from a list. Following C# code can be used in your custom webpart or feature to delete item from SharePoint list. Here I am going to find the items to delete using CAML query.




public void DeleteListItem(){



string strUrl = "http://merdev-moss:5050/testsite";

SPSite site = new SPSite(strUrl);

SPWeb web = site.OpenWeb();



SPList list = web.Lists["Tasks"];

SPListItemCollection itemCollection;



SPQuery oQuery = new SPQuery();

oQuery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>ABC</Value></Eq></Where>";

itemCollection = list.GetItems(oQuery);



List<SPListItem> valuesToDelete = new List<SPListItem>();



foreach (SPListItem item in itemCollection){

if (item != null){

try{

valuesToDelete.Add(item);

}

catch (Exception e){

Console.Write(e.ToString());

}

}

}

web.AllowUnsafeUpdates = true;

foreach (SPListItem itm in valuesToDelete){

itm.Delete();

}

list.Update();

web.AllowUnsafeUpdates = false;

In the above example I have use a CAML query to delete items in the Task list which title equal to ABC. As above you have to maintain separate list to stote items that you are goint to delete, otherwise it will not work.

Sort Object ArrayList in C#

You can easily sort an arraylist using its “sort()” method, but how can you sort an ArrayList of Objects? You can get this task done very easily with “IComparer” Interface.

As an example let’s get a “Person” object which contains two attributes called “ID” and “Name”. Now we need to sort these objects by “ID” or “Name”. By looking at the following picture, you can get very clear idea about what we are going to do now.


You may notice in “Sort 2” first I have sort by “ID” and then by “Name”. I’ll give you the C# code for the above task using simple console application.

Create new class called "Person" and paste this code;


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortArrayList{
class Person {
private int id;
public int ID{
get { return id; }
set { id = value; }
}
private string name;
public string Name{
get { return name; }
set { name = value; }
}

public int CompareTo(Person psn2, ObjCompare.ComparisonType comparisonType, Person psn1){

int returnValue;

if (comparisonType == ObjCompare.ComparisonType.ID){

if (psn1.ID == psn2.ID){
returnValue = Name.CompareTo(psn2.Name);
}
else{
returnValue = ID.CompareTo(psn2.ID);
}
}

else if (comparisonType == ObjCompare.ComparisonType.Name){
returnValue = Name.CompareTo(psn2.Name);

}
else{
returnValue = ID.CompareTo(psn2.ID);
}

return returnValue;
}
}
}

Create new class called "ObjCompare" and paste this code;


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList{

class ObjCompare : IComparer{
public enum ComparisonType{
ID, Name
}
private ComparisonType compMethod;
public ComparisonType ComparisonMethod{
get { return compMethod; }
set { compMethod = value; }
}
public int Compare(object x, object y){
Person psn1 = (Person)x;
Person psn2 = (Person)y;
return psn1.CompareTo(psn2, ComparisonMethod, psn1);
}
}
}

Now update your "Programme.cs" as bellow;



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList{
class Program{
static void Main(string[] args){

ArrayList lst = new ArrayList();

Person psn = new Person();
psn.Name = "Jack"; psn.ID = 15;
lst.Add(psn);

Person psn1 = new Person();
psn1.Name = "David"; psn1.ID = 18;
lst.Add(psn1);

Person psn2 = new Person();
psn2.Name = "Daniel"; psn2.ID = 12;
lst.Add(psn2);

Person psn3 = new Person();
psn3.Name = "Owen"; psn3.ID = 20;
lst.Add(psn3);

Person psn4 = new Person();
psn4.Name = "Colin"; psn4.ID = 16;
lst.Add(psn4);

Person psn5 = new Person();
psn5.Name = "Aiden"; psn5.ID = 18;
lst.Add(psn5);

Console.Write(" ---before sort --- \n");
foreach (Person item in lst) {
int id = item.ID;
string ttl = item.Name;
Console.Write(id + " " + ttl + "\n");
}
/* sorting */
ObjCompare objcom = new ObjCompare();
objcom.ComparisonMethod = ObjCompare.ComparisonType.ID;
lst.Sort(objcom);

Console.Write(" ---after sort -- \n");
foreach (Person item in lst) {
int id = item.ID;
string ttl = item.Name;
Console.Write(id + " " + ttl + "\n");
}
}
}
}

You will get the output as "Sort 2" in the picture. If you don't want to sort by "Name" you can do it by editing "Person" class. There I have check whether "psn1.ID == psn2.ID", by commenting that part you can get the result as "Sort 1".

If you have better solution, just tell me !

Building jQuery Tabs That Open & Close

Building jQuery Tabs That Open & Close

jQuery is obviously a really powerful tool. If you’ve done any work with it, you don’t need convincing. My latest project involving jQuery was a bit tricky because I couldn’t find anything that detailed how to generate a tab once a user clicked on a link, and then how to close that tab if the user clicked the close button. Here is my setup:

I needed to create a page with some static links, that when clicked on would spawn a new tab.

The content area for each tab would contain a Close button that would remove the tab and hide the div contents. I didn’t want the div contents removed because I wanted users to be able to open the tabs again if they wanted to.


<div id="mytabs">
<ul>
<li><a href="#tabs-home">My Projects Home</a></li>
</ul>
<div id="tabs-home">
<h3>Welcome to My Projects Home</h3>
<p><a href="#" onclick="showTab('myActiveProjects', 'My Active Projects')">My Active Projects</a></p>
<p><a href="#" onclick="showTab('mySalesActivities', 'My Sales Activities')">My Sales Activities</a></p>
</div>
</div>
<div id="tabs-myActiveProjects" style="display:none;">
<h3>My Active Projects</h3>
<p><input type="button" name="killTab" value="Close" onclick="hideTab('myActiveProjects')" /></p>
</div>
<div id="tabs-mySalesActivities" style="display:none;">
<h3>My Sales Activities</h3>
<p><input type="button" name="killTab" value="Close" onclick="hideTab('mySalesActivities')" /></p>
</div>

Wiring Up The Javascript


function init()
{
$("#mytabs").tabs();
}

function showTab(tabID, tabName)
{
currentTabID = tabID;

// this will add a tab via the standard method
$("#mytabs").tabs("add","#tabs-" + tabID, tabName);
$("#tabs-" + tabID).css("display","block");

$("#mytabs").tabs('select', tabID);
}

function hideTab(tabID)
{
$("#tabs-" + tabID).css("display","none");
$("a[href^=#tabs-"+ tabID +"]").parent().remove();
$("#mytabs").tabs('select', 0);
}

$(document).ready(init);

Don’t forget to include the jQuery UI JS file and the corresponding CSS. You’ll also need to include the jQuery JS file as well. If you have any troubles with this, drop me a note.


<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.7.2.custom.min.js"></script>
<link type="text/css" href="styles/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />

My next step with the above is to relocate the Close button so that it is an ‘X’ image on the tab itself that when clicked on would close the tab. I’ll update once I figure that out! Good times!


If you have better solution, just tell me !

Password generator using JavaScript / jQuery

The aim is to increase cyber and internet security awareness among surfers. Google and others are joining the move. So I thought I would write a post regarding internet security to add my 2 cents. In this post you will find JavaScript function that generates random passwords of any length as well as jQuery version.



JavaScript Password Generator


$.extend({
password: function (length, special) {
var iteration = 0;
var password = "";
var randomNumber;
if(special == undefined){
var special = false;
}
while(iteration < length){
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if(!special){
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
}
iteration++;
password += String.fromCharCode(randomNumber);
}
return password;
}
});

This function takes two parameters: integer value for password length and optional boolean value true if you want to include special characters in your generated passwords.

Examples of generated passwords


password(8);

// Outputs: Yrc7TxX3

password(12, true);
//Outputs: C}4_ege!P&#M


jQuery password generator



$.extend({
password: function (length, special) {
var iteration = 0;
var password = "";
var randomNumber;
if(special == undefined){
var special = false;
}
while(iteration < length){
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if(!special){
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
}
iteration++;
password += String.fromCharCode(randomNumber);
}
return password;
}
});

// How to use
$.password(8);
$.password(12, true);

If you have better solution, just tell me !

10 Useful code snippets for web developers

In this post I want to suggest you 10 useful code snippets for web developers based on some frequetly asked questions I received in the past months for my readers. This collection include several CSS, PHP, HTML, Ajax and jQuery snippets.


1. CSS Print Framework

Cascading Style Sheets Framework for web printing. To use this framework download the CSS file here and use this line of code into your web pages


<link rel="stylesheet" href="print.css" type="text/css" media="print">

2. CSS @font-face

This snippet allows authors to specify online custom fonts to display text on their webpages without using images:




@font-face {
font-family: MyFontFamily;
src: url('http://');
}

3. HTML 5 CSS Reset

Richard Clark made a few adjustments to the original CSS reset released from Eric Meyers.


4. Unit PNG Fix

This snippet fixes the png 24 bit transparency with Internet Explorer


5. Tab Bar with rounded corners
This code illustrates how to implement a simple tab bar with rounded corners:



6. PHP: Use isset() instead of strlen()

This snippet uses isset() instead strlen() to verify a PHP variable (in this example $username) is set and is at least six characters long.




<?php

if (isset($username[5])) {

// Do something...

}
?>

7. PHP: Convert strings into clickable url

This snippet is very useful to convert a string in a clickable link. I used this snippet for several tutorials;



<? php

function convertToURL($text) {

$text = preg_replace("/([a-zA-Z]+:\/\/[a-z0-9\_\.\-]+"."[a-z]{2,6}[a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href=\"$1\" target=\"_blank\">$1</a>", $text);

$text = preg_replace("/[^a-z]+[^:\/\/](www\."."[^\.]+[\w][\.\/][a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href="\\" target="\">$1</a>", $text);

$text = preg_replace("/([\s\,\>])([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-z" . "A-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})" . "([A-Za-z0-9\!\?\@\#\$\%\^\&\*\(\)\_\-\=\+]*)" . "([\s\.\,\<])/i", "$1<a href=\"mailto:$2$3\">$2</a>$4",

$text);

return $text;

}

?>

8. jQuery: Ajax call

This is the most simple way to implement an Ajax call using jQuery. Change formId and inputFieldId with the ID of the form and input field you have to submit:

9. CSS Layouts Collections

This page contains a collection of over 300 grids and CSS layout ready to use in your projects. Take a look, it's very useful.


10. Simple versatile multilevel navigation Menu

Several months ago I found this simple code (HTML + CSS + JavaScript for jQuery) to implement a versatile multilevel navigation menu (please send me the original source if you find it!). I think it's the simpler and faster way to do that. The result is something like this:


The only thing you have to do is to create nested lists into a main list with id="nav", in this way:



<ul id="nav">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a>
<ul>
<li><a href="#">Link 3.1</a></li>
<li><a href="#">Link 3.2</a></li>
<ul>

</li>


</ul>


...and use this basic CSS code (you have to modify it to customize the layout of this menu with the style of your site!



#nav, #nav ul{margin:0;
padding:0;
list-style-type:none;
list-style-position:outside;
position:relative;
line-height:26px;
}
#nav a:link,
#nav a:active,
#nav a:visited{
display:block;
color:#FFF;
text-decoration:none;
background:#444;
height:26px;
line-height:26px;
padding:0 6px;
margin-right:1px;
}
#nav a:hover{
background:#0066FF;
color:#FFF;
}
#nav li{
float:left;

position:relative;
}
#nav ul {
position:absolute;
width:12em;
top:26px;
display:none;
}
#nav li ul a{
width:12em;
float:left;
}
#nav ul ul{
width:12em;
top:auto;
}
#nav li ul ul {margin:0 0 0 13em;}
#nav li:hover ul ul,
#nav li:hover ul ul ul,
#nav li:hover ul ul ul ul{display:none;}
#nav li:hover ul,
#nav li li:hover ul,
#nav li li li:hover ul,
#nav li li li li:hover ul{display:block;}



...and this is the JavaScript code for jQuery you have to copy in the tag <head> of the pages that use this menu:


<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function showmenu(){
$("#nav li").hover(function(){
$(this).find('ul:first').css({visibility:"visible", display:"none"}).show();

}, function(){
$(this).find('ul:first').css({visibility:"hidden"});
});
}





$(document).ready(function(){
showmenu();
});
</script>

If you have better solution, just tell me !

Use XMLHttpRequest or ActiveX equivalent to create an xml request object

Use XMLHttpRequest or ActiveX equivalent to create an xml request object. Request a single page and alert the results to the browser.





<html>
<
head></head>

<
body>
<
script language="javascript">
var xmlhttp = false;

// If XMLHttpRequest function does not exist (certain versions of IE,
// or if native XMLHTTP support is disabled under the security settings),
// create it to return the activex equivalent.
if(!window.XMLHttpRequest) {
window.XMLHttpRequest = function() {
// For maximum compatibility, try all versions.
var xml_versions=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
for(var x = 0;x < xml_versions.length; x++) {
try {
return new ActiveXObject(xml_versions[x]);
} catch (e) {}
}
return false;
}
}

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}

if(xmlhttp) {
/* .readyState = 0 Uninitialized
.readyState = 1 open() Called
.readyState = 2 send() Called
.readyState = 3 recieving data, .responseText holds partial data in FF
.readyState = 4 data finished
*/
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
alert("RESPONSE HEADERS:\n\n" + xmlhttp.getAllResponseHeaders());
alert("STATUS:\n\n" + xmlhttp.status);
alert("RESPONSE TEXT:\n\n" + xmlhttp.responseText);
}
}

xmlhttp.open("GET", "/?var1=val1&var2=val2");
xmlhttp.send(null);

/* If you want to POST data to recieve_data.php instead
var post_data = 'var1=' + encodeURIComponent('asj$@#&&?') + '&var2=val2';
xmlhttp.open("POST", "recieve_data.php");
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('Content-length', post_data.length);
xmlhttp.send(post_data);
*/
}
</
script>

</
body>
</
html>

If you have better solution, just tell me !