Wednesday, 25 January 2012

Creating a List Item Using ECMAScript (JavaScript, JScript)


<table width="364" height="83" border="1">
  <tr>
    <td>Enter the Title:</td>
    <td><input type="text" id="titletxt" name="titletxt"> </td>
  </tr>
  <tr>
    <td>Enter the Name:</td>
    <td><input type="text" id="nametxt" name="nametxt"> </td>
  </tr>
  <tr>
    <td colspan="2"><input id="btnGetFieldType" onclick="getFieldType()" type="button" value="Get Field Type" align="middle" /></td>
   
  </tr>
</table>
<script language="ecmascript" type="text/ecmascript">
        var fieldCollection;
        var field;
        var list;
var t=document.getElementById('titletxt');
var n=document.getElementById('nametxt');
        function getFieldType() {
            var clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var oList = clientContext.get_web().get_lists().getByTitle('ecmascript List');
       
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
       
    oListItem.set_item('Title',t.value);
    oListItem.set_item('Name',n.value);
       
    oListItem.update();

     clientContext.load(oListItem);
 clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
            }
        }
      function onQuerySucceeded() {

    alert('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}</script>

Tuesday, 24 January 2012

Set The Default Value For The Field in SharePoint 2010 Using ECMAScript


Introduction

In this article you will see how to set the default value for the field in SharePoint 2010 using ECMAScript. I have a list named "List Request" which has the following fields (Navigate to the list, click on List tab in the ribbon interface. Click on List Settings button).

Script1.gif

I am going to set the default value for the column named "Description" using ECMAScript.

Steps Involved

Step 1 : Navigate to the SharePoint site (I have a site page created in my site where I am going to add the content editor web part).

Step 2 : Go to Site Actions, click on Edit Page.

SharePoint2.gif

Step 3 : Click on the Insert tab in the ribbon interface and then click on Web Part button.

SharePoint3.gif

Step 4 : Select Media and Content in the Categories section and then click on Content Editor.

SharePoint4.gif

Step 5 : Click on Add.

Step 6 : The Content Editor web part will be added to the site page.

Step 7 : Click on the down arrow and then click on Edit Web Part.

SharePoint5.gif

Step 8 : Click on "Click here to add new content".

SharePoint6.gif

Step 9 : Click on Format Text tab in the ribbon interface and then click on HTML drop down.

SharePoint7.gif

Step 10 : Click on Edit HTML source.

Step 11 : The HTML source window will pop up.

SharePoint8.gif

Step 12 : Copy and paste the following script.
<script language="ecmascript" type="text/ecmascript">
        var fieldCollection;
        var field;
        var list;
        function fieldDefaultValue() {
            var clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("List Request");
                this.fieldCollection = list.get_fields();
                this.field = fieldCollection.getByTitle("Description");
                this
.field.set_defaultValue("Default");                this.field.update();                clientContext.load(this.field);
                clientContext.executeQueryAsync(Function.createDelegate(thisthis.OnLoadSuccess),
Function.createDelegate(thisthis.OnLoadFailed));
            }
        }
        function OnLoadSuccess(sender, args) {
            
alert(this.field.get_defaultValue());        }
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
</
script
>    <input id="btnFieldDefaultValue" onclick="fieldDefaultValue()" type="button" value="Field Default Value" />

Step 13 : Click on Ok.

Step 14 : In the ribbon interface click on the Save & Close button.

SharePoint9.gif

Step 15 : In the content editor web part you can find a button named "Field Default Value"; click on that button.

SharePoint10.gif

Step 16 : An alert will pop up which displays the default value for the field.

Script2.gif

Monday, 26 December 2011

Run code with elevated privileges in SharePoint

RWEP (Run With Elevated Privileges) method will execute code to supply a delegate that runs a set of code in the context of an the Application Pool identity  account ( which has site collection administrator privileges on all site collections hosted by that application pool ) instead of the logged in user, essentially giving that user Administrator Level Permissions in a confined space.

Basically the code executed inside this method has "System Account" privileges in addition to the current user privileges or in a better way - we can tell that this method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.

But sometimes we used to get "Access denied" even if we use code within RWEP method,looks strange but there are fact under which RWEP will work perfectly and the criteria's are


You should not use old references to SPWeb or SPSite instances inside your delegate, since these objects will hold the permissions of currently signed user, So you need to create new SPSite and SPWeb instances using the Ids of the sites and webs you already have a created, like this:

private void CustomFunction()
{
            // Non-Elevated Permission Code Goes Here

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                         SPSite site = SPContext.Current.Site;   
                         SPWeb web = SPContext.Current.Web;
                          //New SPSite object.
                         using (SPSite newsite = new SPSite(Site.ID))
                         {
                                      //New SPWeb object.
                                     using (SPWeb newWeb = newSite.OpenWeb(web.ID))
                                     {
                                    //Do things by assuming the permission of the "system account".
                                      }
                        }
            });  // Note the Brackets used while creating delegate
}

Example:

private void CustomFunction()
{
      SPSite site = SPContext.Current.Site;
      SPWeb web = SPContext.Current.Web;

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            using (SPSite newSite = new SPSite(site.ID))
            {
                  using (SPWeb newWeb = newSite.OpenWeb(web.ID))
                  {
                        list = newWeb.Lists["ElevatedListTest"];
                        SPListItem newItem = list.Items.Add();
                       
                        // Do stuff to create the list item
 
                        newWeb.AllowUnsafeUpdates = true;
                        newItem["Title"] = "Testing Title";
                        newItem.Update();
                                          list.Update();
                        newWeb.AllowUnsafeUpdates = false;
                  }
            }
       });
}

