Tuesday, December 22, 2015

Easiest way to add Auto complete lookup to SharePoint 2013 or Online Form Fields using SPServices.

Today we will see how can we add an auto complete function to a SharePoint field in SharePoint 2013 or Online using SPServices. It will provide an easier way to provide user lookup functionality as a help instead of mandatory way and also add below code to on NewForm.aspx of your destination List by adding a Script Editor Webpart:

<script language="javascript" src="//code.jquery.com/jquery-1.6.2.min.js"
type="text/javascript"></script>
<script language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices-2014.02.min.js"
type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $().SPServices.SPAutocomplete({
            sourceList: "SourceList", // Source List Name
            sourceColumn: "Title", // Source List Column from where you want to fetch it.
            columnName: "DestinationListColumn", // Destination List Column where you wan to add it.
            ignoreCase: true,
            numChars: 2,
            slideDownSpeed: 'fast'
        });
    });</script>

Wednesday, August 19, 2015

Best way to validate a SharePoint Enhanced Rich text field using JQuery.

Recently I got a requirement to create a new Enhanced Rich text field in my existing application. We also need to validate that its not blank. So at first I know, it will be bit complex due to any obvious selector unavailability for Enhanced Rich Text Field in SharePoint. I searched a lot and found no. of suggestion but nothing seems very logical to me and also did not work for me. Then I have written below script to deal with it.

//Rich Text Field Validation Code

