Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Tuesday, August 8, 2017

How To CheckIn And CheckOut a SharePoint page using JavaScript(JSOM)

Hi Friends,

Recently I have come across a requirement where I need to update the properties of a Sharepoint page. In this post we are going to see how to checkin and checkout a page in sharepoint using JSOM.
Below are the code snippets.

CheckOut:
function checkOut(){
        var ctx = SP.ClientContext.get_current();
        var page = ctx.get_web().getFileByServerRelativeUrl(window.location.pathname);
        //you can use any path. Here I am using current page.
        page.checkOut();
        ctx.load(page);
        ctx.executeQueryAsync(Function.createDelegate(this, checkOut_Success),
                                            Function.createDelegate(this, checkOut_Fail));
}
function checkOut_Success(sender, args){
 alert("Checked Out");
//do your actions
}
function checkOut_Fail(sender, args){
   alert("Fail checkout");
}

CheckIn:
function checkIn(){
         var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var page = web.getFileByServerRelativeUrl(window.location.pathname);   
        //you can use any path. Here I am using current page.  
        page.checkIn();
        page.publish();
        ctx.executeQueryAsync(Function.createDelegate(this, checkIn_Success),
                                            Function.createDelegate(this, checkIn_Fail));
}
function checkIn_Success(sender, args){       
    alert(" checked in "); 
}
function checkIn_Fail(sender, args){   
    alert("Fail  checked in "+args.message);
}

Hope this helps...

Thursday, March 23, 2017

Structural Navigation vs Managed Navigation in SharePoint

Hi Friends,

In this post we are going to learn about the navigation options present in SharePoint Online.

Below are the two main out of the box navigation options in SharePoint
1) Structured Navigation
2) Managed Navigation

What is Structured Navigation?
This is SharePoint out of the box navigation used by default and it is based on the site structure we define for our portal.

Below are some of the advantages and disadvantages using Structured Navigation.
PROS
CONS
  • Navigation will be updated automatically whenever Sites are added.
  • Easy to configure.
  • Pages are automatically added.
  • Security trimmed, so if a user doesn’t have access to a link it will not appear in the top navigation.

  • Slower performance with complex navigation structure having more than 10 levels.
  • URLs are not friendly and can be hard to memorize.
  • Homepages belonging to structured navigation links do not appear in search when you type a search term.
  • Cannot tag a structured navigation link to a document that it may relate to.


What is a Managed Metadata Navigation?
Managed Metadata is a hierarchical collection of centrally managed terms that we can define, and then use as attributes. It uses a dedicated term set for site navigation and the terms correspond to the friendly URL segment created.

Below are some of the advantages and disadvantages using Managed Navigation
PROS
CONS
  • Easy to maintain.
  • Significantly faster page loads.
  • Pages with term show up in search results.
  • Documents tagged with navigation term show up in search results along with homepage of term.
  • Friendly URLs that are easy to remember.
  • Easy to maintain with more options to target search.
  • Pages are automatically added.

  • Not security trimmed, so if a user doesn’t have access to a link in the top navigation they will still see it but can’t get to it.
  • Sites are not automatically added.
  • Cannot be used across site collections.


Hope this helps...

Tuesday, March 21, 2017

How to create thumbnail/preview of any document or Image or Video in SharePoint

Hi Friends,

In this post, we are going to learn how to generate a thumbnail/preview of any Document or Video or Image in SharePoint.

Recently I came across a requirement to show some document links on a page but the links should be the thumbnail of the document instead of a plain text(document title). Please find the below approach I followed to achieve this.

getpreview.ashx is a http handler used to generate thumbnail/preview of any document(word,pdf, ppt etc.,), Image and Video which resides in SharePoint.

If you observe in SharePoint search results, when we mouse over on the search results we get a preview of that item. This is actually happening through http handler getpreview.ashx

This handler expects a parameter called “path” which expects absolute path of the doc/image/video. Please find the below sample URLs to generate the thumbnail.

Image:

Document:

Video:

This handler has also expects a parameter called “resolution” which has a predefined values 1, 2, 3 etc., for different resolutions of previews/Thumbnails. Please find the below sample URLs with different resolutions



