PHP script example, Ajax upload

While the upload via XMLHttpRequest is not possible are there many examples and tutorials to upload file via some "virtual IFRAME".
In this quick tutorial we will show how-to create such an Ajax upload form using the jQuery Form plug-in and our easy upload class.The system is very simple, build your upload form just like normal. In place of posting the form to the script you use some JavaScript code to post the data to some PHP script in the background.


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">

$(document).ready(function() {
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
var options = {
beforeSubmit: showRequest,
success: showResponse,
url: 'upload4jquery.php', // your upload script
dataType: 'json'
};
$('#Form1').submit(function() {
document.getElementById('message').innerHTML = '';
$(this).ajaxSubmit(options);
return false;
});
});

function showRequest(formData, jqForm, options) {
var fileToUploadValue = $('input[@name=fileToUpload]').fieldValue();
if (!fileToUploadValue[0]) {
document.getElementById('message').innerHTML = 'Please select a file.';
return false;
}

return true;
}

function showResponse(data, statusText) {
if (statusText == 'success') {
if (data.img != '') {
document.getElementById('result').innerHTML = '<img src="/upload/thumb/'+data.img+'" />';
document.getElementById('message').innerHTML = data.error;
} else {
document.getElementById('message').innerHTML = data.error;
}
} else {
document.getElementById('message').innerHTML = 'Unknown error!';
}
}

</script>

Next create a PHP script named "upload4jquery.php" and place it in the same directory where other files are located. Place this code into that new file:


<?php
include($_SERVER['DOCUMENT_ROOT'].'/classes/upload/foto_upload_script.php');

$foto_upload = new Foto_upload;

$json['size'] = $_POST['MAX_FILE_SIZE'];
$json['img'] = '';

$foto_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->foto_folder = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->thumb_folder = $_SERVER['DOCUMENT_ROOT']."/upload/thumb/";
$foto_upload->extensions = array(".jpg", ".gif", ".png");
$foto_upload->language = "en";
$foto_upload->x_max_size = 480;
$foto_upload->y_max_size = 360;
$foto_upload->x_max_thumb_size = 120;
$foto_upload->y_max_thumb_size = 120;

$foto_upload->the_temp_file = $_FILES['fileToUpload']['tmp_name'];
$foto_upload->the_file = $_FILES['fileToUpload']['name'];
$foto_upload->http_error = $_FILES['fileToUpload']['error'];
$foto_upload->rename_file = true;

if ($foto_upload->upload()) {
$foto_upload->process_image(false, true, true, 80);
$json['img'] = $foto_upload->file_copy;
}

$json['error'] = strip_tags($foto_upload->show_error_string());
echo json_encode($json);
?>
This tutorial or guide is not about how to use the easy upload class. If you never used the class before try the example files first and than start with this Ajax upload form.

Paths and upload directories

You need to create some upload directories (2 one for the upload and one for the thumbs) and check the permission (chmod the upload directory with 777). If you use the same structure as suggested in the class file you don't need to change the include at the top from the PHP script.

Now we need the form HTML and some other containers where the response data is placed.

<form id="Form1" name="Form1" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
Select an image from your hard disk:

<div>
<input type="file" name="fileToUpload" id="fileToUpload" size="18" />
<input type="Submit" value="Submit" id="buttonForm" />
</div>
</form>
<img id="loading" src="loading.gif" style="display:none;" />

<p id="message">

<p id="result">

jquery ajax error handling

How to handle ajax errors using jQuery ?

jQuery is the most awesome javascript library that made easy for asynchronous ajax calls.it has global ajax function and some pre defined ajax functions like $.get, $.post, load .etc. but we don’t find any error messages by default with this library. we can see the errors with firefox’s addon firebug or with IE developer toolbar.So we manage most common ajax errors in our application with global ajaxSetup function which come with jQuery by default. We can set many options,to see available ajaxsetup options.

most ajax errors we get errors are server response errors and some JSON parse errors. To know more about the HTTP errors details please check here. To test this error handling just copy and paste it to your head section of HTML document.

