Tuesday, January 26, 2010

AJAX Using JQuery Tutorial

You may know that, JQuery is a JavaScript library that we can do smart things using small pease of code. This free and open source JavaScript Library has become the most famous JavaScript Library today because of its Lightweight, Cross-browser and CSS3 Compliant.

Using JQuery we can do thing like Document Navigating, DOM Element Selecting, Creating Animations, Event Handling and Ajax Development very easily. You can learn more about JQuery from JQuery web site.

What this post about ?

This is about a thing that we mostly want when we design web sites. I'm going to discuss how we can get that work done better and smarter using JQuery AJAX. Look at the following picture which describes the whole task, we are going to do.

Just imaging that the above picture is the structure of our web site, when we click on the links at "C", we want to load different contents to the main div in "B". If we use different web pages for all those links and load them when user clicks on a link, we are loading the content on "A" and "C" unnecessarily. That is why we should use AJAX to load the content.

First, download the following example code that I'm going to describe.

Download Source Code(Password : sara)

Open the "index.html" file in your browser and check the result by clicking links "Home", "About" and "Contact Us" on "C". Ignore the problem with last link, I'll explane that later. Now open the "index.html" using a text editor. Then you will see a code like following in the <head> </head> section.

<script src="jquery-1.3.1.min.js" type="text/javascript" ></script>

That is how you can link the JQuey to your web site, it's the same way you link a JavaScript file. Then check the following peace of code.

$(document).ready(function() { 

    //$("#main").load("home.html");
 
    $("#link1").click(function(){
        $("#main").load("home.html");
    });
 
    $("#link2").click(function(){
        $.ajax({
            url: "about.html",
            cache: true,
            beforeSend: function(){
                $("#main").slideUp("fast");
            },
            success: function(html){
                $("#main").slideDown("slow");
                $("#main").html(html);
            }
        });
    });
 
    $("#link3").click(function(){
        $.post("boo.php",  { link_id:"link3" },
        function(data){
            $("#main").html(data);
        }); 
    }); 
 
});

In JQuery we are writing events inside $(document).ready function. In the above code I have given different IDs to links and call functions when they are clicked. There I have used three different ways to get the above task done.

First look at the 5th line, there I have load the "home.html" file inside the main div when click the "Home" link (id is "link1"). That is the easiest way to do a AJAX request. Then check the 9th line. There I have load the "about.html" file inside the main div when click the "About" link (id is "link2"). This method can be used to decorate our request using effects. As above code you can use beforeSend and success functions to get that work done.

If I uncomment the 3rd line, "home.html" page will load to main div in the page load. Finally check the 23rd line, this is different than above mentioned methods. Here I have get the data in a PHP file. I have call the "boo.php" file using POST method and display the result inside main div when "Contact Us" (id is "link3") clicked. Now I think you may noticed that AJAX is simple if you use JQuery.

Tuesday, January 5, 2010

Embed a Picture to Body of Gmail Message

In this post I’m going to show you how to embed a picture to body of the message in Gmail without attaching. To get this work done you have to enable Image Inserting in Google Labs. Let’s see how we can enable this.

First log in to your account and go to Settings as following picture;

Then go to Labs section and there you can find Inserting Images. Enable the feature and save the settings. See the following screen shots to more clarifications.

If you have new interface you can directly go to Lab as follows.



Now you can see new icon in tool bar, using that we can embed images to body of the message as following picture.


This is a simple thing that most people dose not aware.

Monday, December 28, 2009

ADD|Update|Delete Item SharePoint Web Services


In one of my previous article I discussed how we can retrieve data in a SharePoint List Using its Web Services. In this post I’m going to discuss how we can update a SharePoint list using Web Services. Please refer my previous article on "SharePoint List Web Service GetListItems" to learn how to add Web References to your project. Then you can use the following sample codes to Update SharePoint lists.

Updating Existing Items

