Thursday, April 20, 2017

Rename a Web Application in Sharepoint : A solution using powershell


Here is a small script that will enable you all to change a SharePoint Web Application name .



We can use the following SharePoint PowerShell script:





$renameWApp=Get-SPWebApplication | where {$_.Name -match "Old Web Application Name"}
$renameWApp.Name="New Web Application Name"
$renameWApp.Update()

Want to delete more than 5000 items in a sharepoint list : a better way is here

Its a very common issue that you face, to delete bulk data from a SharePoint list (above 5000) .

Everyone would run into the error  : Sorry Something went wrong



Tried deleting from SharePoint designer too , it did not help ...


After hours of trial and error found out something cool for this : MICROSOFT ACCESS to the rescue :
Open Access
1. create a blank database.
2. go to External Data and in the Import & Link section Choose SharePoint List
3. Connect to the SharePoint list

4. Click Next, and choose the list you want to work with . Click OK.

 Open the table ,select any items you want to  edit or delete.


Thats it ...

Tuesday, August 30, 2016

Sharepoint : Get list item Attachment by Name using JSOM

Scenario : Suppose you want to get the attachment from a list item and you only know its name .



Solution :You can achieve this using a simple JSOM code as shown below . the major player in this code is the line "splistItem.get_attachmentFiles().getByFileName("FILENAME"));"




function getAttachmentsDetails()
{

var clientContext = SP.ClientContext.get_current();
var splist = clientContext.get_web().get_lists().getByTitle("LISTNAME");
var splistItem = splist.getItemById(ID);
clientContext.load(splistItem);

// gets the item by attachment file name
clientContext.load(splistItem.get_attachmentFiles().getByFileName("FILENAME"));


clientContext.executeQueryAsync(Function.createDelegate(this, Success), Function.createDelegate(this, Fail));
 
function Success(sender, args) {
    var attachitem = splistItem;
    var total = attachitem.get_attachmentFiles().get_count();
    if (total > 0) {
        console.log(total + " file attachments"); // count will give the attachment count
    }      
}
 
function Fail(sender, args) {
    //failed function
}
}
That's All! SharePoint All the Way !!!


Monday, August 8, 2016

JavaScript : Format Data to MM-DD-YYY hh:mm AM/PM

A simple function to format date in MM-DD-YYY hh:mm AM/PM  format.


Usage :  DateFormatter(Datevalue)


// Function that formats date
function DateFormatter(dateValue) {
    var newDate = new Date(dateValue);
    var sMonth = AdjustDate(newDate.getMonth() + 1);
    var sDay = AdjustDate(newDate.getDate());
    var sYear = newDate.getFullYear();
    var sHour = newDate.getHours();
    var sMinute = AdjustDate(newDate.getMinutes());
    var sAMPM = "AM";
    var iHourCheck = parseInt(sHour);
    if (iHourCheck > 12) {
        sAMPM = "PM";
        sHour = iHourCheck - 12;
    }
    else if (iHourCheck === 0) {
        sHour = "12";
    }
    sHour = AdjustDate(sHour);
    return sMonth + "-" + sDay + "-" + sYear + " " + sHour + ":" + sMinute + " " + sAMPM;
}


//function that pads the values
function AdjustDate(value) {
    return (value < 10) ? "0" + value : value;
}


// Code ends here




SharePoint all the way !!!

What to expect in Sharepoint this Year : ?


I was just reading through the office Blogs this morning and some words in that made me feel super excited . Just thought , I would share a summary of things to expect for the SharePoint users in the year of 2016 .


