Archive

Archive for the ‘javascript’ Category

How to create a link to Nintex Start Workflow Page in the document set home page

January 19, 2013 3 comments

In this blog post, I’d like to show you how to create a link to start Nintex Workflow Page in the document set home page.

1. Firstly, you need to upload the latest version of jQuery to the style library of your team site.


2. Then, upload a text file to the style library for writing your own html and JavaScript

3. In the document set home page, insert a new content editor web part and link the text file you just upload.

4. Update the text file with the following content, you can download this file here.

<script type="text/javascript" src="/Style%20Library/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="/_layouts/sp.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    listItemId=getParameterByName("ID");
	setTheWorkflowLink("YBBESTDocumentLibrary");
});
function buildWorkflowLink(webRelativeUrl,listId,itemId) 
{ 	
	var workflowLink =webRelativeUrl+"_layouts/NintexWorkflow/StartWorkflow.aspx?list="+listId+"&ID="+itemId+"&WorkflowName=Start Approval";
	return workflowLink;
}
function getParameterByName(name)
{
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.search);
	if(results == null){
		return "";
	}
	else{
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}

function setTheWorkflowLink(listName) 
{ 	
	var SPContext = new SP.ClientContext.get_current(); 
	web = SPContext.get_web(); 
	list = web.get_lists().getByTitle(listName); 
	SPContext.load(web,"ServerRelativeUrl"); 
	SPContext.load(list, 'Title', 'Id');	
	SPContext.executeQueryAsync(setTheWorkflowLink_Success, setTheWorkflowLink_Fail); 
}
function setTheWorkflowLink_Success(sender, args) 
{ 
	var listId = list.get_id(); 
	var listTitle = list.get_title(); 
	var webRelativeUrl = web.get_serverRelativeUrl();
	var startWorkflowLink=buildWorkflowLink(webRelativeUrl,listId,listItemId)
	$("a#submitLink").attr('href',startWorkflowLink);
}
function setTheWorkflowLink_Fail(sender, args) 
{
	alert("There is a problem setting up the submit exam approval link");
}
</script>
<a href="" target="_blank" id="submitLink"><span style="font-size:14pt">Start the approval process.</span></a> 

5. Save your changes and go to the document set Item, you will see the link is on the home page now.

Notes:

1. You can create a link to start the workflow using the following build dynamic string configuration:

{Common:WebUrl}/_layouts/NintexWorkflow/StartWorkflow.aspx?list={Common:ListID}&ID={ItemProperty:ID}&WorkflowName=workflowname.
With this link you will still need to click the start button, this is standard SharePoint behaviour and cannot be altered.

References:

http://connect.nintex.com/forums/27143/ShowThread.aspx

How to use html and JavaScript in Content Editor web part in SharePoint2010

How to use jQuery selectors in Asp.net

April 12, 2012 2 comments

In this post,I’d like to show you how to use jQuery selector in Asp.net.

//Attribute Ends With Selector [name$="value"]
var approveRadioButton = $('input[id$="RadioButtonApprove"]');
var reasonsDropdownlist = $('select[id$="ReasonsDropDownList"]');

References:

Selectors
jQuery VSDoc

Categories: javascript, jQuery Tags:

Create simple jQuery plugin

March 4, 2012 Leave a comment

In the last post, I have shown you how to add the function to jQuery. In this post, I will show you how to create plugin to achieve this.

1. You need to wrap your code in the following construct, this is because you should not use $ directly as $ is global variable, it could have clash with some other library which also use $.Basically, you can pass in jQuery object into the function, so that $ is made available inside the function. (JavaScript use function to create scope, so you can make sure $ is referred to jQuery inside the function )

(function($){   
//Your code goes here.
 };  
})(jQuery); 

2. Put your code into the construct above.

(function ($) {
    $.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    };
})(jQuery);  

3. Now you can reference the code into you project and you can call the method in you JavaScript

References:

Provides scope for variables

Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.

