Tuesday, January 14, 2014

Asp.net Postback Mechanism(doPostBack function)

Let us understand how asp.net postback works :)


What is __doPostBack function in javascript and what it does? In asp.net all the web server controls except Button and ImageButton (discussed at the end) use javascript __doPostBack function to trigger postback. This behavior is known as asp.net postback mechanism.

To better understand this function lets go step by step. Lets take any web server control except Button and ImageButton on a sample aspx page.
///ASPX
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" Text="LinkButton" />

///Code behind
protected void LinkButton1_Click(object sender, EventArgs e) { }

Run the page in browser and view it source.
///JavaScript
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

///HTML
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

<a id="LinkButton1" href="javascript:__doPostBack('LinkButton1','')">LinkButton</a>

As you can see _doPostBack function takes two arguments viz. eventTarget and eventArgument. Moreover two hidden fields, “__EVENTTARGET” and “__EVENTARGUMENT,” are automatically declared which are used to store values of 'eventTarget' and 'eventArgument' respectively.

When LinkButton1 is clicked, __doPostBack function in javascript is called passing it respective arguments, in this case eventTarget is LinkButton1 and eventArgument is empty, these values are stored in respective hidden fields i.e. they are added to form parameter collection and finally the form is submitted. On server, ASP.NET retrieves and uses the values from form collection and understands which control caused the postback.

Ok if you have some confusion on these values are retrieved, lets do it ourselves to clear the things out. Take another control on web form, say another link button 'LinkButton2'.


Insert break point on Page_Load event and hit F5. Click on LinkButton1, check the values that are retrieved in Page_Load event.


As you see __EVENTTARGET key returns the value of the control that caused postback, here LinkButton1. Now click on LinkButton2 and check the value you get, it will be "LinkButton2". This is how the asp.net postback mechanism works through use of javascript __doPostBack function.

Button and ImageButton

These are the only two controls which cause postback in asp.net. Rest (as explained above) use javascript __doPostBack function and post the form (ASP.NET postback mechanism). In other words these two controls use client browser's submit behavior and hence they do not use __doPostBack function.

However you can make Button to use asp.net postback mechanism by making use of Button.UseSubmitBehavior property (this property is not available for ImageButton control). UseSubmitBehavior property is of type bool and decides whether Button should use client browser's submit behavior (Default. value = true) or asp.net postback mechanism (value = false).

Lets take two Button control on page:
<asp:Button ID="Button1" runat="server" Text="Uses browser submit behavior" UseSubmitBehavior="true" />
<asp:Button ID="Button2" runat="server" Text="Uses asp.net postback mechanism" UseSubmitBehavior="false" />
Note that you don't have to specify UseSubmitBehavior="true" explicitly as it is the default value/behavior. I have added it just for the sake of understanding. Now run this page and view its source in browser, you will these buttons rendered as follows:
<input type="submit" name="Button1" value="Uses browser submit behavior" id="Button1" />
<input type="button" name="Button2" value="Uses asp.net postback mechanism" onclick="javascript:__doPostBack('Button2','')" id="Button2" />
Button2 for which we set UseSubmitBehavior property to false, will now use _doPostBack function to submit the form.

Asp.Net Page Postback from Javascript

If you need to do page postback from javascript, this one is for you...
Today I came across situation where we were using Jquery calendar but we needed postback as soon as date is selected by user.

Step 1- Bind Javascript function to onselect event of Jquery calendar

$("#mydatepicker").datepicker({
    onSelect: function(dateText, inst) {
        _doPostBack("buttonidoranyvalue","");
    }
});​

Above will make sure page is post back as soon as date is selected by user.
first parameter is eventtarget, second paramerter is eventargument.
Same can be used in any java scripts functions

Step 2 - Check Event Target in Request.Forms parameters and do whatever you want man :) like below