The following are the functionalities that will be rolled out from Microsoft this year :
  • Access to SharePoint Online document libraries and Office 365 Group files from the OneDrive mobile app.
  • Intelligent discovery of documents from both OneDrive and SharePoint.
  • Copy from OneDrive to SharePoint in the OneDrive web experience.
  • OneDrive Universal Windows Platform (UWP) application.
  • Document analytics surfaced in OneDrive to provide insight into document usage, reach and impact.
  • Synchronization of SharePoint Online document libraries with the new OneDrive sync client.
  • Synchronization of shared folders with the new OneDrive sync client.
  • Mobile access to SharePoint document libraries in on-premises farms.
  • Move and copy files between OneDrive and SharePoint in web experiences.
Reference : https://blogs.office.com/2016/05/04/the-future-of-sharepoint/


Already Excited and Just cant wait :) .... SharePoint all the way !!!!1

Sharepoint 2016 : Team Sites Gets an Upgrade and it looks awesome..

Fresh Look, Change in Logic  and cool things that makes it fabulous
Microsoft have made some changes to the look and feel , and logic of SharePoint 2016 team sites .  when a site is created from the “SharePoint home” page you’ll actually be creating an Office 365 Group *and* a team site together.  That is a major change to the previous logic of One drive .
The following images shows the new look UI for the team sites .
 

 
 
  • So these modern team sites will be a collaboration of  SharePoint team sites and Office 365 Groups together.
  • Every group will have a  team site associated with it .
  • Moreover this will have a fresh look and feel as shown in the image above.

  SharePoint all the way...

Sharepoint FrameWork 2016 : A new baby is born



In the Month of May 2016 , Microsoft Announced- a new development  model for SharePoint . It has been given the name SHAREPOINT FRAMEWORK . Consider it as a modern development kit that is flexible , enhancable, robust  and that embraces Microsoft’s “mobile-first,
cloud-first”  terms.


This new baby  focuses on client-side rendering framework leveraging open source JavaScript technologies. This will allow developers to use modern JavaScript and web templating frameworks across cloud and on-premises SharePoint.


The Framework is built on top of a collection of frameworks, libraries and techniques that you want to be comfortable with before you begin work with the Framework. In particular, the Framework makes use of JavaScript-based client-side rendering (CSR), and in fact the development framework, the Workbench, is built on top of Node.js, a JavaScript-based application runtime environment. The Framework makes use of an array of open-source tools that have been becoming standard for any web-based project.


Tools needed for us to be prepared :
1. JavaScript  : Client side code/library
2. Node.js   : is a network application runtime environment
3. Yoeman  :  another Node.js-based tool that allows you to quickly scaffold a project
4. Gulp  :  Gulp is a task-runner based on Node.js
5. React.js : a rich framework for building web applications
6. Visual Studio Code : an open-source code editor built by Microsoft
7. GIT
8. TypeScript : Strong Typed JavaScript




Expected Release :


The SharePoint Framework will be released to Office 365 customers in First Release this summer. Web parts built with the framework can be added to modern pages and experiences and to existing pages.


  • The Files API on Microsoft Graph.
  • SharePoint Webhooks (preview).
  • Client-side web parts for existing pages (preview).
  • The Sites API on Microsoft Graph.
  • SharePoint Webhooks (GA).
  • Custom sites on the SharePoint Framework.
References : https://blogs.office.com/2016/05/04/the-future-of-sharepoint/


Together , let us be ready to welcome this new baby of ours.


SharePoint All the Way !!!!

Thursday, August 4, 2016

Retrieve Query String Value from Sharepoint using Javascript

If you want to retrieve the values passed via Query String from a SharePoint URL , please use the below function . You can add it to any script editor , content editor web parts or visual web parts .


For example , I have a Query String say ID, and I want the value passed to it , I can call my method as follows.


<script>
$(document).ready(function() {
var ID= getParameterByName('ID'); 
//ID will return the Query string value
alert(ID);
});