Delegate Control

SharePoint Delegate control is a mechanism that we can insert a code or control to the SharePoint Master page(and Page Layout) without touching any of code in the SharePoint Master page(and in Page Layout) and also it is a container type control which can holds child controls on it 

The Search bar is located at the top of all the pages in a site, and the master page uses a delegate control in a placeholder to determine what to render at runtime. Here is the markup for the delegate control:


<SharePoint:DelegateControl runat=”server” ControlId=”SamllSearchInputBox”/>

Note that the ControlId value determines what delegate control is needed to be added in the respective place.

Importance:
·         Using the delegate control a developer can customize the SharePoint site controls without editing the code master page (After inserting the Delegate).
·         Suppose if you want add a counter for no.of.vistors to the site. We created a control for displaying the total count in the master page. If we want to keep this control in the master page we need to edit that master page and add all the controls over here. At any time if any mistake happen then whole master page will be changed knowingly or unknowingly. To avoid this we have delegate controls.

AdditionalPageHead
Top most delegate control in the master page allows multiple controls. You can use this delegate to inject JavaScript, custom logic, etc. to the master page. You can specify a control which only has a code to do whatever you need in onLoad event.
<Control Id="AdditionalPageHead" Sequence="90"             
           ControlSrc="~/_CONTROLTEMPLATES/a/test1.ascx" />

<Control Id="AdditionalPageHead" Sequence="91"             
           ControlSrc="~/_CONTROLTEMPLATES/b/ test1.ascx" />
Sequence controls the order if more than one control



Scenario 1 (Creating Delegate Within Master Page Itself)

You can create new simple delegate within the master page itself.





Scenario 2 (Creating Custom delegate control using Visual Studio)
Steps:
1.       Open Visual Studio 2010 and create a new Empty SharePoint project.
2.       Map a new folder to the CONTROLTEMPLATES directory in the SharePoint root (the 14 hive).
3.       Add a new item visual web part and empty element like below image.


4.       Design the logic inside the Visual Web part or add an div element with sample text for testing  and finally edit the Element.xml file like below

<?xml version="1.0" encoding="utf-8"?>


<Control Id="MyControl" Sequence="20" ControlSrc="~/controltemplates/TestTemp.ascx" />

</Elements>
5.       Save the changes and deploy into the site.
6.       Now we created a delegate control and want to add it to our site. Now add the following code to our master page anywhere you want.

<SharePoint:DelegateControl ControlId=" MyControl " AllowMultipleControls="true" runat="server">
</SharePoint:DelegateControl>





SpListItem.Update and SpListItem.SystemUpdate and SpListItem.UpdateOverwriteVersion

1.     Update(): With this method you can update the list item. But it will change values  in 'Modified By' to the SHAREPOINT\system account and sets the Modified column to the current date time. If versioning is enabled, the version is increased.

2.     SystemUpdate(): This method also updates the list item but it will not change the values in the Modified By and the Modified column. This method comes with two overloads. You can also specify a Boolean value to indicate if you want to increase the version number or not ( By default it will be fasle, so that the version will not be updated).

3.     UpdateOverwriteVersion(): This method updates the list item without changing the version number. 

Example:

 using (SPSite site = new SPSite("http://testsite"))
 {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists["Test List"];
            SPListItem item = list.Items[1];
            item["Title"] = "Sample Update";
            item.Update(); // update version,modified and modified column
           //item.SystemUpdate(); // update version number
          //item. UpdateOverwriteVersion(); // update version number.
           list.Update();
         }

  }

SQL Joins


The SQL JOIN refers to using the JOIN keyword in a SQL statement in order to query data from two tables.

When you perform a SQL join, you specify one column from each table to join on. These two columns contain data that is shared across both tables.

Join Types

Depending on your requirements, you can do an "inner" join or an "outer" join. These are different in a subtle way
  • INNER JOIN (or JOIN) : This will only return rows when there is at least one row in both tables that match the join condition.
  • LEFT OUTER JOIN (or LEFT JOIN): This will return rows that have data in the left table (left of the JOIN keyword), even if there's no matching rows in the right table.
  • RIGHT OUTER JOIN (or RIGHT JOIN): This will return rows that have data in the right table (right of the JOIN keyword), even if there's no matching rows in the left table.
  • FULL OUTER JOIN (or FULL JOIN): This will return all rows, as long as there's matching data in one of the tables.
Syntax:

SELECT * FROM table_name1 Join_Name(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL JOIN) table_name2 ON table_name1.column_name = table_name2.column_name

Examples:

Source Tables


Left Table(Individual)
IdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike


Right Table(Publisher)
IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor
10Administrator

1) Inner Join

SELECT * FROM Individual
INNER JOIN Publisher
ON Individual.IndividualId = Publisher.IndividualId
WHERE Individual.IndividualId = '2'

Result
IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
2HomerSimpsonhomey2Contributor
2) Outer Join

     a)Left Outer Join
           
            SELECT * FROM Individual AS Ind
     LEFT JOIN Publisher AS Pub
     ON Ind.IndividualId = Pub.IndividualId

Result

IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL
   b)Right Outer Join
    SELECT * FROM Individual AS Ind
    RIGHT JOIN Publisher AS Pub 
    ON Ind.IndividualId = Pub.IndividualId

Result
IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
NULLNULLNULLNULL10Administrator
3)Full Outer Join
SELECT * FROM Individual AS Ind
FULL JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId

Result

IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL
NULLNULLNULLNULL10Administrator