Javascript Code for setting global error handling.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$().ready(function(){
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
In the above example we handle following common error and show response text for other rare errors.

  • 0-xhr status ,is it initialized or not that means user is offline.

  • 404-page not found

  • 500-Internel Server error.

  • request timeout – jQuery custom error.

  • parseerror-jQuery custom error when parsing JSON data.

  • we just throw other errors with response error

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 !

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 !

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>
Hide line numbers

If you have better solution, just tell me !

SP Web Application Get Central Administration

With this code you can get the central administration webapplication.


   1:  private static SPWebApplication GetCentralAdministrationWebApplication()
   2:  {
   3:      SPWebService cS = SPWebService.ContentService;
   4:      var service = cS.Farm.Services.GetValue<SPWebService>("WSS_Administration");
   5:      SPWebApplicationCollection webApplications = service.WebApplications;
   6:      foreach (SPWebApplication webApplication in webApplications)
   7:      {
   8:          return webApplication;
   9:      }
  10:      return null;
  11:  }


If you have better solution, just tell me !

Collection Of using SPSiteDataQuery in whole site

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);
}
}
}
}

If you have better solution, just tell me !

Get URL parameters & Using jQuery

In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:

http://www.example.com/?
me=myValue&name2=SomeOtherValue

Calling getUrlVars() function would return you the following array:

{
"me" : "myValue",
"name2" : "SomeOtherValue"
}

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];
// To get the second parameter
var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:


$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});

Now you can use it in the following way:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');

If you have better solution, just tell me !

To Check whether to see a string is empty

There are several ways to check a string to see if it’s empty. However, you should try to always use the following method. It’s faster, and uses less resources. This may seem like a minimal piece of code -

string strAmIEmpty = "";

if (strAmIEmpty.Length == 0)

{

// empty so do something

}


But if you were checking strings through out your application, it all adds up in the end.

If you have better solution, just tell me !

Lookup fields and event lists - JQuery and SharePoint

JQuery to change the width of a mulitvalued lookup field in SharePoint and to hide the Workspace field in an event list.

The script to change the width of multivalued lookup fields:



<script type="text/javascript">
$(document).ready(function()
{
$("select[id*='<INSERT_YOUR_FIELDNAME>']").parent().width(300);
$("select[id*='<INSERT_YOUR_FIELDNAME>']").parent().height(200);
$("select[id*='<INSERT_YOUR_FIELDNAME>']").width(300);
});
</script>

The script to hide the workspace checkbox in an event list:

This first bit of script hides the ‘Workspace’checkbox in the NewForm and the EditForm. The script to hide the workspace field from the DispForm.aspx:


<script type="text/javascript">
$(document).ready(function()
{
$("a[name='SPBookmark_WorkspaceLink']").parent().parent().parent().hide();
});
</script>


<script type="text/javascript">
$(document).ready(function()
{
$("a[name='SPBookmark_WorkspaceLink']").parent().parent().parent().hide();
});
</script>

There are several ways to add the script to the pages. For the Lookup fields I used the I descibe in this blog post. For the Event list, I created custom EditForm, NewForm and DispForm pages and added the script to those pages directly.


If you have better solution, just tell me !

Select Options Sorting and dropdown Using jQuery

There are probably a dozen ways to skin this cat, but this is how I did it (I was already using jQuery on this site):


// get the select
var $dd = $('#select-id');
if ($dd.length > 0) { // make sure we found the select we were looking for

// save the selected value
var selectedVal = $dd.val();

// get the options and loop through them
var $options = $('option', $dd);
var arrVals = [];
$options.each(function(){
// push each option value and text into an array
arrVals.push({
val: $(this).val(),
text: $(this).text()
});
});

// sort the array by the value (change val to text to sort by text instead)
arrVals.sort(function(a, b){
return a.val - b.val;
});

// loop through the sorted array and set the text/values to the options
for (var i = 0, l = arrVals.length; i < l; i++) {
$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
}

// set the selected value back
$dd.val(selectedVal);
}

The above code will only work if the option values are numbers. If the values are alphanumeric and we are doing an alphabetical sort, then the sort function should be replaced with:


arrVals.sort(function(a, b){
if(a.val>b.val){
return 1;
}
else if (a.val==b.val){
return 0;
}
else {
return -1;
}
});

If you have better solution, just tell me !

How To Change the Default EditForm, NewForm and DispForm

Problem