function getParameterByName(name,url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


</script>

Check If current User member of Sharepoint Group using JSOM (2013 or 2010)

The following block of code will help you identify if the current logged in user is already a part of any SharePoint group .


Say for example, I need to check if the current user belongs to Elninos Football Team SharePoint group .  You can use the following scripts in script web parts, content editor web parts, or visual web parts.


Please see the code below:

<script>
// Provide the Group name
var grpName="Elninos Football Team";
$(document).ready(function() {

 ExecuteOrDelayUntilScriptLoaded(IsCurrentUserMemberOfGroup, "sp.js");
 
});
     
  });
//Ready function ends

function IsCurrentUserMemberOfGroup()
{
       
        var userInGroup;
        var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();    
        var currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);
        var allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);
        currentContext.load(allGroups, 'Include(Users)');
        currentContext.executeQueryAsync(OnSuccess,OnFailure);
       
  
        function OnSuccess(sender, args) {
            var userInGroup = false;
          
            var groupEnumerator = allGroups.getEnumerator();
            while (groupEnumerator.moveNext() && !userInGroup)
            {
               var oGroup = groupEnumerator.get_current();
               if (oGroup.get_title() ==  grpName )
               {
                  var collUser = oGroup.get_users();
                  var userEnumerator = collUser.getEnumerator();
                  while (userEnumerator.moveNext() && !userInGroup)
        {
                  var oUser = userEnumerator.get_current();
                  if (oUser.get_id() == currentUser.get_id())
                   {
                    userInGroup = true;
                    alert("User is a member of the Group you have given");
                   }
                   }
                }
            }
       }
        function OnFailure(sender, args) {
  alert("User not found");
        }      
}
</script>

Wednesday, September 9, 2015

Read user profile Information in sharepoint 2013 and JSOM

Requirement : Read user profile Information in  sharepoint 2013 and JSOM?


Steps to do it :
1.  Create a new page in sharepoint 2013 "UserProfiletest.aspx"
2. Add a script editor webpart to it.
3. Add references to jquery library and sp.js  in the script tag
4. Paste the following code in the script editor webpart .


<script>
 $(document).ready(function () {
            siteUrl = _spPageContextInfo.webServerRelativeUrl;
            GetLoadVision();
        });




        function GetLoadVision() {
           //load sp.js
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
        }




function retrieveListItems(){
var userID="domain/username";
getUserProfile(userID);
}

function getUserProfile(userID)
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var userInfoList = web.get_siteUserInfoList();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' +'<Value Type=\'Number\'>' + userID + '</Value></Eq' +'</Where></Query><RowLimit>1</RowLimit></View');
this.collListItem = userInfoList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
var item = collListItem.itemAt(0);
var profile = item.get_item(‘Notes’);
var pictureUrl = item.get_item(‘Picture’).get_url();
var userImage = document.getElementById(‘myImageContainer’); -> Image object
userImage.src = pictureUrl;
var profileDiv = document.getElementById(‘userProfileContainer’);
profileDiv.innerHTML = profile;
}


</script>


<div id="userProfileContainer’"></div>


That's it... :)

Friday, August 1, 2014

Color Code/replace with images a SharePoint List Column Value in Sharepoint 2013- The outstanding JS link property to the rescue

Wondering how to color code a sharepoint list column based on its value.
You have come to the right page here.. congrats..

Requirement: I have a list called colour code. Now I have a column named Active , which stores Yes or No values.




I need to show ticks for all Yes values and Cross for all No. how will i Do it?


JS Link to the rescue.
1 .Go to your Display Form, open the page in edit mode
2. Now in the webpart properties , go to Miscellaneous tab reference the link to a JS file called Colors.js
Put the following in the JS Link proerty "~sitecollection/style Library/colors.js"

3.  Now just paste the following code in Colors.js  file and upload it to the Style Library of the site.
Note: give  your site collection url in the image tag