Hope this helps…

Wednesday, March 15, 2017

How to use Image Renditions in SharePoint

Hi Friends,
In this post we are going to learn What are the Image Renditions and how we can use it in SharePoint.

Image renditions helps to display a single image into various sizes based on our needs. Apart from choosing size, it also allows you to crop the image while adding it to the publishing page.

So based on our needs, we can display abcd.jpg as Logo, Banner and Thumbnail etc., This technique helps in reducing the size of the file that is downloaded to the client, which then improves site performance. You can find some of the ways to improve SharePoint site speed and performance here.

The other advantage if you notice, we need not to create different sized images i.e., one for logo, one for thumbnail etc.,. With Image renditions we can display a single image into multiple sizes.

Below are the prerequisites for using Image Renditions 
  •  Publishing Site
  • BLOB Caching enabled(Follow this link on how to configure BLOB cache and its uses)



Please find the below steps on how we can configure Image Renditions.

1.     Go to the top-level site of the publishing site collection.

2.    Choose the Settings icon. On the Site Settings page, in the Look and Feel section,  choose Image Renditions.

3.    This will show you list of available Image Renditions available on this site. We can  modify the existing one, Or we can even create our own based on required dimensions.



          4.       ID indicates the RenditionID. We will be using this RenditionID as a parameter to                       specify the dimensions of an image we need.

         5.       If we want to construct image URL directly from the RenditionID, we just need to                  add it as a  Query String.

Examples: If we want display abcd.jpg as 100*100 on a page, then my image source URL will be “abcd.jpg?RenditionID=1
If we want display abcd.jpg as 200*200 on a page, then my imgage source URL will be “abcd.jpg?RenditionID=2”

        6.       If we want to insert the image in the page content then follow the below steps. 
a)     Edit the page and place the cursor in the Page Content field.

b)    From the Ribbon Insert tab, choose Picture, and then choose From    SharePoint.

c)     Select the image that you want to add to the page and then choose Insert. The image will be displayed at full size.

d)    Next on the Design tab, in the Select group, choose Pick Rendition, and then select an  image rendition whichever required. That’s it, the image will display according to the size  specified for the image rendition.

Hope this helps... 

Tuesday, March 14, 2017

What is a BLOB cache in SharePoint and how to use it?

Hi Friends,

In this article, we are going to learn what is a BLOB cache and how to configure it.

The term BLOB means Binary Large Objects. BLOB cache is one of the disk-based caching techniques used in the SharePoint applications which has large amounts of Media content (Video, Audio and Images etc.,) and heavy user traffic.

So basically this method is used to improve the performance of a SharePoint Application. You can also find some of the other SharePoint performance improvement techniques here.

Disk-based caching techniques are extremely fast which eliminates the need for database round trips. BLOBs are retrieved from the database once and stored on the Web client(WFE server). Further requests are served from the cache and trimmed based on security.

Note: If you are using Image Renditions in the application, then BLOB Cache is the pre-requisite.

We can enable/disable the BLOB cache by modifying the web.config file of the SharePoint web application.
By Default, BLOB cache is disabled. Below is how it looks like.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="false" />

- Location is the directory where the cached files will be stored.
- Path specifies which files(Ex: mov|mp3|mp4|mpeg|mpg) are cached based on the file extension.
- maxSize is the maximum allowable size of the disk-based cache in gigabytes.

- enabled is a Boolean that disables or enables the cache.

To turn ON the BLOB, just make the property enabled as true as shown below.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="true" />

Note : change the location attribute to specify a directory that has enough space to accommodate the cache size.


Hope this helps...

Friday, March 10, 2017

When to use ScriptLink in SharePoint 2013

Hi Folks,

Some times we will run into situations where our custom js file should load only after the page is ready.

In this kind of scenario's, best thing to use is ScriptLink.

ScriptLink have the ability to specify, when we want the script to load asynchronously after the page is ready. By Default, the ScriptLink will always look for the scripts present in /_LAYOUTS/1033 folder.

<SharePoint:ScriptLink language="javascript" name="MyCustomJS.js" Defer="true" runat="server"></SharePoint:ScriptLink>

