Monday, April 16, 2018

Rotate an image n number of times

Rotate an image n number of times



script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">

$(document).ready(function(){
 
    var elemn = $("a[title|='Refresh Access'] > img");
    AnimateRotate(360,"infinite",elemn);
   
    }); 
   
 function AnimateRotate(angle,repeat,elemn) {
    var duration= 1000;
    setTimeout(function() {
        if(repeat && repeat == "infinite") {
            AnimateRotate(angle,repeat,elemn);
        } else if ( repeat && repeat > 1) {
            AnimateRotate(angle, repeat-1,elemn);
        }
    },duration)   
    var $elem = elemn;
    $({deg: 0}).animate({deg: angle}, {
        duration: duration,
        step: function(now) {
            $elem.css({
                'transform': 'rotate('+ now +'deg)'
            });
        }
    });
}

Friday, March 16, 2018


I had a requirement to move root level site collection as a subsite, as everyone knows this can be done by using the Granular back up for the site, you need to take .cmp file,
I tried to restore the site to a sub site, i was unable to import it as the site template for the destination site is not matching with the backup file which i took,
i.e. The back up which i took is BLANKINTERNET#0 web template, and i created a blank site wanted to override this site, i.e. STS#1, then again i tried to create a publishing site as the source was the publishing site, again this did not work, becouse  destination was CMSINTERENET#1 site,
the best solution is to create site of source site, i wrote a power shell script to achieve this,

Fixing: The client and server cannot communicate, because they do not possess a common algorithm


A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The client and server cannot communicate, because they do not possess a common algorithm.) (Microsoft SQL Server, Error: -2146893007)"

run below PS in your server, I got it from somewhere from internet. which fixed my servers
note: it will ask for restart.

Friday, February 9, 2018

Powershell to add dummy documents to SharePoint List for Testing purpose

Write-Host "Loading SharePoint Powershell Snapin"
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'} 
if ($snapin -eq $null) {  Add-PSSnapin "Microsoft.SharePoint.Powershell" }

# ---- Script settings ----
$sourceDocumentPath = "C:\temp\TestDoc.docx" # Source document to spawn new documents from for the creation
$newFilenamePrefix = "TestDoc"
$newFilenameExtension = ".docx"
$numberDocsToCreate = 5000

# Settings for the destination to create documents in

$webUrl = "http://site:1111/sites/tdm3"
$docLibraryName = "Lib"
$folderPathWithinDocLibrary = "" # Leave empty e.g. "" to create documents in root folder of library otherwise specify path relative to root folder e.g. "/Testing/Folder A"

# -------------------------

#Open web and library
$web = Get-SPWeb $webUrl
$docLibrary = $web.Lists[$docLibraryName]
$docLibraryUrl = $docLibrary.RootFolder.ServerRelativeUrl
$uploadfolder = $web.getfolder($docLibraryUrl + $folderPathWithinDocLibrary)

#Open file
$file = get-item $sourceDocumentPath
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

# Create documents in SharePoint
write-host "Creating $i documents based on the file $sourceDocumentPath"

for($i=1; $i -le $numberDocsToCreate; $i++)
{
$newFilePath = $docLibraryUrl + $folderPathWithinDocLibrary + "/" + $newFilenamePrefix+$i+$newFilenameExtension
write-host "Creating document: $newFilePath ..."
$spFile = $uploadfolder.Files.Add($newFilePath, [System.IO.Stream]$fileStream, $true)
}

write-host "Completed"

#Close file stream
$fileStream.Close()

#Dispose web
$web.Dispose()

Schedule Nintex Workflows to ListItems via Nintex web service


Small Utility to Schedule Nintex Workflows to SharePoint ListItems via Nintex web service

