Saturday, February 15, 2014

Get the Selected Date/Time within a SharePoint 2010 Calendar using jQuery

The selected date in a SharePoint 2010 calendar may be needed when writing custom solutions. This can be retrieved using JavaScript and jQuery.  First, we need to determine if we are in the month, week, or day scope of the calendar.  There is probably a better way to do this, but the following seems to work: 



// make these global
var selectedDate = 'no date selected';
var selectedTime = 'no time selected';


// put the rest of the code in a function
function GetSelectedDate() {

  var dayScope = $('table.ms-acal-detail');
  var weekScope = $('table.ms-acal-detail');
  var monthScope = $('table.ms-acal-month');


  var isDayScope = dayScope.length > 0 ? dayScope.attr('summary').indexOf('Daily') > -1 : false;
  var isWeekScope = weekScope.length > 0 ? weekScope.attr('summary').indexOf('Weekly') > -1 : false;
  var isMonthScope = monthScope.length > 0 ? monthScope.attr('summary').indexOf('Monthly') > -1 : false;


Now lets get the selected element:


var selecteddateelement = $('.ms-acal-vitem');


Now that we know which view we are in, and have the selected element, we can determine the selected date if we are in the monthly scope.


  if(isMonthScope) {
var tditem = selecteddateelement.parent();
var tritem = selecteddateelement.parent().parent();
var prevtr = tritem.prev();
var indx = tritem.children().index(tditem) + 2;
var dttd = prevtr.children(':nth-child(' + indx + ')');
if(selecteddateelement.length > 0) selectedDate = dttd.attr('date');
  }

Next lets handle the weekly  scope .

  else if(isWeekScope) {
var weektritem = selecteddateelement.parent();
var weekdayindx = weektritem.children().index(selecteddateelement) + 1;
var weekselectedhalfhourstarttime = $('[class^=ms-acal-hour]').index(weektritem) / 2;
var weekdttd = $('.ms-acal-week-top').children(':nth-child(' + weekdayindx + ')');
if(weekdttd.length > 0) selectedDate = weekdttd.attr('date');
if(weekselectedhalfhourstarttime >= 0) selectedTime = weekselectedhalfhourstarttime;
  }

And finally the daily  scope .

  else if(isDayScope) {
var verbosedaydate = $('.ms-acal-display').text();
var daydatesplit = verbosedaydate.split(/,| /);
var month = daydatesplit[1];
var dayscopemonth = (new Date()).getMonth() + 1; // default to current month


if(month == "January") dayscopemonth = 1;
else if(month == "February") dayscopemonth = 2;
else if(month == "March") dayscopemonth = 3;
else if(month == "April") dayscopemonth = 4;
else if(month == "May") dayscopemonth = 5;
else if(month == "June") dayscopemonth = 6;
else if(month == "July") dayscopemonth = 7;
else if(month == "August") dayscopemonth = 8;
else if(month == "September") dayscopemonth = 9;
else if(month == "October") dayscopemonth = 10;
else if(month == "November") dayscopemonth = 11;
else if(month == "December") dayscopemonth = 12;


var dayscopeday = daydatesplit[2];
var dayscopeyear = daydatesplit[3];


selectedDate = dayscopemonth + '/' + dayscopeday + '/' + dayscopeyear;


var daytr = selecteddateelement.parent();
var dayselectedhalfhourstarttime = $('[class^=ms-acal-hour]').index(daytr) / 2;
if(dayselectedhalfhourstarttime >= 0) selectedTime = dayselectedhalfhourstarttime;
  }

Now the selectedDate and selectedTime will be populated.  Echo these to the console to see the values:

  console.log("selectedDate:    " + selectedDate); // change this to do something with the date
  console.log("selectedTime:    " + selectedTime); // change this to do something with the time
  // end the function
}

The selectedDate and selectedTime variables should be global variables.  This allows the preceding code to be put into a function, say "GetSelectedDate()" and bound to a click event on the calendar.  The issue with not doing this is if you are trying to call this code from a button or anchor click outside of the calendar, when clicked, first the calendar looses focus, then the ms-acal-vitem class is stripped.  The result is that nothing is selected when the code would run, coming back with "no date selected" every time.  Binding to click would look like this:



$(document).ready(function () {
$('.ms-acal-rootdiv').unbind("click").click(function () {
GetSelectedDate();
});
});


Doing so will set the global variables selectedDate and selectedTime every time a click is made.  Another thing you may want to do is create a function to set these variables to the current date and time.  This could be called first, then the preceding code, resulting in selectedDate and selectedTime always having a date populated.

It seems like a long way to go to get the selected date, and does not handle localization.  I would love to see what others are doing to solve this issue.  I know there are some xslt solutions out there too.

Thanks to 
http://franknezrick.blogspot.in/2012/03/get-selected-datetime-within-sharepoint.html

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!!!