MyCustom.js should be present in /_LAYOUTS/1033 folder, if not we will get a SharePoint Error screen.

If you set the "Localizable" property of the ScriptLink to false, you can also reference files outside of /_LAYOUTS/1033/ and just put your path to the "Name" property

<SharePoint:ScriptLink Language="javascript" Localizable="false" Name="/_layouts/JS/MyCustomJS.js" runat="server"></SharePoint:ScriptLink>

With the above approaches, we can load the page first and then load the script file.

Note: Using Defer="False" is basically the same as loading the script with the usual method as below.
<script type="text/javascript" src="/_layouts/1033/MyCustomJS.js"></script>


Hope this helps...

Thursday, February 23, 2017

SharePoint 2010/2013 Display user information using ProfilePropertyLoader

Hi Folks,

This article talks about the best way to get the user profile properties on page.

Sometimes we come across the requirement asking to show the User related information on the page.
Generally we write code by accessing User Information list to get the User related data.

In such cases, rather than writing code SharePoint gives us the provision to read the User data.

SharePoint has something called "ProfilePropertyLoader" control which will be available in any SharePoint page which has the below register tag.

<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Follwing are the tags we need to add to the page inoder to read the current user Name and Email.

User Name
The first line below is needed to load and make the profile properties available.

<SPSWC:ProfilePropertyLoader runat="server"/>

<SPSWC:ProfilePropertyValue PropertyName="FirstName" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>

<SPSWC:ProfilePropertyValue PropertyName="LastName" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>

Email
<SPSWC:ProfilePropertyValue cssClass="loggedin" PropertyName="WorkEmail" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>


Hope this helps...

RELATED POST: How to get current user info using jquery spservices



SharePoint site performance improvement techniques - SharePoint2010/2013 and SharePoint Online

Hi Friends,

In this article we will talk about the Steps to Optimize SharePoint Performance.

This article covers some of the factors which plays a vital role in the performance of the SharePoint site on a high level.

1)    Code optimization


  •  Server side code - Use optimized methods, SPDisposeCheck etc.,


Poor Performing Methods and Properties
Better Performing Alternatives
SPList.Items.Count
SPList.ItemCount
SPList.Items.XmlDataSchema
Create an SPQuery object to retrieve only the items you want.
SPList.Items.NumberOfFields
Create an SPQuery object (specifying the ViewFields) to retrieve only the items you want.
SPList.Items[System.Guid]
SPList.GetItemByUniqueId(System.Guid)
SPList.Items[System.Int32]
SPList.GetItemById(System.Int32)
SPList.Items.GetItemById(System.Int32)
SPList.GetItemById(System.Int32)
SPList.Items.ReorderItems(System.Boolean[],System.Int32[],System.Int32)
Perform a paged query by using SPQuery and reorder the items within each page.
SPFolder.Files.Count
SPFolder.ItemCount


  • CSOM - Keep ExecuteQuery function call as less as possible.
Also request properties whichever required. Ref below example

var userObj = clientContext.Web.CurrentUser;
clientContext.Load(userObj, user => user.Title, user => user.LoginName);




  • Use caching in Code (Both CSOM and Server Side). Use the cache duration depends on how often the block of code changes the data.

2)    Merge JS files to single wherever possible.

3)    Make JS files to minified (min) files.

4)    Reduce the usage of global variables in JS files.

5)    Merge CSS files to single wherever possible.

6)    Use CDN(Content Deployment Network) deployment of JS, CSS and Images.

Note: Using CDNs only makes sense in a SharePoint Online context and should be avoided with SharePoint Server.


Hope this helps...

Wednesday, February 22, 2017

Scroll to top of the page after Pagination or Refinement in SharePoint 2013 search results

Hi Friends,

In SharePoint out of the box search results, the paging control will be under the Search results. In this case, whenever there is paging happened the SharePoint will keep the page remained at the bottom though it moved to next set of results. This make users to scroll up the page in order to see the next set of results.


We can overcome this approach using "ScrollToTopOnRedraw” property in Search results webpart. This is a hidden property which will not be visible in Edit webpart properties UI. However this change can be done by modifying the  .webpart file.