if(Request.Form.Params.Get("_EVENTTARGET") == "buttonidoranyvalue") {
//do whatever you want }


Hope this helps...Happy Coding!!!!

Sunday, January 12, 2014

How to create custom action for list items using Client Object Model

Okay...You need to add custom action to list items using client object model.
This user custom action menu item will be added to drop-down menu which is displayed for list items.


          using Microsoft.SharePoint.Client;
            string urlWebsite = "http://xxxxxxxx:9999/";
            ClientContext clientContext = new ClientContext(urlWebsite);
            Web oWebsite = clientContext.Web;
            List oList = oWebsite.Lists.GetByTitle("TestList");
            UserCustomActionCollection collUserCustomAction = oList.UserCustomActions;
            UserCustomAction oUserCustomAction = collUserCustomAction.Add();
            oUserCustomAction.Location = "EditControlBlock";
            oUserCustomAction.Sequence = 100;
            oUserCustomAction.Title = "How to in SharePoint";
            oUserCustomAction.Url =  @"http://howtoinsharepoint.blogspot.in/";
            oUserCustomAction.Update();
            clientContext.Load(oList,
                list => list.UserCustomActions);
            clientContext.ExecuteQuery();
Location property specifies EditControlBlock
Sequence specifies an order of placement in relation to other user custom actions,
Url specifies an absolute path to a page that defines the action. 

Hope this helps...Happy Coding!!!!

How to Add/Update/Delete List Items using Client Object Model


How to Add/Update/Delete List Items using Client Object Model

Steps to add new List Item:
  • Go to Visual Studio 2010.
  • Go to File => New => Project.
  • Select Console Application and name it as CreateListItem.
  • Click Add.
  • Add the references to Microsoft.SharePoint.Client.dll.

    using Microsoft.SharePoint.Client;namespace CreateListItem
    {
        class Program    {
            static void Main(string[] args)
            {
                string siteUrl = "http://xxxxxxxx:9999/";
                ClientContext clientContext = new ClientContext(siteUrl);
                List oList = clientContext.Web.Lists.GetByTitle("TestList");
                ListItemCreationInformation listCreationInformation = newListItemCreationInformation();
                ListItem oListItem = oList.AddItem(listCreationInformation);
                oListItem["Title"] = "Creating New Item";
                oListItem.Update();
                clientContext.ExecuteQuery();
            }
        }
    }
  • Hit F5.
  • Go to the SharePoint list "TestList" and you could see a new item is added.
Steps to update List Item:

using Microsoft.SharePoint.Client;
namespace
 UpdateListItem
{
    class Program    {
        static void Main(string[] args)
        {
            string siteUrl = "http://xxxxxxxx:9999/";
            ClientContext clientContext = new ClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle(" TestList");
            ListItem oListItem = oList.GetItemById(1); // 1 is id of item to be updated
            oListItem["Title"] = "Updating Item.";
            oListItem.Update();
            clientContext.ExecuteQuery();
        }
    }
}Hit F5.
  • Go to the SharePoint list "TestList" and you could see a item is updated.
Steps to delete List Item:

using Microsoft.SharePoint.Client;
namespace UpdateListItem
{
    class Program    {
        static void Main(string[] args)
        {
            string siteUrl = "http://xxxxxxxx:9999/";
            ClientContext clientContext = new ClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle("TestList");
            ListItem oListItem = oList.GetItemById(1); // 1 is item id to be delted
            oListItem.DeleteObject();
            clientContext.ExecuteQuery();
        }
    }
}
  • Hit F5.
  • Go to the SharePoint list "TestList" and you could see a new item is added.
Hope this helps...Happy Coding!!!!

SharePoint and jQuery–Getting & Setting SharePoint Form Fields


Question 1: From where to download JQuery Base Library?
Answer 1: http://code.jquery.com/jquery-1.7.2.min.js
Question 2: How to include JQuery Script?
Answer 2: Upload the JQuery base library to the Assets list and include the library using the below syntax
<script type="text/javascript" src="../../Assets/jquery-1.7.2.min.js"></script>
Question 3: What attribute to use for getting the INPUT object?
Answer 3: We need to use the title attribute of the INPUT control
<input name="ctl00$m$g_e2bcfa9c_6e16_4b44_9833_22e44201a72b$ctl00$ctl04$ctl03$ctl00$ctl00$ctl04$ctl00$ctl00$TextField" type="text" maxlength="255" id="ctl00_m_g_e2bcfa9c_6e16_4b44_9833_22e44201a72b_ctl00_ctl04_ctl03_ctl00_ctl00_ctl04_ctl00_ctl00_TextField" title="Email" class="ms-long" />
Question 4: How to write JQuery function?
Answer 4:
<script type="text/javascript" src="../../Assets/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
});
}
</script>
Note: $(document).ready(function ()... is referred as the MAIN() function
Question 5: How to get the value of the INPUT field?
Answer 5: var variablename = $("input[title='title of the input control']").val();
Question 6: How to make the field readonly?
Answer 6: $("input[title='title of the input control']").attr("readonly","true");
Question 7: How to get the value of the Dropdown?
Answer 7: var variablename = $("select[title='title of the dropdown control']").val();
Question 8: How to set the value to the text field?
Answer 8: $("input[title='title of the input control']").val("enter value here");
Question 9: How to remove the readonly of the text field?
Answer 9: $("input[title='title of the input control']").removeAttr("readonly"); 
Question 10: How to set focus to the text field?
Answer 10: $("input[title='title of the input control']").focus(); 
Question 11: How to use JQuery in PreSaveAction?
Answer 11: 
<script type="text/javascript" src="../../Assets/jquery-1.7.2.min.js"></script>
<script language = "Javascript">
function PreSaveAction()
{
var variablename = $("input[title='title of the input control']").val();
}
</script>
Note: do not include $(document).ready(function ()... 
Question 12: How to call JQuery function in Dropdown value change?
Answer 12:
<script type="text/javascript" src="../../Assets/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select[title='title of the control']").change(function () {
//write logic here
});
});
</script>
Question 13: How to set the width of the Text field?
Answer 13: $("input[title='title of the control']").width(100);
Question 14: How to disable Textfield?
Answer 14: 
$("input[title='title of the control']").attr('disabled','disabled');
Question 15: How to Remove disable attribute on Textfield?
Answer 15: 
$("input[title='title of the control']").removeAttr('disabled');
Question 16: How to check numeric value in Text field?
Answer 16:
var numbervaluefield = $("input[title='title of the control']").val();
var numericheckvaariable = $.isNumeric(numbervaluefield);
Note: The function will return boolean value
Question 17: How to compare date in Jquery?
Answer 17:
var startdate = new Date($("input[title='Start Date']").val());
var enddate = new Date($("input[title='End Date']").val());