You’ve developed some custom new, edit and display application pages that are stored in the _layouts directory. Let’s assume the filenames are newform.aspx, dispform.aspx and editform.aspx. You now want to change the properties of your custom list so that any new, edit or display requests point to your custom pages.
If you open up your site within SharePoint Designer and expand the Lists folder, from there you can access the properties of that custom list by right clicking on it and selecting Properties. Once the List Properties pane is open, click on the Supporting Files tab.



You’ll see there that you can actually choose what display, edit and new forms you want your list to be using. So if you’ve developed something custom, you would click Browse…, point to your new location and select the file. Here is where it starts to fail, I am only able to browse within the site itself and cannot navigate to my _layouts directory to select the files I mentioned above.

Solution

I suspected this was a limitation of the SharePoint Designer UI and not actually a limitation of the Object Model. I did a bit of fiddling with my SPList object and was not able to find anything that let me change those properties. If you look at the screenshot above, there is a key piece of information that’ll make the light turn on (at least it did for me). The Supporting Files tab has a drop down selector for the Content type specific forms. If you think about that a moment, you’ll remember that ALL lists within SharePoint inherit from a default content type.


So armed with that knowledge, I created an SPContentType object and took a look at it’s properties and methods. Sure enough, there are 3 properties I can set to change these forms: EditFormUrl, NewFormUrl and DisplayFormUrl. Here is some sample code I used to change the forms for my custom list called ‘My List’ that inherits from the Item content type:

So in the example code above, I had to determine what default content type my list inherited from. In this case it was the Item content type.
So in the example code above, I had to determine what default content type my list inherited from. In this case it was the Item content type.

NOTE:

If you need to change the content type directly, you can definitely do that, however, I did a bit of testing and found that any lists ALREADY inheriting from that content type did not pickup my changes to the form locations. Any NEW list that I created that was inheriting from that content type did pickup the changes. In order for me to change the form locations for the existing list I had to use the code above. For reference, here is how you would change the content type directly. The code has only a subtle difference.

1
2
3
4
5
6
7
8
9
10
11
SPWeb web = SPContext.Current.Web;

web.AllowUnsafeUpdates = true;

SPContentType ct = web.ContentTypes["Name Of Your Content Type"];

ct.EditFormUrl = "_layouts/editform.aspx";
ct.NewFormUrl = "_layouts/newform.aspx";
ct.DisplayFormUrl = "_layouts/dispform.aspx";

ct.Update();

As always, any questions, let me know!

SuperLoad jQuery Plugin

This plugin adds the ability to update multiple elements with a single Ajax response.

Usage
$.superLoad( options );

The options are the same as taken by the jQuery.ajax( ) method, with
the following observations:
dataType: defaults to 'html'
success: will be called after the content is updated on the page.

Expected response format:

<div class="ajax-response">

<div class="ajax-content" title="!update #div1">
<p>
Anything inside this div will be used to update the #div1 element
like $('#div1').html( $(thisDiv).html() );
</p>
</div>

<div class="ajax-content" title="!appendTo #div2">
<p>
Anything inside this div will be appended to the #div2 element
like $('#div2').append( $(thisDiv).html() );
</p>
</div>

<div class="ajax-content" title="!prependTo #div3">
<p>
Anything inside this div will be prepended to the #div3 element
like $('#div3').prepend( $(thisDiv).html() );
</p>
</div>

<div class="ajax-content" title="#div4">
<p>
if the !command is not given, !update will be assumed
</p>
</div>

<div class="ajax-content" title="!replaceWith #div5">
<p>
Replaces #div5 with this P element
</p>
</div>

<script>
//each script tag will be evaluated after the content has been applied.
doStuff();
</script>

<script>
doOtherStuff();
</script>

</div>
The title attribute: 
  • The ajax-content element's title attribute is used to determine what to do with the content:
  • The format is: "!command selector"
  • "!command": defaults to !update
  • !update: replaces the inner HTML of the selected element(s) with the inner HTML of the ajax-content
  • !prependTo: adds the inner HTML of the ajax-content to the top of the inner HTML of the selected element(s)
  • !appendTo: adds the inner HTML of the ajax-content to the bottom of the inner HTML of the selected element(s)
  • !other: Beyond the above 3 standard !commands, one can also simply pass the name of any valid jQuery command (default of from a plugin) as long as the command is able to be applied to the selected element(s) and takes the new content as its argument.