"ScrollToTopOnRedraw" is a boolean property which is false by default and all we need to do is, setting this property true.

Please find the below steps

1) Export your current search results webpart to get .webpart file

2) Open it in a text editor or Notepad

3) Find the property “ScrollToTopOnRedraw” and change its value from False to True and Save the file.

4) Import the webpart and add it in your page.

Thats All. The page scrolls to top whenever there is pagination or refinement.

Hope this helps...

Open and Close a SharePoint modal dialog with HTML structure

HI Friends,

In this post we are going look at How to Open and Close a SharePoint Modal Dialog using HTML instead of webpage.

Generally we use SharePoint modal dialog in order to call a webpage as pop-in. But, in this post we are going to open a DIV as a pop-in using SharePoint modal dialogue SP.UI.ModalDialog.showModalDialog

Note: You can open any HTML structure as per your needs.

Please use the below code snippet which does this trick.

function OpenModaldialog() {
  SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    var element = document.createElement('div');
    element.innerHTML = '<div id="modalcontent">This is modal dialogue cocntent</div>';

    SP.UI.ModalDialog.showModalDialog({
     html: element,
     title: 'Dialogue box',
     allowMaximize: false,
     showClose: true,
     dialogReturnValueCallback : Function.createDelegate(null, CloseCallback),
     autoSize: true
    });
   }, "SP.js");
}

function CloseCallback(result, target) {
   //custom action if any
}

That's it, you just need to call the function OpenModaldialog(); on the onclick event of the button through which you want to launch the modal dialogue.

Hope this helps...

RELATED POST: How to Show and Hide a Modal Pop up Dialog in a SharePoint
RELATED POST: How to Open and Close a jquery dialog popup

Thursday, May 14, 2015

Add Asset picker(Browse and select file) control to Textbox in a Sharepoint list form Or Page

Hi Guys,

In this post we are going to learn How to add Asset picker control to a SharePoint FORM/Page.

Recently I came across a requirement where user needs to add the reference of a document present in a document library while adding a new list item. As Sharepoint doesn't provide you any OOTB column/field control to pick the asset from the site, User has to go the document library select the particular document then copy shortcut and finally paste the copied URL into List form.

Some of the users do not like this behavior when they have the file already present in document library and expects the option of browse and pick behavior.

In this post we will be adding the "browse and pick file" control to any Textbox box field(of List form) in which you wants to save the URL of the file.

Below are the steps which does the trick.

Step 1:
Create a js file called "createassetpickercontrol.js"

Step 2:
Add the following snippet to the "createassetpickercontrol.js"
$(document).ready(function () {

// With the below line we will be dynamically adding the Browse control next to the textbox where we need to place this. 

//Replace "controlid" with your actual id of the textbox.

$("textarea#controlid").closest('td').append("<div id='btnbrowsectrl' style='display:none'><input onclick='GetFileURL()' type='button' value='Browse File' /><span>Browse File location if exists on same site</span></div>");

 //The below snippet to acheive the browse functionality
//Create a object which will be used for the Asset. I have used the object name as 'assetPickerObj'
    with(new AssetPickerConfig('assetPickerObj'))
    {{
         DefaultAssetImageLocation='';
         //CurrentWebBaseUrl will be the url of the site or site collection.
         CurrentWebBaseUrl='https://siteurl.com';
         OverrideDialogFeatures='';
         OverrideDialogTitle='';
         OverrideDialogDesc='';
         OverrideDialogImageUrl='';
         //AssetUrlClientID is the id of the control in which the path of the selected file will be saved.
         AssetUrlClientID='controlid';
         AssetTextClientID='';                                                             
         UseImageAssetPicker=false; //make this false to show Documents instead
         DefaultToLastUsedLocation=true;
         DisplayLookInSection=true;                                                            
         ReturnCallback = null;}}
});

