Thursday, October 16, 2014

Working with Code Analysis Tools in Sharepoint Using SPCorp CE and DisposeChecker

A) SPCop CE (Community Edition):
1. Download
We can down load SPCop.Setup.msi file version 5.1.4.9436 in the following location
Supports: It supports Visual Studio 2013, 2012, 2010
2. Installation: After downloading SPCop.Setup.msi install this SPCop EC.
3. After Installing it is directly Attach to Visual Studio 2013 As follows

 

Righty click on Solution
Select SPCop Community Edition
Next click on Run SharePoint Code Check
SPCop CE Analysis the Code it displays error messages and warning messages as follows




In above Screen we can find out non disposed objects and others details.

B) SPDispose Check Static Analysis:
1. Download
We can down load SPDisposeCheckRules-VS2012.rar file in the following location
Supports: It supports Visual Studio 2013
2. Installation: After downloading extract zip file it contains dll and exe files
 Now right click on SPDisposeCheck.exe install.
We can analysis code in two ways

i.                    With visual studio 2013
Attach SPDisposeCheck to visual studio 2013  
Open solution file click on project and select properties next click on code analysis
Check Enable code Analysis on the build
Click on open button  check SPDisposeCheck and change it action to Error As follows

Click save then it ask rule name gave rule name give rule name (ex: rule1) and click on save


Select Rule Set and browse Rule1 file and save
Now build the project it shows the following warnings 


Note: this tool is analysis only try catch blocks.



ii.                  With Command prompt
Open the command prompt
Change the directory to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\FxCop\Rules.
Using bellow command
Cd C:\Program Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\FxCop\Rules
SPDisposeCheck.exe D:\Dlls Axalta.Global.DcpIformsTemplate.dll

 


Note:
If we have used SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web to get the web or site objects then no need to dispose these Objects explicitly as it will be handled by SharePoint .

If we have used like  SPSite oSPsite = new SPSite("http://server") , SPWeb oSPWeb = oSPSite.OpenWeb() 
then we need to dispose the Objects by use of using statements or calling object.Dispose() in Finally Block.
 
 For more information Please go through the below url for your reference 
 


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()