Wednesday, October 15, 2014

Custom PreSave Action in SharePoint List Form


1.Comment default SharePoint Save button

 <!--<SharePoint:SaveButton runat="server" ControlMode="New" id="savebutton2"/> -->

 2.Place one html input button as like following

<input type="button" value="Save & mail" name="Save" onclick="if(!PreSaveAction())return true;{ddwrt:GenFireServerEvent('__commit;__redirect={../../SitePages/Views/default.aspx}')};" />

3.Write PreSaveAction method as follows

&ltscript type="text/javascript">
function PreSaveAction(){
   Repeat Step 4 // PresaveAction we can set  default values to  sharepoint controls
  return true;
}
 &ltscrip>

4.PresaveAction we can set  default values to  sharepoint controls

    var CurrentUser= $().SPServices.SPGetCurrentUser({ fieldName: "Title", debug: false });
     $("input[title='From']").val(CurrentUser)

In the above we are getting the Current User Name and set to From field Value in the respective List


Sharepoint Forms Controls Validation Using JQuery

1.Add bellow script after <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server"> 
 
 
<script type="text/javascript" src="../../SiteAssets/jquery-1.8.2.min.js"></script >
 <script type="text/javascript" src="../../SiteAssets/jquery.SPServices-2014.01.min.js">  </script> 
 <script type="text/javascript">

Single Line Text Box:

  var DueDate=$("input[title='Due Date']").val();
        if(typeof(DueDate) == "undefined" || DueDate== null || DueDate=="")
         {
               alert("Please Enter Due Date.");
               $("input[title='Due Date']").focus();
                 return false;
           }
   Note : Here 
Due Date is List Column Name                

Muti Line Text Box with Plain Text:

var Name =$("textarea[title='Name']").val();
    if( Name=="")
    {
     alert("enter Name");
    $("textarea[title='Name']").focus();
     return false;
   }


Muti Line Text Box With Rich Text:

 if($('#tdDetails div[role=textbox]').text().length<=1)
    {
       alert("Please Enter Details.");                        
        return false;
   }

Here control is present in  the tdDetails is TD id of table.

Drodown List:

 var LocationId= $("select[Title='Location']").attr("id");
 var LocationControl= document.getElementById(LocationId);                 
 var  strLocation= LocationControl.options[LocationControl.selectedIndex].text;
 if(strLocation=="(None)")
  {
        alert("Please select the Location value");
         return false;
   }


Monday, October 13, 2014

Permission Issue in SharePoint Custom Timer Jobs

Problem

It's easy to find blogs and msdn documentation on creating Custom Timer jobs, but still developers face issues while deploying and running them on SharePoint farms due to lack of development guidelines for timers. In this blog, I will discuss one issue which is related to permission levels for a custom timer job.  Let's say we have the following scenario:
List list_A list_B
SiteCollection SiteCollection: sitecollection_A sitecollection_B
WebApplication webapplication_A webapplication_B
Based on changes made to this list_A, list_B has to be updated which is in sitecollection_B in WebApplication webapplication_B. Out of the box webparts or configurations cannot achieve this.  I thought about writing event handlers, but the success rate with event handlers working on two webapplications is quite low, especially in a farm environment. Also I wanted to do a sync only at non-peak usage hours like every night at 11pm, but this cannot be achieved with event handlers.
So how do we sync two lists in different web applications or based on updates to one list, make appropriate changes in another webapplication?

Solution

The solution is to write a Custom Timer job!
Since two different web applications are involved, they can be in two different "Application Pools" i.e. their System Account user can be different. So we need to elevate privileges to their respective System Accounts in order to run our code. But how do we do that?  SPSecurity.RunwithElevatedPrivileges doesn't work for Timer Jobs, so how can we elevate Privileges in a Timer job?  The solution is to use USER TOKENS of System Account for elevating privileges instead of using SPSecurity.RunwithElevatedPrivileges.

The below example shows how to use a User Token to instantiate the site collection.

SPUserToken myUserToken_A = null;
SPUserToken myUserToken_B = null;

using (SPSite mySiteCollection_A = new SPSite("http://webapplication_A/sites/sitecollection_A"))
{
    myUserToken_A = mySiteCollection_A.SystemAccount.UserToken;
}

using (SPSite mySiteCollection_B = new SPSite("http://webapplication_B/sites/sitecollection_B"))
{
    myUserToken_B = mySiteCollection_B.SystemAccount.UserToken;
}