function GetFileURL(){
    //Following is the function which launch the AssetPortalBrowser.aspx automatically.
    APD_LaunchAssetPickerUseConfigCurrentUrl('assetPickerObj');

//the above line will just give you the relative url to the textbox.
//set absolute url in textbox if required then use the below lines
var newabsoluteurl= window.location.protocol + "//" + window.location.host+$("#controlid ").val().replace(/\s+/g,"%20");
$("#controlid").val(newabsoluteurl);

return false;

}

Step 3: 
Upload the above JS to your site.

Step 4:
Go to the List and then Select default New Form as shown below.

Add a HTML Form webpart and then add the below JS references in it and then Save the page.
AssetPicker.js is a sharepoint farm JS file and will be available in layouts folder. The folder structure will change from 2007 to 2010 environment.

<script src="/_layouts/1033/AssetPickers.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/createassetpickercontrol.js" type="text/javascript"></script>

There you go, you could now see the browse button to pick the file url when you open the LIst form as below.

Hope this helps...

How to hide ribbon from SharePoint page using CSS

Hi Folks,
In this post we are going to write a css class which will hide ribbon of the sharepoint page.

Below is the css class which does the trick.

#s4-ribbonrow
{
      display:none !important;
}


Hope this helps...

Related post: Hide Sharepoint Recent Changes Section

Open and Close a Sharepoint Modal Dialog with URL

Hi Folks, in my earlier post we have seen how to launch a popup in any page using purely jquery approach. Click here...
In this post we are going to acheive this with Sharepoint framework.

Sharepoint has exposed some client side functions where we can easily call a page as modal dialog/ pop up.

SP.UI.ModalDialog.showModalDialog(options) Method helps us in acheiving the same.

Below is the actual implementation of this function.

function openDialogAndReceiveData(tUrl, tTitle) {
         var options = {
             url: tUrl,
             title: tTitle,
    autoSize: false,
    width:600,
    height:350,
    dialogReturnValueCallback: onPopUpCloseCallBackWithData
         };
         SP.UI.ModalDialog.showModalDialog(options);
     }

function onPopUpCloseCallBackWithData(result, returnValue) {
//If any action that needs to be done on parent page upon close of popup.      
}

The above function is a generic one where we just need to call this function on the onclick of the button on which we are expecting the popin/modal dialog to be opened.
Parameters:
tUrl = absolute or relative path of the page which we need to see as a dialog
tTitle = Title of the modal dialog.

Hope this helps...

RELATED POST: Show and Hide a SharePoint modal dialog with HTML structure
RELATED POST: How to Show and Hide a jquery dialog popup

Tuesday, March 24, 2015

Sharepoint shortcut URL's

Hi Guys,

Sometimes we wanted to bypass some of the UI navigation steps and wanted directly to get into some page like settings or edit mode etc.,

Here are some of the relative links that I know.

Site Settings page:
/_layouts/settings.aspx

View all site content page:
/_layouts/viewlsts.aspx

Pages library:
/pages/forms/allitems.aspx

Manage Site Collection features page:
/_layouts/managefeatures.aspx?Scope=Site

Manage Site Features page:
/_layouts/managefeatures.aspx

Sign in as a different user prompt:
/_layouts/closeconnection.aspx?loginasanotheruser=true

If you want see which all webparts on a page, you can simple go to Web Part Maintenance page by adding the below query string to the end of the URL of any aspx page.
?Contents=1

Sandboxed Solution Gallery page:
/_catalogs/solutions/Forms/AllItems.aspx

Welcome Page settings page:
/_layouts/AreaWelcomePage.aspx

Happy Learning...

Sunday, January 5, 2014

Update User Profile property through jQuery SPServices

Hi folks,
In this post we are going to update User Profile property through jQuery SPServices. Below is the code snippet which does the trick.
Just call the function with the parameters CurrentUserAccountName, PropertyName and PropertyValue.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>

function updateUserProfile(currUserAccName, propertyName, propertyValue) {
   var propertyData = "<PropertyData>" +
  "<IsPrivacyChanged>false</IsPrivacyChanged>" +
  "<IsValueChanged>true</IsValueChanged>" +
  "<Name>" + propertyName + "</Name>" +
  "<Privacy>NotSet</Privacy>" +
  "<Values><ValueData><Value xsi:type=\"xsd:string\">" + propertyValue + "</Value></ValueData></Values>" +
  "</PropertyData>";

   $().SPServices({
       operation: "ModifyUserPropertyByAccountName",
       async: false,
       webURL: "/",
       accountName: currUserAccName,
       newData: propertyData,
       completefunc: function (xData, Status) {
           var result = $(xData.responseXML);
           if (Status == "success") {
              //success message if needed
           }
       }
   });


}

