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 & ClosejQuery 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&#MjQuery 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 FrameworkCascading 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
2. CSS @font-face
<link rel="stylesheet" href="print.css" type="text/css" media="print">This snippet allows authors to specify online custom fonts to display text on their webpages without using images:
3. HTML 5 CSS Reset
@font-face {
font-family: MyFontFamily;
src: url('http://');
}Richard Clark made a few adjustments to the original CSS reset released from Eric Meyers.
4. Unit PNG FixThis 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.7. PHP: Convert strings into clickable url
<?phpif (isset($username[5])) {?>
// Do something...
}This snippet is very useful to convert a string in a clickable link. I used this snippet for several tutorials;
8. jQuery: Ajax call
<? 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;
}
?>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 CollectionsThis 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 MenuSeveral 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 !
Using XMLHttpRequest and a Callback AJAX Example
You alread have a webserver installed. If you want to use the SAX Servlet as the backend for this tutorial then you need to have it compiled and deployed.
A big part of WEB 2 is of course AJAX which is asynchronous javascript and xml. We will breakdown an AJAX request down. A complete list of the code is available at the end of this page.
When you load the page the first thing that happens is the creation of an XMLHttpRequest object to handle the xml functions.
1. <html>
2. <head>
3. <script langua="javascript">
4. function new_XHR() {
5. var xhr;
6. try{
7. xhr = new ActiveXObject("Msxml2.XMLHTTP");
8. }catch(e){
9. try{
10. xhr = new ActiveXObject("Microsoft.XMLHTTP");
11. }catch(E){
12. xhr = false;
13. }
14. }
15. if(!xhr && typeof XMLHttpRequest != 'undefined'){
16. xhr = new XMLHttpRequest();
17. }
18. return xhr;
19. }What we are trying to do here, is instantiate an XMLHttpRequest object. As you can see I have not bothered to handle the error if the browser cannot instantiate an object.Now lets have a look at the actual HTML.
49. <body>
50. <form>
51. Name <input id="NameBox" type="text"/>
52. <a href="javascript:DoCallback()">Send the data without submitting the form</a>
53. </form>
54. <div id="MessagePane"/>
55. </body>
56. </html>
57.This shows a textbox and a URL. When you click on the URL it calls the javascript DoCallback function.
The XMLHTTP request
20.
21. var myxhr;
22. function DoCallback(){
23. myxhr = new_XHR();
24. myxhr.onreadystatechange=MyCallback;
25. myxhr.open('GET',"saxxmldemo_static.xml?"
26. +"name="+document.getElementById("NameBox").value);
27. myxhr.send(null);
28. }
29.This sets the callback function onreadystatechange=MyCallback. As you can see this is adding the value in the textbox to the URL. This really doesn't matter if you are using the saxxmldemo_static.xml as this is a static xml file. If you want to use the SAX Servlet example replace line 25 with
myxhr.open('GET', 'http://127.0.0.1:8080/SAXJHelloWorldServlet/saxxmldemo.xml?
This will point to the SAX Servlet which will echo the 'name'. Make sure you have the SAX Servlet example deployed and ready to go.The Callback
29.
30. function MyCallback(){
31. var name;
32. var message;
33. if(myxhr.readyState==4 && myxhr.status==200){
34. var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35. for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36. var node = subrootNode[0].childNodes[i];
37. if(node.tagName=="name")
38. name=node.firstChild.nodeValue;
39. else if(node.tagName=="message")
40. message=node.firstChild.nodeValue;
41. else{}
42. }
43. document.getElementById("MessagePane").innerHTML = "Hey "+name+" the server says \""+message+"\"";
44. }
45. }This is the function that gets called when the XMLHttpRequest object changes state i.e receives a response. As you can see on line 33, we are only interested in readyState=4 (document has loaded) and status 200 which means successful. You should have more error handling code here. You can use childNodes to drill down and extract the information or you can use getElementsByTagName(). The message is written to the html div with the id 'MessagePane' using innerHTML.
childNodes[n]
__childNodes[0] (.firstChild)
__childNodes[1]
____childNodes[0] (.firstChild)
____childNodes[1]
__childNodes[2]The xmldemo_static.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <user-data>
3. <name type="Alias">Doctor Octopus</name>
4. <message type="greeting">Hello there from the SAX servlet</message>
5. </user-data>Entire listing of index.html
1. <html>
2. <head>
3. <script langua="javascript">
4. function new_XHR() {
5. var xhr;
6. try{
7. xhr = new ActiveXObject("Msxml2.XMLHTTP");
8. }catch(e){
9. try{
10. xhr = new ActiveXObject("Microsoft.XMLHTTP");
11. }catch(E){
12. xhr = false;
13. }
14. }
15. if(!xhr && typeof XMLHttpRequest != 'undefined'){
16. xhr = new XMLHttpRequest();
17. }
18. return xhr;
19. }
20.
21. var myxhr;
22. function DoCallback(){
23. myxhr = new_XHR();
24. myxhr.onreadystatechange=MyCallback;
25. myxhr.open('GET',"http://127.0.0.1:8080/SAXJHelloWorldServlet/saxxmldemo.xml?"
26. +"name="+document.getElementById("NameBox").value);
27. myxhr.send(null);
28. }
29.
30. function MyCallback(){
31. var name;
32. var message;
33. if(myxhr.readyState==4 && myxhr.status==200){
34. var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35. for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36. var node = subrootNode[0].childNodes[i];
37. if(node.tagName=="name")
38. name=node.firstChild.nodeValue;
39. else if(node.tagName=="message")
40. message=node.firstChild.nodeValue;
41. else{}
42. }
43. document.getElementById("MessagePane").innerHTML =
44. "Hey "+name+" the server says \""+message+"\"";
45. }
46. }
47.
48. </script>
49. </head>
50. <body>
51. <form>
52. Name <input id="NameBox" type="text"/>
53. <a href="javascript:DoCallback()">Send the data without submitting the form</a>
54. </form>
55. <div id="MessagePane"/>
56. </body>
57. </html>If you have better solution, just tell me !
Collection of Form Validation
checkEmail()Next we want to see if the email address the user entered is real. The most effective way to do this is to go out on the Net and ask the domain the user claims to hail from if that the person actually has an account. But this takes a big toll on the machine that’s running the checks — and it isn’t possible with JavaScript anyway. With JavaScript we can check to see if the email string looks like an email address. We want it to follow this format: some characters, then an at symbol (@), then some more characters, then a dot (.), then two or three more characters, and that’s it. This won’t be perfect validation —it is possible to slip phony non-RFC-compliant addresses by it — but it’s normally good enough. If the pattern doesn’t match, we reject the email address.
The regular expression that expresses the format goes something like this: /^.+@.+\..{2,3}$/. The carat (^) means the start of the string and the dollar sign ($) means the end of the string. By surrounding the rest of the regular expression with these characters, we ensure that we evaluate the entire string, rather than just a portion. Each .+ means "at least one character" — the dot (.) means "any character"” and the plus sign (+), you recall, means "one or more." The .{2,3} portion means "two or three characters." And when we want to match a literal dot, we need to escape the character with a backslash. That’s why we have \. there.
var emailFilter=/^.+@.+\..{2,3,4,6}$/;
if (!(emailFilter.test(strng))) {
error = "Please enter a valid email address.\n";
}Again, we want to check to make sure that no forbidden characters have slipped in. For email addresses, we’re forbidding the following: ( ) < > [ ] , ; : \ / "
checkPhone()
var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
if (strng.match(illegalChars)) {
error = "The email address contains illegal characters.\n";
}To validate a phone number, first we want to clear out any spacer characters, such as parentheses, dashes, spaces, and dots. We can do this with a regular expression and the replace() method, replacing anything that matches our regular expression with a null string. Having done that, we look at what we have left with the isNaN() function (which checks to see if a given input is Not A Number), to test if it's an integer or not. If it contains anything other than digits, we reject it.
var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
//strip out acceptable non-numeric characters
if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.";
}Then we count the length of the number. It should have exactly ten digits — any more or less, and we reject it.
if (!(stripped.length == 10)) {
error = "The phone number is the wrong length.
Make sure you included an area code.\n";
}check Dropdown()
Finally, we want to make sure that the user has selected an option from our drop-down menu (and not the first option, which isn’t an option at all, but just a "Choose one" header). For this, we use the select object’s selectedIndex property, which returns the index of the selected option. If the index is 0, we reject the input.
checkRadio()
function checkDropdown(choice) {
var error = "";
if (choice == 0) {
error = "You didn't choose an option
from the drop-down list.\n";
}
return error;
}To make sure that a radio button has been chosen from a selection, we run through the array of radio buttons and count the number that have been checked. Rather than sending the whole radio object to a subfunction, which can be problematic (because the radio object has no property indicating which value has been chosen), we pre-process the radio form element in a for loop and send that result to a subfunction for evaluation.
for (i=0, n=theForm.radios.length; i<n; i++) {
if (theForm.radios[i].checked) {
var checkvalue = theForm.radios[i].value;
break;
}
}
why += checkRadio(checkvalue);
function checkRadio(checkvalue) {
var error = "";
if (!(checkvalue)) {
error = "Please check a radio button.\n";
}
return error;
}
checkWholeForm()A master function, called checkWholeForm() is placed at the top of the page that contains a form.
function checkWholeForm(theForm) {
var why = "";
why += checkEmail(theForm.email.value);
why += checkPhone(theForm.phone.value);
why += checkPassword(theForm.password.value);
why += checkUsername(theForm.username.value);
why += isEmpty(theForm.notempty.value);
why += isDifferent(theForm.different.value);
for (i=0, n=theForm.radios.length; i<n; i++) {
if (theForm.radios[i].checked) {
var checkvalue = theForm.radios[i].value;
break;
}
}
why += checkRadio(checkvalue);
why += checkDropdown(theForm.choose.selectedIndex);
if (why != "") {
alert(why);
return false;
}
return true;
}If you have better solution, just tell me !
HTML CheckBox Using Java Script
<html>
<head>
<title>DynAPI Examples - HTML CheckBox</title>
<script language="JavaScript" src="./dynapisrc/dynapi.js"></script>
<script language="Javascript">
dynapi.library.setPath('./dynapisrc/');
dynapi.library.include('dynapi.api');
dynapi.library.include('TemplateManager');
dynapi.library.include('HTMLCheckBox');
</script>
<script language="Javascript">
var tp = new Template('This is the Template:<center><form><table border="1" width="180"><tr><td align="center">Select an option below:<br>{@chk1}Kitchen {@chk2}Living Room</td></tr></table></form></center>',100,100,250,200,'#EEEEEE');
tp.addChild(new HTMLCheckBox(null,'kit',true),'chk1');
tp.addChild(new HTMLCheckBox(null,'lroom'),'chk2');
tp.chk2.addEventListener({
onclick:function(e){
var o=e.getSource();
alert('This is a Check Box with a value of "'+o.getValue()+'"');
}
});
dynapi.document.addChild(tp);
</script>
</head>
<body>
<script>
dynapi.document.insertAllChildren();
</script>
</body>
</html>If you have better solution, just tell me !
Generating a Unique Identifier for Each Page Instance
Sometimes there may be a need for identifying each page instance univocally. One ocasion may be, for example, if we want to store something in a session which is specific to a certain page.
What I did was override the Page class' ID property and have it return a unique value for a page that is kept throughout all postbacks. Here is my code:
publicoverride String ID{
get
{
String id = null;
if ((this.IsPostBack == true) && (String.IsNullOrEmpty(this.Context.Request.Form["__ID"]) == false)){
id = this.Context.Request.Form["__ID"];}
elseif (String.IsNullOrEmpty(this.Context.Items [ "__ID" ] as String) == false){
id = this.Context.Items [ "__ID" ] as String;}
else
{
id = Guid.NewGuid().ToString(); this.Context.Items [ "__ID" ] = id;}
return (id);}
}
protectedoverridevoid OnPreInit(EventArgs e){
this.ClientScript.RegisterHiddenField("__ID", this.ID); base.OnPreInit(e);}
If you have better solution, just tell me !
Using SPSiteDataQuery to whole site collection
Using the SPQuery class you can query one SharePoint list for items.
To set up a query across a whole site collection you can use the SPSiteDataQuery object.
The following method fetches all .doc files from all doclibs of the site collection and prints out a list of urls to those items.
public void TestSiteDataQuery()
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb("/"))
{
SPSiteDataQuery query = new SPSiteDataQuery();
// Search in doclibs only
query.Lists = "<Lists BaseType='1' />";
// Only .doc files
query.Query =
@"<Where>
<Eq>
<FieldRef Name='DocIcon' />
<Value Type='Computed'>doc</Value>
</Eq>
</Where>";
// Select only needed columns: file reference
query.ViewFields = "<FieldRef Name='FileRef' />";
// Search in all webs of the site collection
query.Webs = "<Webs Scope='SiteCollection' />";
// Perform the query
DataTable table = web.GetSiteData(query);
// Generate an absolute url for each document
foreach (DataRow row in table.Rows)
{
string relativeUrl =
row["FileRef"].ToString().Substring(
row["FileRef"].ToString().IndexOf("#") + 1);
string fullUrl = site.MakeFullUrl(relativeUrl);
// Write urls to console
Console.WriteLine(fullUrl);