(function () {     var statusFieldCtx = {};     statusFieldCtx.Templates = {};     statusFieldCtx.Templates.Fields = {     "Active"://Name of the column for which images needs to be displayed
  {     "View": StatusFieldViewTemplate     }
};     SPClientTemplates.TemplateManager.RegisterTemplateOverrides(     statusFieldCtx     ); })(); function StatusFieldViewTemplate(ctx) {     var _statusValue = ctx.CurrentItem.Active; // Active is the column name    if (_statusValue == 'Yes')     {
        return "<img src=SiteCollectionURL/style%20library/tick.png'/>";         } if (_statusValue == 'No') {     return "<img src= SiteCollectionURL /style%20library/cross.png'/>"; } }


4. that’s it and you are done.. Now just go to the list and refresh your page. See the magic your self:

Friday, April 4, 2014

How to hide the Site Contents link from Quick Launch for all the pages across the sites in sharepoint 2013

If you want this to be done for all the pages in teh site .. you must implement it via the master page ..

This would ensure that it is hidden from all the pages

we are goind to use jquery . Create a js file in teh layouts folder. and paste the following code in it .

$(document).ready(function(){

$('a[href$="/_layouts/15/viewlsts.aspx"]').each(function()

{ $(this).hide(); });

});

Now in the master page please refer to the js file as shown below in the layouts before the close of body tag.

"script type="text/javascript" src="_layouts/15/customjsfile.js"

Tuesday, March 11, 2014

How to get the site collection URL in the masterpage of a SharePoint 2013 site or subsites using Javascript in masterpage

There might be times when you really want to get the URL of the site collection within the master page of sharepoint 2013 sites.

well you can achieve it by using the below javascript line .

Inorder to add script in masterpage , we have to follow the conventional and well known method of the script tag inside the body of HTML.

now within the script tag just copy paste the following function

function getSiteCollectionsURL()

{

var sitecollectionURL = window.location.protocol + "//" + window.location.host +_spPageContextInfo.siteServerRelativeUrl

return sitecollectionURL;

}

the function can be called from anywhere inside the masterpage according to your needs.. it will return the site collection url no matter where you are , ie , whether you are in the subsite or the site collection or the nested subsite.

Thursday, March 6, 2014

Read a list column value using SP services in SharePoint

How can i read  a column value value of a share point list using Jquery and SP services

This can be achieved by the following java script function .

Make sure in your JS page you have refered the jquery and spservices link
//read the tiltle field value of ABC list
function ReadColumnValue()
{

var myvalue=null;
var strViewfields = "<ViewFields><FieldRef Name='Title'/></ViewFields>";
$().SPServices({
webURL: strSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "ABC",

            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
               
if($(this).attr("ows_title")!= undefined)
{

       myvalue=$(this).attr("ows_title");


}
                });
            }

        });



the variable myvalue will containt eh list column value of the tilte field of the AB list




How to make sure if a particular SharePoint Group Exists or Not?

Inorder to know if a particular group exists in sharepoint group collection , just use the following function..

 private bool GroupExists(SPGroupCollection objgroups, string strName)
        {
            const string NAME = "Name";
            bool isGroupExists = false;
            if (string.IsNullOrEmpty(strName) ||

                (strName.Length > 255) ||

                (objgroups == null) ||

                (objgroups.Count == 0))
            {

                isGroupExists = false;
            }

            else
            {
                XDocument doc = XDocument.Parse(objgroups.Xml);
                isGroupExists = doc.Descendants().Where(g => g.Attribute(NAME) != null).Where(g => g.Attribute(NAME).Value.Equals(strName, StringComparison.InvariantCultureIgnoreCase)).Count() > 0;
            }
            return isGroupExists;

        }


The function would return true if the group exists in group collection of sharepoint..


You just have to call the function as shown below :



                SPGroupCollection objSiteGroups = YOURWEBOBJECT.SiteGroups;
                if (GroupExists(objSiteGroups, "YOUR GROUP NAME"))
                {
                   // Do all that you want with the group coz the group does exists
                }
Happy sharepointing :)


Thursday, November 28, 2013

Add a user to a custom group in SharePoint Group - A Function to serve the purpose