using (SPSite tempSite_A = new SPSite("http://webapplication_A/sites/sitecollection_A",
myUserToken_A))
{
 using (SPSite tempSite_B = new SPSite(("http://webapplication_B/sites/sitecollection_B",
myUserToken_B))
 {

  //Write your Custom Code here

  //Example:

  //

  //or

  //

 }
}

How does this work?

"mySiteCollection_A.SystemAccount.UserToken" in the above example uses the user token of the site collection's System Account (SharePoint\System).  Using this User Token, we open the site collection with elevated privileges. Now using this site collection's instance, we can do our custom coding.

WSP Add/Install/Update/Uninstall ect. Using Power Shell commands

we can get help from using power shell help command for writing power shell commands

get-help CommandName -example

Ex: get-help Add-SPSolution -example

Add Solution:
Add-SPSolution -LiteralPath c:\wspfileName.wsp

Install Solution:
Install-SPSolution -Identity wspfileName.wsp -GACDeployment 
(or)
Install-SPSolution -Identity wspfileName.wsp –WebApplication siteUrl  –GACDeployment 
Enable Feature:
Enable-SPFeature -identity "FeatureName" -URL siteUrl

Update Solution:
Update-SPSolution -Identity wspfileName.wsp -LiteralPath c:\wspfileName.wsp -GACDeployment

Uninstall Solution
Uninstall-SPSolution -Identity wspfileName.wsp

Remove Solution
Remove-SPSolution -Identity wspfileName.wsp

Disable Feature:
Disable-SPFeature -identity "FeatureName" -URL siteUrl

SiteBackUp:
Backup-SPSite siteUrl -Path C:\BackupFileName.bak

SiteRestore:
Restore-SPSite siteUrl -Path C:\BackupFileName.bak -force 

Ex: siteUrl= http://SP2013/sites/SiteName/

Monday, October 6, 2014

Change the default columns names in the share point default View

1.Give jQuery Liabrary refrence.
2.get fields names using document.ready function and rename the fields

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

$(document).ready(function(){
   // here title0 field name changed to Title
  $('Div[name=title0]').html("Title");
 
 $('Div[name=number]')
      .html("<b style='color:black;font-size:small;font-weight:bold'>Number</b>");
 
});
</script>

Time out Exception in dataview webpart

By default Request Time is 1 m sec
Change default Request Time 1 m sec to 5 m sec using power shell Script as follows

$myfarm = Get-SPFarm
$myfarm.XsltTransformTimeOut
$myfarm.XsltTransformTimeOut = 5
$myfarm.Update()

Tuesday, September 30, 2014

The number of items in this list exceeds the list view threshold, which is 5000 items

List View threshold is 5,000 items if more than 5,000 items  list views are not displayed data
similarly Create Page is not displayed.
 
1.The number of items in this list exceeds the list view threshold, which is 5000 items. Tasks that cause excessive server load (such as those involving all list items) are currently prohibited.
Learn about managing a large list or library and ensuring that items display quickly.


 2.Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer

3<View><Query><Where><And><Eq><FieldRef Name='ContentType' /><Value Type='Text'>Item</Value></Eq><Geq><FieldRef Name='DateComposed' /><Value IncludeTimeValue='TRUE' Type='DateTime'>2014-01-01T02:24:39Z</Value></Geq></And></Where></Query></View>

For Solving these issues we need to do following changes.

1.Change List  threshold limit maximum what we required (i.e more than 5,000 items) using central Admin
2. Delete Unique Permission for the list 
3.Create Indexes columns for the required List. Index column should be Unique number column or Grouping column or Other Columns (Ex EmployeeID ,Year , Created... etc.)
4.if any list have more than 5000 items and it does not have any filter conditions then divide that view into more views based data.(Ex; List Have 7000 items divide  into two views 4500(2000-2010), 2500 items ( 2010-2014)
5.Apply filters on the views.

6.in the new page write filter condition like in screen shot and red condition 3 and past into following SelectCommand
SelectCommand="
 In above CAML query DateComposed is indexed column

7.Run Crawling service

Now almost all views are displayed and new page is displayed .

8.If any view shows  issue no2   then change row limit all items to 500, 200, 100, 50, 10
   where it is displayed  data then stop row limit.

Here All most All issues are solved for me In UAT

When ever we are resorting UAT Site collection BackUP to In Production site

if we got same threshold issue then do following changes

1.we need to recreate indexed columns
2.Run Crawling service

Here All most All issues are solved