var RichtTxtContent = $('nobr:contains("Rich Text Field Title")').closest('tr').find('div[id$="TextField_inplacerte"]').text();
if( RichtTxtContent.length === 1 ||  RichtTxtContent.length === 0)
{
alert("Please enter  Richt Text Content .");
SetRemoveStyleOnFocus($('nobr:contains("Rich Text Field Title")').closest('tr').find('div[id$="TextField_inplacerte"]'));
return false;

I have just selected whole Row with the Rich Text Field Title, then found out a div with the text its always append it into this div client Id. Refer below screen shot to see the ID.


Then we need to check length as by default its set to 1. We need to compare with both 1 and 0.


Here is a function which will make sure that field is highlighted with focus whenever its blank. You can write your own classes to highlight it.

function SetRemoveStyleOnFocus(inputField)
{
$(inputField).focus(function() {
    $(this).addClass("focus");
});
$(inputField).blur(function() {
    $(this).removeClass("focus");
    });

    $(inputField).focus();
}

We just need to call this piece of code on Pre Save event of a SharePoint OOB New\Edit form or any other event as per need.


Validate no. of characters and their type entered into any input field using Java Script.

Here are I am writing an example how can we make sure that entered input in a filed should be only a 6 Digit number. You can modify it to according to your requirements:

var InputFieldValue = $("#InputFiledID").val();//Bit Jquery :) You can use java script too.

if( InputFieldValue!= '')
    {
var digits = "0123456789";
        var temp;
        if (InputFieldValue.length > 6){
        alert("Entered value cannot be more than 6 Digit Numbers ");
        return false;
        }
        else if(InputFieldValue.length < 6){
        alert("Entered value cannot be less than 6 Digit Numbers ");
        return false;
        }
        else {
for (var i = 0; i < InputFieldValue.length ; i++) {
        temp = InputFieldValue.substring(i, i + 1);
        if (digits.indexOf(temp) == -1) {
        alert("Entered value cannot contain any Character.");
        return false;
        }
        }
        }
     }

On the above code we have provided a string of characters which we want to permit as inputs. In this case we want to validate against numerals.  Then we select each character of input field value and try to find it into our format string, if it does not contain we return vale as false.

This can be extend for checking against any format.

Here is an example how can we extend it. For an input in this format "xx-xx-xx" where 'x' needs to be a number:

if( InputFieldValue != '')
{
var digits = "0123456789";
        var temp;
        if (InputFieldValue.length > 8){
        alert("Entered Value cannot be more than 6 Digit Numbers ");
                return false;
                }
                else if(InputFieldValue.length < 8)
                {
                alert("Entered Value cannot be less than 6 Digit Numbers ");
                return false;
                }
                else {
for (var i = 0; i < InputFieldValue.length; i++) {
            temp =InputFieldValue.substring(i, i + 1);
            if(i==2|| i==5)
            {
            if(temp!='-')
            {
            alert("Entered Value be in xx-xx-xx format. Does not conation - in current values.");
                   return false;
                   }
            }
            else if (digits.indexOf(temp) == -1) {
                alert("Entered Value cannot contain any Character ");
                return false;
            }
            }
             }
            }

On the above code, we are making sure that on 3rd and 5th position its always contain '-'.

Hope it helps someone.


Thursday, July 16, 2015

Creating multiple layer of folders in SharePoint using SPServices and Jquery on any version.

Recently I got a requirement, where user wants to create a set of multiple layer of multiple folders. Creating all those folders one by one with same structure manually is very time consuming work. At the same time we wanted not to deploy any custom C# solution and we need it on SP2007. So I decided to use SPServices.

Below is the code which I have added into a Content Editor Webpart:

<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://www.sympraxisconsulting.com/Demos/jQuery%20Libraries/jquery.SPServices-0.6.0.min.js"></script>
<script language="javascript" type="text/javascript">
  $(document).ready(function() {
  });

function CallOnButtonClick()
{
var librarynaem = "List or Library Title";
var newfolder = document.getElementById("topFolderName").value;
CreateFolder(librarynaem, newfolder);
}  

function CreateFolder(librarynaem, newfolder) {
 jQuery().SPServices({
  operation: "UpdateListItems",
  async: false,
  listName: librarynaem ,
  updates: "<Batch OnError='Continue' PreCalc='TRUE' ListVersion='0' >" +
    "<Method ID='1' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder + "</Field>" +
    "</Method>" +
    "<Method ID='2' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder1"+ "</Field>" +
    "</Method>" +
"<Method ID='3' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder1/Folder11"+ "</Field>" +
    "</Method>" +
"<Method ID='4' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder1/Folder12"+ "</Field>" +
    "</Method>" +
"<Method ID='5' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder2"+ "</Field>" +
    "</Method>" +
"<Method ID='6' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder3"+ "</Field>" +
    "</Method>" +
"<Method ID='7' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder3/Folder31"+ "</Field>" +
    "</Method>" +
"<Method ID='8' Cmd='New'>" +
     "<Field Name='FSObjType'>1</Field>" +
     "<Field Name='BaseName'>" + newfolder +"/Folder3/Folder32"+ "</Field>" +
    "</Method>" +
   "</Batch>",
  completefunc: function(xData, Status) {
   //alert("Status=" + Status); 
alert("New Service Added. Please refresh.");
 document.getElementById("topFolderName").value = "";
   }
 });
 }
  
</script>
<input type="text" id="topFolderName" />
<input type="button" onclick="CallOnButtonClick()" value="Add New Folder Structure">

Running this code will create folders and sub folders. We can create it any level using "/" for a new level in name parameter.

Friday, July 10, 2015

Find out users from a particular domain and remove them from whole SharePoint web application with checking status in Active Directory.

Recently we have got an requirement to remove users from a particular domain from SharePoint Web-application. In addition to it we also need to check if that user is still active on that Active Directory.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CheckCurrentUserStatus
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Started...");

            Console.WriteLine("Please enter any site collection URL to access Web Application and press enter");
            string siteURL = Convert.ToString(Console.ReadLine());

            Console.WriteLine("Please enter domain name and press enter.");
            string DomainName = Convert.ToString(Console.ReadLine());
            string StartedTime = DateTime.Now.ToString();

            Console.WriteLine("Started For... Site URL " + siteURL + " and Doamin Name " + DomainName);
            GetAllUsersFormADomain(siteURL, DomainName);
            Console.WriteLine("Stared Executing at : " + StartedTime);
            Console.WriteLine("Complted Executing at : " + System.DateTime.Now.ToString());
            Console.Read();
        }

        private static bool DoesUserExistsDisabledAndDeletable(string strDomain, string strUserName)
         {
                 bool isUserExistsAndDisabled = false; 
                    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, strDomain))
                    {
                       isUserExistsAndDisabled =  ForEachUserNameCheckExistsAndDisabled(strDomain, strUserName, pc);
                    }
                 return isUserExistsAndDisabled;

         }

        private static bool ForEachUserNameCheckExistsAndDisabled(string strDomain, string strUserName, PrincipalContext pc)
        {
            bool isUserExistsAndDisabled = false;
            
            UserPrincipal up = UserPrincipal.FindByIdentity(pc, strUserName);

            bool UserExists = (up != null);
            if (UserExists)
            {
                bool isEnabled = (bool)up.Enabled;
                if (isEnabled)
                {
                    isUserExistsAndDisabled = false;
                    Console.WriteLine(strDomain + " " + strUserName + " " + "Account Enabled...!!!");
                    File.AppendAllText("UsersStatus.txt", strDomain + " " + strUserName + " " + "Account Enabled...!!! Can not be Deleted." + "\r\n");
                    //TextWriter tsw = new StreamWriter(@"UsersStatusEnabled.txt", true);
                }
                else
                {
                    isUserExistsAndDisabled = true;
                    Console.WriteLine(strDomain + " " + strUserName + " " + "Account is Disabled...!!!");
                    File.AppendAllText("UsersStatus.txt", strDomain + " " + strUserName + " " + "Account is Disabled...!!! Deleted from SharePoint" + "\r\n");
                                 
                    //TextWriter tsw = new StreamWriter(@"UsersStatusDisabled.txt", true);
                }
            }
            else
            {
                isUserExistsAndDisabled = true;
                Console.WriteLine(strDomain + " " + strUserName + " " + "Account does not exists...!!!");

                File.AppendAllText("UsersStatus.txt", strDomain + " " + strUserName + " " + "Account does not exists...!!! Deleted from SharePoint." + "\r\n");
                //TextWriter tsw = new StreamWriter(@"UsersNotFound.txt", true);
            }
            return isUserExistsAndDisabled;
        }

        private static void GetAllUsersFormADomain(string siteURL, string DomainName)
        {
           
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite objSPSite = new SPSite(siteURL))
                {
                    if (objSPSite!=null)
                    {
                        DeleteUsers(objSPSite, DomainName);
                    }
                }
                
            });
        }

        private static void DeleteUsers(SPSite objSPSite, string DomainName)
        {
            SPWebApplication objSPWebApp = objSPSite.WebApplication;
                    foreach (SPSite siteCollection in objSPWebApp.Sites)
                    {
                        foreach (SPWeb web in siteCollection.AllWebs)
                        {
                            SPUserCollection objSPColl = web.AllUsers;
                            foreach (SPUser user in web.AllUsers)
                            {
                                string[] DomainAndUserName = user.LoginName.ToString().Split('\\');
                                if (DomainAndUserName != null && DomainAndUserName.Length > 0)
                                {
                                    string Domain = DomainAndUserName[0];
                                    string UserName = DomainAndUserName[1];
                                    if (Domain.ToLower().Equals(DomainName.ToLower()))
                                    {
                                        if (DoesUserExistsDisabledAndDeletable(DomainName.ToLower(), user.LoginName))
                                        {
                                            web.SiteUsers.Remove(user.LoginName);
                                        }
                                    }
                                }

                            }
                        }
                   }
        }

        
    }
}