In the following code I have update the "Tasks" list, there I have update the title of two items which has the ID 7 and 10.
    public void updateListItemsWS()
    {
        WS_Lists.Lists myservice = new WS_Lists.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://mermoss:5050/testsara/_vti_bin/Lists.asmx";
        try
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

            elBatch.SetAttribute("OnError", "Continue");
            elBatch.SetAttribute("ListVersion", "1");

            string strBatch = "<Method ID='1' Cmd='Update'>" +
                  "<Field Name='ID'>7</Field>" +
                  "<Field Name='Title'>Sara1</Field></Method>" +
                  "<Method ID='2' Cmd='Update'><Field Name='ID' >10</Field>" +
                  "<Field Name='Title'>Sara2</Field></Method>";

            elBatch.InnerXml = strBatch;
            myservice.UpdateListItems("Tasks", elBatch);

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
Delete Items

To delete item, use following phrase in the above code, this will delete the item which has ID of 10.

string strBatch = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>10</Field></Method>";

Add New Item

To add item, use following phrase in the above code,

string strBatch = "<Method ID='1' Cmd='New'>" +
"<Field Name='ID'>New</Field>"+
"<Field Name='Title'>TestTitle1</Field>"+
"</Method>";

Thursday, December 17, 2009

SharePoint List Web Service GetListItems


In this post, I’ going to discuss how we can retrieve data from a SharePoint List using its Web Services. First to know about SharePoint Web Services please refer this. We can user List Web Service which provides methods for working with SharePoint Lists, Content Types, List Items, and Files to read a List. Here we are going to use GetListItems method.

To use the above method we should know the GUIDs of the target list and view. Please follow my article on SharePoint List GUIDs to see how we can get them.

This is how you can Add Web Reference; I’ll get created Web Site Project in Visual studio to illustrate. Actually it is simple, first click on Add Web Reference and give the URL to the Web Service.





This is a sample code to read SharePoint list,
    public void getListData()
    {
        WS_Lists.Lists myservice = new WS_Lists.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://merdev-moss:5050/testsara/_vti_bin/Lists.asmx";
        try
        {
            /* Assign values to pass the GetListItems method*/
            string listName = "{5C65CB1A-2E1B-488A-AC07-B115CD0FC647}";
            string viewName = "{75E689B4-5773-43CB-8324-58E42E1EB885}";
            string rowLimit = "100";

            // Instantiate an XmlDocument object
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

            /*Use CAML query*/
            query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
            "<Value Type=\"Counter\">0</Value></Gt></Where>";
            viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
            queryOptions.InnerXml = "";

            System.Xml.XmlNode nodes = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, null, null);

            foreach (System.Xml.XmlNode node in nodes)
            {
                if (node.Name == "rs:data")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "z:row")
                        {
                            Response.Write(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
In the above code I have use CAML queries to get the result. It will return all the result because I’m searching for Items which has ID greater than 0. It is always true. If you want to know how to write CAML quires easily please refer my article on CAML & SPQuery in SharePoint.

Wednesday, December 16, 2009

SharePoint List GUIDs, How to Find?


In this post I’m going to discuss about an easiest way to find GUID of a SharePoint list and a View. If you are using the MOSS 2007 there is straight forward way to get the List GUID, these are the steps.

1. Access the list via your browser.

2. Go to Settings --> List Settings and right-click on the "Information management policy settings" links and choose Copy Shortcut.

3. Paste the URL and you can see the GUID surrounded with "{" and "}".

If you are using WSS 3.0 follow these steps, you can use this method to find the View GUID in MOSS 2007

1. Access the list via your browser and select the View you want to find the GUID.

2. Select "Modify this View" and copy the URL.

3 You will get a URL like this,

http://mysite:5050/testsara/_layouts/ViewEdit.aspx?List=%7B5C65CB1A%2D2E1B%2D488A%2DAC07%2DB115CD0FC647%7D&View=%7B75E689B4%2D5773%2D43CB%2D8324%2D58E42E1EB885%7D&Source=http%253A%252F%252Fmysite%253A5050%252Ftestsara%252FLists%252FTasks%252FAllItems%252Easpx

There you can find,

List=%7B5C65CB1A%2D2E1B%2D488A%2DAC07%2DB115CD0FC647%7D
View=%7B75E689B4%2D5773%2D43CB%2D8324%2D58E42E1EB885%7D

Replace "%7B" with "{"
Replace all "%2D" with "-"
Replace "%7D" with "}"

You are now left with the GUIDs, in the above example;

List ID is {5C65CB1A-2E1B-488A-AC07-B115CD0FC647}
View ID is {75E689B4-5773-43CB-8324-58E42E1EB885}

You can use SharePoint Tips Utility Pack if you need to get the GUID of List columns. There in menu bar, select "List Management --> Change Field Settings" and load your site.

Thursday, December 10, 2009

Add User To SharePoint Group Programmatically


Let’s see how we can programmatically add a user to existing SharePoint user group . You can use the following method which has two string parameters, one for group name and other for user login name for get the above task done.
public void addUserToGroup(string groupName, string userLoginName)
{
    string strUrl = "http://mysite:5050/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser spUser = web.EnsureUser[userLoginName];

                if (spUser != null)
                {
                    SPGroup spGroup = web.Groups[groupName];
                    if (spGroup != null)
                    spGroup.AddUser(spUser);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}
Here you should provide the login name in correct format (DomainName\UserName). For example you can call this method like follow,

addUserToGroup("Test Group", "SA\\saranga.rathnayaka");

Wednesday, December 9, 2009

Add Item To List With LookUp Column Programmatically


In my previous posts on "Working With SharePoint List" I have discussed how we can Read, Add and Update SharePoint List. If you have to add new Item to a list which has lookup column, you have to follow a different procedure.

If you look at the following figure, you can easily understand what I'm going to do. I'm going to add a new record to List_B, which has a lookup column from List_A's Title Field.



This is a sample code to get the above task done,
        
    public void addToLookUp()
    {
        /* open the web */
        SPSite site = new SPSite("http://merdev-moss:5050/testsara");
        SPWeb web = site.OpenWeb();

        string targetList = "List_B";
        string sourceList = "List_A";
        string sourceListField = "Title";

        /* we are going to add new row to List_B,
        * It (List_B) has a lookup column called "A_Column",
        * It (A_Column) get data from Title field of List_A.
        * (List_A has value called "test2" in Title field)
        */

        SPListItemCollection listItems = web.Lists[targetList].Items;
        SPListItem item = listItems.Add();
        item["Title"] = "New Title";
        int ID = get_ID(web, sourceList, sourceListField, "test2");
        if (ID != 0)
            item["A_Column"] = ID;
        item.Update();
    }

    public static int get_ID(SPWeb web, string list, string field, string itemname)
    {
        int id = 0;
        SPList sharedDocumentList = web.ServerRelativeUrl.Equals("/") ? web.GetList(web.ServerRelativeUrl + list) : web.GetList(web.ServerRelativeUrl + "/" + list);
        SPListItemCollection listItems = sharedDocumentList.Items;
        foreach (SPListItem item in listItems)
        {
            if (item[field].ToString() == itemname.ToString())
                id = item.ID;
            break;
        }
        return (id);
    }

Tuesday, December 8, 2009

Create SharePoint List View Programmatically


In this post I’m going to describe how you can programmatically add a view to SharePoint list or Document Library. You can get this work done by using SPViewCollection.Add Method (Microsoft.SharePoint), here is a sample code,
        public void createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "Test View";

            System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
            viewFields.Add("Title");
            viewFields.Add("Priority");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }
Above code creates a view in the collection with the specified name "Test View" and added view fields. Query string will return all items, because always ID is greater than 0. Row limit is 100 and the view displays items page by page. Last Boolean mean it is not the default view.

Please refer my article on CAML & SPQuery in SharePoint to find out easy way to write CAML quires used in above code.

Add View Using Existing View

You also can create new List View with the help of existing one, this sample code will create new View which has another field using above created View.
        public void _createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "New Test View";

            System.Collections.Specialized.StringCollection viewFields = list.Views["Test View"].ViewFields.ToStringCollection();
            viewFields.Add("Status");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }

Add Permission Level To SharePoint User Group


In this post I'm going to discuss how you can add a permission level (Read, Contribute, Full Control, etc) to a SharePoint user group. Here is a sample code,
        public void addPermissionToGroup()
        {
            SPSite site = new SPSite("http://mysite:5050/");
            SPWeb spWeb = site.OpenWeb();
            string permissionName = "Read";
            string groupName = "Project Manager";

            try
            {
                spWeb.AllowUnsafeUpdates = true;
                SPRoleAssignment roleAssignment = new SPRoleAssignment(spWeb.SiteGroups[groupName]);
                roleAssignment.RoleDefinitionBindings.Add(spWeb.RoleDefinitions[permissionName]);

                if (!spWeb.HasUniqueRoleAssignments)
                    spWeb.BreakRoleInheritance(false);

                spWeb.RoleAssignments.Add(roleAssignment);
                spWeb.Update();
            }
            catch (Exception _exception)
            {
                throw _exception;
            }
            finally
            {
                spWeb.AllowUnsafeUpdates = false;
            }
        }
You can view RoleDefinitions defined for your site by visiting to Site Settings --> Advanced Permissions.

Wednesday, December 2, 2009

Add Menu Bar To Blogger Blog


I was able to add a nice multilevel dropdown menu to my blog. In this post I’m going to discuss how you also can add it to your blogger blog. Here I’m using pure CSS multilevel menu generated by Free CSS Drop Down Menu Generator.



You can’t use the code directly in blogger without some modifications; I’ll describe how you can edit the code to use it in blogger to get a menu bar like above picture (Figure 1).

Create the Menu

First get the following code and save it as .html file. Then edit the styles and links as you want. If you like this style, you only need add links for menus and sub menus.

Note : If you use the above mentioned Menu Generator in the HTML code you must replace "<![if gt IE 6]></a><![endif]>" using "<!--[if gt IE 6]><!--></a><!--<![endif]-->", otherwise it will not work in the Blogger.

View Code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
ul.cssMenu ul{display:none}
ul.cssMenu li:hover>ul{display:block}
ul.cssMenu ul{position: absolute;left:-1px;top:98%;}
ul.cssMenu ul ul{position: absolute;left:98%;top:-2px;}
ul.cssMenu,ul.cssMenu ul{
 margin:0px;
 list-style:none;
 padding:0px 2px 2px 0px;
 background-color:#d8d8d8;}
ul.cssMenu table {border-collapse:collapse}ul.cssMenu {
 display:block;
 zoom:1;
 float: left;}
ul.cssMenu ul{
 border-left:2px solid #444444;
 border-bottom:1px solid #444444;
 border-right:1px solid #444444;
 border-top:0px;
 z-index:9999;}
ul.cssMenu li{
 display:block;
 margin:2px 0px 0px 2px;
 font-size:0px;}
ul.cssMenu a:active, ul.cssMenu a:focus {outline-style:none;}
ul.cssMenu a, ul.cssMenu li.dis a:hover, ul.cssMenu li.sep a:hover {
 display:block;
 vertical-align:middle;
 background-color:#d8d8d8;
 text-align:left;
 text-decoration:none;
 padding:4px;
 _padding-left:0;
 font:normal 11px Verdana;
 color: #444444;
 text-decoration:none;
 cursor:default;}
ul.cssMenu span{
 overflow:hidden;
 font-weight:bold;
 background-position:right center;
 background-repeat: no-repeat;
 padding-right:11px;}
ul.cssMenu li {    float:left;}
ul.cssMenu ul li {float:none;}
ul.cssMenu ul a {
 text-align:left;
 white-space:nowrap;}
ul.cssMenu li.sep{
 text-align:center;
 padding:0px;
 line-height:0;
 height:100%;}
ul.cssMenu li.sep span{
 float:none;    
 padding-right:0;
 width:5;
 height:16;
 display:inline-block;
 background-color:#AAAAAA;    
 background-image:none;}
ul.cssMenu ul li.sep span{width:80%;height:3;}
ul.cssMenu li:hover{position:relative;}
ul.cssMenu li:hover>a{
 background-color:#eeeeee;
 font:normal 11px Verdana;
 color: #000000;
 text-decoration:none;}
ul.cssMenu li a:hover{
 position:relative;
 background-color:#eeeeee;
 font:normal 11px Verdana;
 color: #000000;
 text-decoration:none;}
ul.cssMenu li.dis a {color: #AAAAAA !important;}
ul.cssMenu img {border: none;float:left;_float:none;margin-right:4px;width:16px;height:16px;}
ul.cssMenu a:hover ul,ul.cssMenu a:hover a:hover ul,ul.cssMenu a:hover a:hover a:hover ul{display:block}
ul.cssMenu a:hover ul ul,ul.cssMenu a:hover a:hover ul ul{display:none}
</style>
</head>
<body>
<ul class="cssMenu">
 <li><a href="#" title="test title"><span>SEO</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul>
   <li><a href="#" title="test title">Your Site in Google</a></li>
   <li><a href="#" title="test title">Selecting Good Title</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
 <li><a href="#" title="test title"><span>Blogger Tips</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul class="cssMenum">
   <li><a href="#" title="test title">Expandable Blogger Posts</a></li>
   <li><a href="#" title="test title">Blogger Title Tip</a></li>
   <li><a href="#" title="test title">Adding META Tags</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
 <li><a href="#" title="test title"><span>SharePoint</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul class="cssMenum">
   <li><a href="#" title="test title">What is SharePoint</a></li>
   <li><a href="#" title="test title"><span>Create Custom Features</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
    <ul class="cssMenum">
     <li><a href="#" title="test title">Removing Features</a></li>
    </ul>
   <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
   <li><a href="#" title="test title">CAML in SharePoint</a></li>
   <li><a href="#" title="test title">User Groups</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
</ul>
</body>
</html>

Add Menu to Blog

1. Now you have to edit the HTML in your blogger template. To do that first go to "Edit HTML" (Figure 2). (Before editing your template, download the full template)



Find "b:section class='header'" and set the value of "maxwidgets" to 3, if it is less than it (Figure 2). Set "showaddelement" to "true",

2. Then Find the </head> tag in your template and paste the styles just before that tag. Make sure you should include <style type="text/css"> and </style> tags.

3. Now you can add new "HTML/JavaScript" Gadget to your blogger header and paste the code between <body> and </body> from the .html file you created using my code given in the top of this post (Figure 3). There do not give a Title for the Gadget.



Now every thing is ok and view your blog to see the new Gadget.