internal class Program
    {
        private static void Main(string[] args)
        {
            var sourceListName = "EIQ"; //
            var siteUrl = "http://site:3333";
            var UserName = "dtu";
            var pwd = "Password10";
            var domain = "dev";
            string env = "DEV";
            string workflowName = "IncompleteForm_WF";
            try
            {
                ClientContext clientContext = null;
                if (env.ToUpper() == "DEV")
                {
                    clientContext = Auth(siteUrl, UserName, pwd, domain);
                }
                else if (env.ToUpper() == "UAT")
                {
                    clientContext = MixedAuthRequest(siteUrl, UserName, pwd, domain);
                }

                NintexWorkflowWSSoapClient soapClient = InitializeNintexSoapClienn(UserName, pwd, domain);
                Microsoft.SharePoint.Client.User spUser;
                spUser = clientContext.Web.CurrentUser;
                Console.WriteLine("Loading User!");
                clientContext.Load(spUser, user => user.LoginName);
                Console.WriteLine("Loading Login Name");
                clientContext.ExecuteQuery();
                Console.WriteLine(spUser.LoginName);
                //Process EID list items
                ProcessEIQItems(clientContext, sourceListName, soapClient, workflowName);
                Console.ReadLine();
            }
            catch (Exception ex)
            {

                string message = "Error in main method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                Console.ReadLine();
            }
        }

        private static NintexWorkflowWSSoapClient InitializeNintexSoapClienn(string UserName, string pwd, string domain)
        {
            try
            {
                var soapClient = new NintexWorkflowWSSoapClient("NintexWorkflowWSSoap");
                //need to name the endpoint being used.
                soapClient.ClientCredentials.Windows.ClientCredential.UserName = UserName;
                soapClient.ClientCredentials.Windows.ClientCredential.Password = pwd;
                soapClient.ClientCredentials.Windows.ClientCredential.Domain = domain; //optional
                                                                                       //soapClient.ClientCredentials.Windows.AllowNtlm = true; //optional
                soapClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; //optional
                return soapClient;
            }
            catch (Exception ex)
            {
                string message = "Error in Initialising the Nintexwebservice soap method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                throw ex;
            }
        }

        private static void ProcessEIQItems(ClientContext clientContext, string listName, NintexWorkflowWSSoapClient soapClient, string workflowName)
        {
            ListItemCollection olistItems = null; 
            try
            {
                Microsoft.SharePoint.Client.List oList = clientContext.Web.Lists.GetByTitle(listName);
                CamlQuery query = new CamlQuery();
                query.ViewXml = string.Format("true" +
                    "
");
                olistItems = oList.GetItems(query);
                clientContext.Load(olistItems);
                clientContext.ExecuteQuery();
                if (olistItems != null && olistItems.Count > 0)
                {
                    foreach (ListItem listItem in olistItems)
                    {
                        var strDate = Convert.ToDateTime(listItem["NextReminderDate"].ToString());
                        if (strDate != null)
                        {
                            ScheduleNintexWrorkflow(listName, soapClient, workflowName, listItem, strDate);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                string message = "Error in ProcessEIQItems method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                throw ex;
            }
        }

        private static void ScheduleNintexWrorkflow(string listName, NintexWorkflowWSSoapClient soapClient, string workflowName, ListItem listItem, DateTime strDate)
        {
            try
            {             
                Schedule sc = new Schedule();
                sc.StartTime = strDate;
                RepeatInterval ri = new RepeatInterval();
                ri.CountBetweenIntervals = 14;
                ri.Type = RepeatIntervalType.Hourly;
                sc.RepeatInterval = ri;
                sc.MaximumRepeats = 0;
                sc.WorkdaysOnly = false;
                sc.EndOn = EndScheduleOn.RepeatCount;
                var ret = soapClient.AddWorkflowScheduleOnListItem(Convert.ToInt32(listItem["ID"]), listName, workflowName, "", sc, true);
            }
            catch (Exception ex)
            {
                string message = "Error in Scheduling the item ID: " + Convert.ToString(listItem["ID"]);
                Console.WriteLine(message);
                ErrorLogging(ex, message);
            }
        }

        public static void ErrorLogging(Exception ex, string message)
        {
            string strPath = @"D:\NintexScheuldeWFLog.txt";
            if (!System.IO.File.Exists(strPath))
            {
                System.IO.File.Create(strPath).Dispose();
            }
            using (StreamWriter sw = System.IO.File.AppendText(strPath))
            {
                sw.WriteLine(message + ",Error Message: " + ex.Message);
            }
        }

        private static ClientContext MixedAuthRequest(string siteUrl, string userName, string pwd, string domain)
        {
            ClientContext returnContext = null;
            ClientContext spClientContext = null;

            int retryCount = 5; // Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["retryCount"]);   

            for (int i = 0; i <= retryCount; i++)
            {
                try
                {
                    using (spClientContext = new ClientContext(siteUrl))
                    {

                        spClientContext.ExecutingWebRequest += new EventHandler(Ctx_MixedAuthRequest);
                        spClientContext.AuthenticationMode = ClientAuthenticationMode.Default;




                        spClientContext.Credentials = new NetworkCredential(userName, pwd, domain);
                        returnContext = spClientContext;

                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (i == retryCount)
                    {
                        Console.WriteLine("Falied Mixed Auth Context: " + ex.Message);
                        throw;
                    }
                }
            }
            return returnContext;
        }

        private static void Ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
        {
            //Add the header that tells SharePoint to use Windows authentication.
            e.WebRequestExecutor.RequestHeaders.Add(
            "X-FORMS_BASED_AUTH_ACCEPTED", "f");
        }

        public static ClientContext Auth(string siteURL, string username, string password, string domain)
        {
            ClientContext context = new ClientContext(siteURL);
            Web web = context.Web;


            // for network credentials
            NetworkCredential _myCredentials = new NetworkCredential(username, password, domain);
            context.AuthenticationMode = ClientAuthenticationMode.Default;
            context.Credentials = _myCredentials;
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

            //context.Credentials = new SharePointOnlineCredentials(spoUserName, pwd);
            try
            {
                context.Load(web);
                context.ExecuteQuery();
                Console.WriteLine("Authentication Succesful for " + web.Title + " site");
                return context;
            }
            catch (Exception e)
            {
                Console.WriteLine("Authentication failed.");
                return null;
            }
        }

    }

Get All List Items from SharePoint List page wise to handle threshold limit


Below is the common error during development:
The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator. 
How to handle in client object model?
  • To avoid threshold error, we can use below orderby query.
OrderBy Override='TRUE'>

  • Using Sorting on the returned list
items = items.OrderBy(item => item.FieldValues["FileLeafRef"]).ToList();
  • Implementing the search on the items. Sample below which brings matched document string name on the page
items = items.FindAll(f => f.FieldValues["FileLeafRef"].ToString().ToLower().Contains("".ToLower())).ToList();

  •  Complete Method

Check if SharePoint Group Exists Client Object Model


Check if SharePoint Group Exists Client Object Model

Web web = clientContext.Site.RootWeb;
clientContext.ExecuteQuery();
var currentGroups = web.SiteGroups;
clientContext.Load(currentGroups);
clientContext.ExecuteQuery();
bool isGroupExists = false;
if (currentGroups.Count > 0)
{
isGroupExists = currentGroups.OfTypeGroup>().Count(g => g.Title.Equals(“Pass your groupname”, StringComparison.InvariantCultureIgnoreCase)) > 0;


}