If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:

    (function() {
        var myProperty = "hello world";
        alert(myProperty);
    })();
alert(typeof(myProperty)); // undefined

How does an anonymous function in JavaScript work?

Building Your First jQuery Plugin

A Plugin Development Pattern

Categories: javascript, jQuery

How to retrieve the value of querystring from url using Javascript

March 2, 2012 Leave a comment

The following is a Javascript function I found on the internet , I keep here just in case I need to use it again.

function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

You can also add this method to jquery as below.

$.getParameterByName = function (name) {
            name = name.replace( /[\[]/ , "\\\[").replace( /[\]]/ , "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace( /\+/g , " "));
        };
        $(document).ready(function () {
            alert($.getParameterByName("id"));
        });

References:
http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript

http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

http://stackoverflow.com/questions/7541218/writing-jquery-static-util-methods

http://api.jquery.com/category/utilities/

Categories: javascript

Working with jqGrid and WCF service

July 20, 2009 2 comments

Today , I am going to show how to work with jqGrid with WCF in asp.net application. jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web.You can download a copy of the code from here

1. To start with , we need to download the latest version of jQuery and jqGrid plug-in. At the time of writing ,the latest version of jqGrid is jqGrid 3.5 beta. The major differences for this version is that starting with this version, jqGrid does not use a loader (which loads the needed files one by one), but all the needed code is contained in one file. The desired modules can be built using the jqGrid download manager . In order to use this, first a language file should be loaded and then the jqGrid file.

2. Next, you need to add JavaScript into your project and references using script tag. In order to use jqGrid 3.5, first a UI theme CSS file should be loaded. The detailed instruction is in the downloaded jqGrid zip file.Then,we need to create an AJAX-Enabled WCF Service in our asp.net web project. We need to create an method in the WCF service and add the following attributes to the method.

[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json
)]
public string GetProducts()
{
IList personList = ProductRepository.GetProducts();
int total = 1, page = 10;
ProductJqGridView productJqGridView = new ProductJqGridView(total, page, personList);
return productJqGridView.ToJson();
}

GetProducts method will return a list of products.After that I am instantiate ProductJqGridView object and call ToJson method to serialize the object into the correct JOSN format so that the jqGrid can consume it.

3. Before we looked the JavaScript ,we need to see what required in the markup. We need a table to display the data ,a div for the page navigation and button to load the data.Please see the source code for details.

4. Last, we are going to look at how to write JavaScript to bind the JSON data to the jqGrid.We use function as our datatype.The function we are using is getProducts which doing an AJAX call to the server and a JSON string is returned.In the successFunction we insert all the data into the jqGrid by calling thegrid.addJSONData.

function successFunction(jsondata) {
var thegrid = jQuery("#productGridView")[0];
thegrid.addJSONData(JSON.parse(jsondata.d));
}