if(enddate < startdate)
{
 alert("End Date cannot be lesser than Start date.");
 $("input[title='End Date']").focus();
 return false;
}
else
{
 return true;
}
Question 18: How to set default value in Rich Text field?
Answer 18:
<script type="text/javascript" src="../../Assets/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

var htmlcontentval = "<table border='1' cellpadding='0' cellspacing='0'><tr><td colspan='3'>Month-Year</td></tr><tr><td>Milestone</td>       <td>Onsite Effort</td><td>Offshore Effort</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></table>";
$("textarea[title='Milestone Information']").val(htmlcontentval);
});
</script>
Note: Milestone information is the title of the textarea used in the Rich text field
Question 19: How to hide the Sharepoint Enhanced Richtext field?
Answer 19:
 $("textarea[title='richtexttitle']").closest("tr").hide();

Question 20: How to unhide the Sharepoint Enhanced Richtext field?
Answer 20:
 $("textarea[title='richtexttitle']").closest("tr").show();
Question 21: How to convert string to uppercase?
Answer 21
$("input[title='titlename']").val().toUpperCase();
Question 22: How to check length of the string?
Answer 22
$("input[title='titlename']").val().val().length;
Question 23: How to validate Email address?
Answer 23:
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("input[title='titlename']").val();
if(!emailReg.test(emailaddressVal))
{
 alert("Please enter valid email address");
}
Question 24: How to get the lookup text value (Dropdown text value)?
Answer 24:
$("option:selected", $("select[title='titlename']")).text();

Hope this helps...Happy Coding!!!

Disable Control in default Add/Edit List form

We might have came across situation where we need to disabled controls on add/edit form based on user selection or for that matter based on any condition/requirement.