Hope this helps...

Tuesday, September 24, 2013

Javascript Hide recent changes section sharepoint 2010

Hi Folks,
In this post we are going to write a script which will hide Recently Modified Items from the Quick launch of sharepoint site.


Below is how we are going to acheive.

Add a HTML Form Web Part to any section of the page(preferably master page) and then add the below style.

<style>
.s4-recentchanges
{  
  display:none;
}
</style>

Below is the output without Recently Modified Items



Hope this helps...

Monday, June 10, 2013

Differences Between Sandboxed and Farm Solutions

Hi Guys,
In this post we are going to list out the differences between Sandboxed and Farm based Solutions.

Farm based Solutions:
Farm solutions are hosted in the IIS worker process (W3WP.exe).It runs the code that can affect the whole farm.So whenever you deploy a farm solution you must restart the application pool or ISS Server.
If you deploy any feature or retract any feature the whole application pool got recycled.
W3WP is the worker process to which you should attach while debugging Farm based solutions.

Sandboxed Solutions:
Sandboxed solutions are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe).It runs the code that can only affect the site collection of the solution.
Whenever you deploy a sandbox solution, no need of restarting neither the IIS application pool nor the IIS server as sandboxed solutions do not run in the IIS worker process.
SPUCWorkerProcess is the worker process to which you should attach while debugging sandbox solutions.

Points to be noted:
•One major difference is we can't create Aplication pages in Sandbox solutions.Beacuse Application pages are stored in the 14\TEMPLATES\_LAYOUTS and when we deploy as sandbox we dont have permissions to the physical folder.
•Also we cant create VISUAL web parts in Sandbox soultions.
•We cant use code to connect to the external web services or to database in the sandbox soltion
•Farm solutions are installed and deployed. Sandboxed solutions are uploaded and activated.
runwithelevatedprivileges doesn't work in Sandboxed solutions.
• Site collection adminstrator can deploy a Sandboxed solutions, where as Farm administrator can only deploy Farm based Solutions.

Hope this helps...

Wednesday, May 15, 2013

Deleting all versions of a document present in document library except last 2 major and 1 minor versions Moss2007/Sharepoint2010

Recently i came across a requirement to develop a admin component which will delete all the versions of the document except some major and minor verisons present in a Sharepoint document library. Thought of sharing with you guys aswell.
In this post we are going to Delete all versions of a document present in document library except last 2 major and 1 minor versions
Below is the code snippet which performs the action.
You can made the variables int majorVersionsRequired and int minorVersionsRequired are as configurable depending on the versions you require.

try
{
   using (SPSite site = new SPSite("<<http://siteurl/>>"))
   {
      using (SPWeb web = site.OpenWeb())
      {
         SPList list = web.Lists["<<Doc Lib Name>>"];
         int majorVersionsRequired = 2;
         int minorVersionsRequired = 1;

         foreach (SPListItem item in list.Items)
         {
            SPListItemVersionCollection versionCol = item.Versions;
            int count = versionCol.Count;
            int tempMajorVersionsRequired = 0;
            int tempMinorVersionsRequired = 0;
            int versionSiNo = 0;
                           
            for (int i = 0; i <= count - 1; i++)
            {
               if (versionCol[i - versionSiNo].Level == SPFileLevel.Published)
               {
                  // this is a major version
                  tempMajorVersionsRequired++;
                  if (tempMajorVersionsRequired > majorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
               else if (versionCol[i - versionSiNo].Level == SPFileLevel.Draft)
               {
                  //this is a minor version
                  tempMinorVersionsRequired++;
                  if (tempMinorVersionsRequired > minorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
            }
          } 
      }
   }
}
catch (Exception ex)
{

}


Hope this helps...

Popular Posts