Ajax Progress Bar Control

Published a ProgressBar AjaxToolKit control



View live demo

<!-- Continuous Mode / 150px wide -->
<mb:ProgressControl ID="ProgressControl1" runat="server" Mode="Continuous" Width="150px" />
<!-- Manual Mode / 70px wide -->
<mb:ProgressControl ID="ProgressControl12" runat="server" Mode="Manual" Width="70px" />

Modifing behavior control from UI Client using JQuery:

Play continous control $find('ProgressControl1').play();

Stop continous control $find('ProgressControl1').stop();

Set Percentage value control $find('ProgressControl1').set_percentage(62);

Increment percentage value control $find('ProgressControl1').set_percentage('+15');

The progressbar control support skins.

;">

If you have better solution, just tell me !

JQuery and JSON Web Service

Use JQuery to consume JSON Web Services is a lightweight method, for increment performance in your website.

If you want call a JSON Web Service from your javascript code, you should : use HTTP POST and content-type "application/json; charset=utf-8″. Asp.Net Ajax make this for you transparently.

$(document).loadMyContent(function() {
$.ajax({
type: "POST",
url: "myService.asmx/GetMyContent",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#myDiv').html(msg.d);
}
});
});

Insert javascript code after content for best performance.

JQuery Pluggins

JQuery Pluggins is a mechanism for adding in methods and functionality. You can found a lot of available pluggins. Read more about pluggin developing.

A simple example :

jQuery.fn.mypluggin = function() {
return this.each(function(){
alert(this);
});
};
Using our developped pluggin : $("div p").mypluggin ();

Combining javascript file

howto combine javascript files in 3.5 and 4.0.

<asp:ScriptManager runat="server">
<CompositeScript>
<Scripts>
<asp:ScriptReference Name="WebForms.js" Assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
/>
<
asp:ScriptReference Name="MicrosoftAjaxWebForms.js" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<asp:ScriptReference Name="MicrosoftAjax.js" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</Scripts
>
</CompositeScript>
</asp:ScriptManager>
In 4.0 <asp:ScriptManager runat="server" EnableCdn="true"/>

If you have better solution, just tell me !


How to Add a ToolTip to the Telerik Ajax RadEditor

This one was not immediately obvious to me so I’m posting the solution here. I’m using a Telerik Ajax RadEditor on my page as follows:

<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolsFile="ToolsFile.xml">
</telerik:RadEditor>
 

Now, after doing a bit of inspection, I discovered there was a property I could set on the RadEditor called ToolTip that seemed to just require a string value as follows:

 

<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolTip="Some message to the user" ToolsFile="ToolsFile.xml">
</telerik:RadEditor>

I assumed this would produce exactly what I needed. Unfortunately, after testing the above out, I got nothing, no tool tip. Doing a search on the forums turned up nothing useful, not even an explanation as to what the ToolTip property was really for. However, I did come across an entirely separate control in the Ajax suite of controls called RadToolTip.

That’s clever I thought, perhaps I’ll just give that a go. I was hoping there would be some sort of property I would set that would allow me to specify what control to tie this tool tip to. Guess what! There is! My final solution was as follows:

<telerik:RadToolTip ID="rttNotes" runat="server" TargetControlID="rhfNotes" Text="Some message to user"></telerik:RadToolTip>
<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolsFile="ToolsFile.xml">
</telerik:RadEditor>

There you have it. I haven’t played around with all the properties and options I have available to me with the RadToolTip, but I’m sure there are some useful ones in there!

If you have better solution, just tell me !

Code Translation for .NET (C#<->VB.NET)

This service will translate the code for you, just start typing the code or upload a file to convert it.

For now it only supports from VB.NET to C# and from C# to VB.NET.

VB.NET to C# and from C# to VB.NET Click Here

To use it you can either:

  1. Start typing your code.
  2. Copy and Paste the code in the Code Text Box.
  3. Translate an entire file using the file upload.
Disclaimer:

No copy is done whatsoever of the code that you either type, or upload for translation. Everything is processed in the server in memory and returned immediately to the browser.