Add Content Editor Webpart below the NewForm/EditForm, then include the Javascript in source editor of Content Editor Webpart

<script language="javascript">
$("input[title='title of the input control']").attr("readonly","true"); 
</script>


Note - Make sure jquery libraries is referenced in master page or else call it content editor webpart itself

Hope this helps...Happy Coding!!!!

Taxonomy hidden list in SharePoint



The taxonomy hidden list contains all the metadata taxonomy terms that are used in your site collections. Below are some of the facts about this list:
a. As the name of the list indicates, the list is a hidden list which means you will not be seeing a link to this list anywhere in your site collection.
b. The URL of the list would be like: http://YourSharePointSite/Lists/TaxonomyHiddenList/
c. This list will only be present in the root site of your site collection.
d. The list by default has read access to all NT\Authenticated users. Make sure to verify this when your users have issues with using the metadata taxonomy service.
e. The list contains only the taxonomy terms that were used anywhere in your site collections. That means when you are using a taxonomy term for the first time in any list, that term gets added as a new list item in the taxonomy hidden list.
f. This list contains the following fields to store the data about the taxonomy terms:
clip_image001
Hope this helps...Happy Coding!!!

Saturday, January 4, 2014

Deploy Site Pages with Webpart with WSP

How to create a webpart page and embed a webpart into it using elements xml file.
To start with, create an Empty SharePoint project in visual studio 2010.
wp1
The next step is to create a visual webpart, we will be embedding this into our webpart page
wp2
For demonstration, I added a label control with text property set to “Cool Webpart”
wp3
Now add a new module to the project
wp4
This will create two files into the solution
wp5
Delete the sample text file. Add an aspx page.
wp6
Now open the aspx page and paste following markup
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" 
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" 
Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" 
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" 
Inherits="WebpartPages.MyPage" masterpagefile="~masterurl/default.master" %>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <WebPartPages:WebPartZone runat="server" ID="wpzMyZone">
    <ZoneTemplate></ZoneTemplate>
    </WebPartPages:WebPartZone>
</asp:Content>
Open the code behind and ensure the page inherits WebPartPage
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace WebpartPages
{
    public partial class MyPage : WebPartPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}
Now open up the elements xml file and update it as below
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Webpartpage" Url="SitePages">
    <File Path="Webpartpage\MyPage.aspx" Url="MyPage.aspx"  
          Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE">
      <AllUsersWebPart WebPartOrder ="0" WebPartZoneID ="wpzMyZone">
        <![CDATA[ 
          <webParts>
            <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
              <metaData>
                <type name="WebpartPages.MyWebpart.MyWebpart, WebpartPages, 
                Version=1.0.0.0, Culture=neutral, PublicKeyToken=132122a1200767d5" />
                <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
              </metaData>
              <data>
                <properties>
                  <property name="Title" type="string">MyWebpart</property>
                  <property name="Description" type="string">Mywebpart</property>
                      
                </properties>
              </data>
            </webPart>
          </webParts>
        ]]>
      </AllUsersWebPart>
    </File>
  </Module>
</Elements>

Deploy the solution. Now open up the SitePages library, there you can see the new webpart page we just created.
Hope this helps...Happy Coding!!!!

Get Set Value in PeopleEditor Webpart in Visual Webpart

Adding to Webpart

<SharePoint:PeopleEditor ID="myPeoplePicker" runat="server" Width="300" BorderStyle="Solid" BorderColor="Black" BorderWidth="1" />


Reading Value from Control

if(myPeoplePicker.ResolvedEntities.Count >0 )
{
PickerEntity objEntity = (PickerEntity) myPeoplePicker.ResolvedEntities[0];
    SPUserInfo objInfo = new SPUserInfo();
    objInfo.LoginName = objEntity.Key;
    strAccountName = objInfo.LoginName;

//objEntity.EntityData Gets or sets a data-mapping structure that is defined by the consumer of the PickerEntity class. This properties has all data related to user entity.

}

Setting Value to Control

myPeoplePicker.CommaSeparatedAccounts = "domain\username";
myPeoplePicker.ValidateEntity()


Hope this helps...Happy Coding!!!