How do i add a user to a group using SharePoint Object Model.

The following function will help you to achieve this...

1. Get the loginname of the user and pass it to the following function
2. the following code adds the user to the Sharepoint Group called MYSite_MyGroup1.

public void AddUser(strloginName)
{
if (!string.IsNullOrEmpty(strloginName))
 {                                                                //Gets the Collection of Site Groups
                                SPGroupCollection objSPSiteGroups = objSPWeb.SiteGroups;
                               string  strCustomGroupName = "MYSite_MyGroup1";
                                if (objSPSiteGroups != null && !string.IsNullOrEmpty(strloginName))
                                {                                                                     
                                        // Adds the new user to the MYSite_MyGroup1 group
                                        objSPgpUserGroup = objSPWeb.SiteGroups[strCustomGroupName];

     // Make sure that the user is added to site . the following built in method makes sure it is added to the site
                                        objnewUser = objSPWeb.EnsureUser(strloginName);                                    


              //Add the user to group                         
                                        objSPgpUserGroup.AddUser(objnewUser);
                                        objSPgpUserGroup.Update();                                 
                                   

                                 }
 }
}


And thats it...

Monday, November 25, 2013

How to remove an event Handler from a list ? A method to detach the event handler

In my previous post i explained about a method to add/attach an event handler to a list.

Now what would you do to remove an event handler from a list ?

The following function would help you to achieve the same in sharepoint..

Just like in the adding event handler post , create the following method.



  private void RemoveHandler(SPList objlist, string strrecieverName)
        {
            try
            {
              
                Guid objGuid = new Guid();
                SPEventReceiverDefinition objEvent = objlist.EventReceivers.Cast<SPEventReceiverDefinition>().FirstOrDefault(l=>string.Compare(l.Name,strrecieverName,true)==0);
                if (objEvent != null)
                {
                    objGuid = objEvent.Id;
                }

                if (objGuid.CompareTo(System.Guid.Empty) != 0)
//Deletes the eventHandler object
                    objEvent.Delete();
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }
        }
----------------------------------------------------------------------------------------------------------------------------------------------


Now call the RemoveHandler() method from the feature deactivating method of Reciever.cs .

This will remove the adding and deleting event handler from the test list respectively.


   public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb objweb = (SPWeb)properties.Feature.Parent;
            List<SPList> objspLists = new List<SPList>();
            try
            {
                SPList objTestList = objweb.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title, "TestList", true) == 0);
       
                if (TestList!= null)
                {
                   //Remove the adding and deleting event handler from the test
                    RemoveHandler(objTestList , "AddingEventHandler");
                    RemoveHandler(objTestList , "DeletingEventHandler");
                  
                }
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }

        }

-----------------------------------------------------------------------------------------------------------------------------------------------------------------


How to attach an event handler to a SharePoint List using C#? a simple reusable method for attaching an event handler

Creation of event handler requires creation of an event receiver class in SharePoint .  For this we would  need to create a feature receiver from the already built in template of visual studio.  Once the receiver is created we can use the following code to attach the event handler to any list.


The following is the code to attach the event handler to the list

Reciever.cs

 private void AddHandler(SPList objList, string strRecieverName, int iseqno, SPEventReceiverType eventType)
        {
            try
            {
                SPEventReceiverDefinitionCollection objEventDefColl = objList.EventReceivers;
                ////Set the values for the Definition object 
                Assembly objAssembly = Assembly.GetExecutingAssembly();
                string strAssemblyName = objAssembly.FullName;
               
// MyCustomClass.cs" is the Name of the class in which the logic is writen to handle various events like adding,updating,deleting
                 string strClassName = "MyCustomClass.cs";
      
                string strReceiverName = strRecieverName;
                string strDefData = "Data";
                int iSequenceNo = iseqno;
                ////Create the Definition object 
                SPEventReceiverDefinition oEventDef = objEventDefColl.Add();
                ////Set the properties
                oEventDef.Name = strReceiverName;
                oEventDef.Assembly = strAssemblyName;
                oEventDef.Class = strClassName;
                oEventDef.Data = strDefData;
                oEventDef.SequenceNumber = iSequenceNo;
                oEventDef.Type = eventType;
                oEventDef.Update();
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }
        }