function getProducts() {
$.ajax({
url: “linkification-ext” href=”http://DataLoader.svc/GetProducts” title=”Linkification: http://DataLoader.svc/GetProducts“>DataLoader.svc/GetProducts“,
data: “{}”, // For empty input data use “{}”,
dataType: “json”,
type: “POST”,
contentType: “application/json; charset=utf-8”,
success: successFunction
});
}
function dataBindToGrid() {
jQuery(“#productGridView”).jqGrid({
datatype: getProducts,
colNames: [‘ProductID’, ‘Name’, ‘ProductNumber’, ‘Color’, ‘Size’, ‘Style’],
colModel: [{ name: ‘ProductID’, index: ‘ProductID’, width: 200, align: ‘left’ },
{ name: ‘Name’, index: ‘Name’, width: 200, align: ‘left’ },
{ name: ‘ProductNumber’, index: ‘ProductNumber’, width: 200, align: ‘left’ },
{ name: ‘Color’, index: ‘Color’, width: 200, align: ‘left’ },
{ name: ‘Size’, index: ‘Size’, width: 200, align: ‘left’ },
{ name: ‘Style’, index: ‘Style’, width: 200, align: ‘left’ }
],
rowNum: 10,
rowList: [5, 10, 20, 50, 100],
sortname: ‘ProductID’,
pager: jQuery(‘#pageNavigation’),
sortorder: “desc”,
viewrecords: true
});
}
jQuery(document).ready(function() {
jQuery(“input#LoadData”).live(“click”, dataBindToGrid);
});

A word of caution…

This is only a simple example using jqGrid, many of its functionalities have not been implemented. Since this is only a “Hello World” like example, I will show some of its advanced functionalities in some other article.
Conclusion
The hardest part for using AJAX and jqGrid is not the concept but the level of JavaScript skills. To be able to write maintainable AJAX code, you need to learn JavaScript. I have created an article on my blog to help you learn JavaScript. Here is the link. I hope my examples can help people get started using jqGrid using WCF in an ASP.NET web application. Your feedback is much more appreciated.

kick it on DotNetKicks.com

Categories: .net, AJAX, javascript, jQuery, WCF

JavaScript 101

July 17, 2009 Leave a comment

This week in the company’s  mentoring session, I have talked about AJAX and JavaScript. Most of developers have awful experiences when working with JavaScript and think JavaScript is just a bunch of crap. However I think JavaScript is not a bunch of crap, it has good parts too.

The reason people finds JavaScript hard to work with are:
1. JavaScript is different language; you need to program in a different way
2. Limited IDE support for JavaScript
3. Lots of bad books on JavaScript
4. People do not put effort on learning how to program JavaScript

How we learn JavaScript?

To start with, go to read Douglas crockford’ javascript website and watch all the Video Tutorials below. It will convince you that JavaScript is good Language that worth your time and effort to learn.

Then you need some good books on JavaScript. My recommendation are : JavaScript: The Good Parts and JavaScript: The Definitive Guide

Finally,when you are programming in JavaScript you need always use jslint to QA your JavaScript Code. jslint is a code analysis to tool which help you to correct any mistakes and bad coding practices used in JavaScript.

Best practices when coding JavaScript

1. Avoid using Equal(==) and not equal(!=)

These operators can do type coercion(e.g. “”==false will evaluate to true )

It is better to use === and !==, which do not do type coercion.

2. Never use With statement in JavaScript

It is ambiguous.Please check this blog for details

3. Avoid using Eval statement in JavaScript

The only exception is when you parse JSON.However, you need to completely trust your server which you should not.

There are several JSON parser you can find in JSON

Most recent browser (at the time of writing IE8,FireFox 3.5,Chrome 3) support native JSON Parsing.For more info, Check here

4. The number type in JavaScript is 64-bit floating point (aka “Double”)

0.1+0.2!==0.3

0.1 + 0.2 = 0.30000000000000004

5. Style Isn’t Subjective

block{

}

Works well in JavaScript

block

{

}

Might work well in other languages but not in JavaScript.

Check this ppt slides for details.

6. Use jslint to QA your JavaScript.

Useful links

Video Tutorial

JavaScript: The Good Parts

http://google-code-updates.blogspot.com/2009/03/doug-crockford-javascript-good-parts.html

The JavaScript Programming Language

http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/

An Inconvenient API: The Theory of the Dom

http://yuiblog.com/blog/2006/10/20/video-crockford-domtheory/

http://www.yuiblog.com/blog/2007/01/24/video-crockford-tjpl/
http://yuiblog.com/blog/2006/11/27/video-crockford-advjs/

Advanced JavaScript

http://yuiblog.com/blog/2006/11/27/video-crockford-advjs/

JavaScript

http://www.crockford.com/

http://www.json.org/

Asp.net and jQuery

http://encosia.com/

http://west-wind.com/Weblog/default.aspx

http://mattberseth.com/blog/jquery/

http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/

kick it on DotNetKicks.com

Categories: javascript