Thursday, July 2, 2015

CRUD Operation in SharePoint List Using REST API in Windows Form with C#

Here is how we can we perform SharePoint List Add, Update and delete operations using REST API.

Structure of Form Solution we need to add a Service Reference with below URL:

http://severname:portname/sites/sitename/_vti_bin/listdata.svc

Add a Data Source using service reference by putting same URL:



Structure of the windows form application will be as below:


Now write below code to perform all operations:

namespace RESTExample
{
    public partial class REST : Form
    {
        BidManagementDataContext context;

        private void InitContext()
        {
            context = new BidManagementDataContext(new Uri("http://jsy-shpwebvt003:19891/sites/BidManagement/_vti_bin/ListData.svc"));
            context.Credentials = CredentialCache.DefaultCredentials;
        }

        public REST()
        {
            
            InitializeComponent();
        }

        private void Add_Click(object sender, EventArgs e)
        {
            InitContext();
            NotesItem objNotes = new NotesItem() { Title = "Insterted through Rest" };
            context.AddToNotes(objNotes);
            context.SaveChanges();
            BindList();
            
        }

        private void Update_Click(object sender, EventArgs e)
        {
            InitContext();
            NotesItem objNotes = context.Notes.FirstOrDefault();
            objNotes.Title = "Updated by Code...";
            context.UpdateObject(objNotes);
            context.SaveChanges();
            BindList();
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            InitContext();
            NotesItem objNotes = context.Notes.FirstOrDefault();
            //objNotes.Title = "Updated by Code...";
            context.DeleteObject(objNotes);
            context.SaveChanges();
            BindList();
        }

        private void REST_Load(object sender, EventArgs e)
        {
            BindList();
        }

        private void BindList()
        {
            InitContext();
            notesBindingSource.DataSource = context.Notes;
        }

        
    }
}

Thursday, June 25, 2015

Redirect a SharePoint Edit form with ID without using any JavaScript using SharePoint Save feature.

To get ID of an item from a OOB SharePoint Custom edit page, we have to add get this from Query String. To pass it into OOB Save functionality. We have to pass it on the below

To redirect without any XSL variable:


<td class="ms-separator">&#160;</td>
                                                                                                                <td class="ms-toolbar" nowrap="">
                                                                                                                <input type="button" class="ms-ButtonHeightWidth" style="width:13em!important" value="Save and Redirect" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={abc.aspx?Type=New}')}" />
                                                                                                </td>

In edit form with ID parameter:

Find this text:
                <xsl:param name="dvt_apos">&apos;</xsl:param>
                <xsl:variable name="dvt_1_automode">0</xsl:variable>

Add below text to store value in an XSL variable:

                <xsl:param name="ListItemId" />
    <xsl:variable name="RedirectLoc">abc.aspx?ItemID=<xsl:value-of select="$ListItemId"/></xsl:variable>


<input type="button" class="ms-ButtonHeightWidth" style="width:16em!important"  value="Save and Redirect" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={',$RedirectLoc,'}'))}"/>

Now if you wan tot fire PreSaveAction in addition to it, here are the important links to understand what is happening. Below I am writing what we need to add on our page:

Add this function to your JS of form:

function PreSaveItem()
 {
       if ("function"==typeof(PreSaveAction))
       {
         return PreSaveAction();
       }
     return true;
 }

Then change your button to below code:

<input type="button" class="ms-ButtonHeightWidth" style="width:16em!important" value="Save and Redirect" name="Save and Redirect" onclick="if (!PreSaveItem()) return false;{ddwrt:GenFireServerEvent(concat('__commit;__redirect={',$RedirectLoc,'}'))}" />

Now PreSaveAction will also be fired before redirecting. Also in case of multiple save button on forms, we can write something Just before PreSaveAction.