---------------------------------------------------------------------------------------------------------------------------------------------

Now in the reciever.cs file just call the method AddHandler inside the FeatureActivated Mehod.

This will enable the event handler to be attached to the TestList as soon as the feature is activated on thesite


  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb objweb = (SPWeb)properties.Feature.Parent;
                SPList objTestList= objweb.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title,TestList, true) == 0);
                //Attach the ItemAdded event and the ItemDeletingEvent
                if (objTestList!= null)
                {
                   
                    AddHandler(objTestList, "AddingEventHandler", 10003, SPEventReceiverType.ItemAdding);
                    AddHandler(objTestList, "DeletingEventHandler", 10002, SPEventReceiverType.ItemDeleting);
                                    
                    
                }
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }

        }

--------------------------------------------------------------------------------------------------


Happy SharePointing again :)


Sunday, November 24, 2013

what is the maximum file size limit in Sharepoint 2013 ?

what is the maximum file size limit in SharePoint 2013 ?

Its 2GB.

Yes the maximum size of file should not exceed 2 GB.

Tuesday, October 22, 2013

Handling List with Huge Amount of Data/Items ? -- the Concept of ContentIterator

How to Handle Large list data in SharePoint?
SPQuery Fails for Large Lists Items?
Unable to Retrieve list item from large lists? 

ContentIterator to the rescue...


so how to use it? 
 If indexed column condition return more value than List View Threshold, it handles by batch..

      Simply include the  Microsoft.Office.Server.dll which is available in 14/ISAPI/
2    Include namespace Microsoft.Office.Server.Utilities. as reference


So what it gives us??
· Fetches list items as a batch so it reduces the load.
· Batch Procesing can be stopped at anytime.
· Alternative to SPQuery as it fails for large data greater than list threshold


It works as follows
SPQuery.ListItemCollectionPosition in 2007 MOSS  helps to fetch large number of items efficiently in the batches. ContentIterator.ProcessListItems method make use of SPQuery.ListItemCollectionPosition internally in a such way that its value is less than the list threshold value .

ContentIterator will run through each item in the list, invoking the callback provided for list item processing—in this case, ProcessItem. If an error occurs while iterating the list, then the error function is invoked—in this case, ProcessError. Using this approach the ContentIterator processes the list in pieces and avoids any excessively large queries. This functionality is provided as part of Enterprise Content Management (ECM) in SharePoint Server 2010.


static int exceptions = 0;
static int items = 0;

protected void OnTestContentIterator(object sender, EventArgs args)
{
    items = 0;
    exceptions = 0;
    string query1 = @"<View>
        <Query>
            <Where>
                <And>
                    <BeginsWith>
                        <FieldRef Name='Title' />
                        <Value Type='Text'>A</Value>
                    </BeginsWith>
                </And>
            </Where>
        </Query>
    </View>";

    ContentIterator iterator = new ContentIterator();
    SPQuery listQuery = new SPQuery();
    listQuery.Query = query1;
    SPList list = SPContext.Current.Web.Lists["Parts"];
    iterator.ProcessListItems(list,listQuery,ProcessItem,ProcessError)
    );
}

public    bool ProcessError(SPListItem item, Exception e)
{
    // process the error
    exceptions++;
    return true;
}
public void ProcessItem(SPListItem item)
{
    items++;
    Do what you wish with the item


}


Rename a Web Application in Sharepoint : A solution using powershell

Here is a small script that will enable you all to change a SharePoint Web Application name . We can use the following SharePoint Pow...