Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Monday, April 16, 2018

Rotate an image n number of times

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

            });

        }

    });

}

 

function ShowRefreshError() {

 

    var element = document.createElement('div');

    var refresherror = '<div  id="dialog" title="Refresh Failed.">' +

        '  If the problem persists, please contact the <a href="https://google.com/"> HelpDesk</a>' +

        ' <div  align="center"> </br><input onclick="return SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, value);" type="button" value="OK" name="opret_ok"> </div> ' +

        '</div>';

    element.innerHTML = refresherror;

 

    var options = {

        html: element,

        title: 'Refresh Failed.',

        allowMaximize: false,

        showClose: false,

        autoSize: true

    };

 

    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);

}

 

RefreshLink = function () {

 

    var elemn = $("a[title|='Refresh] > img");

    AnimateRotate(360, 2, elemn);

 

    $.ajax({

        cache: false,

        type: "GET",

        url: "https://google.com?webAddress,

        crossDomain: true,

        xhrFields: {

            withCredentials: true

        },

        success: function (data) {

            }

            else {

                ShowRefreshError();

            }

        },

        error: function (status, error) {

            ShowRefreshError();

        }

    });

};

 

 

 

Friday, February 9, 2018

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

public static List<ListItem> GetAllListItemsInaList1(ClientContext ctx, string siteurl)

        {

List<ListItem> items = new List<ListItem>();

            ctx.Load(ctx.Web, a => a.Lists);

            ctx.ExecuteQuery();

List list = ctx.Web.Lists.GetByTitle("EngagementDocumentLibrary");

ListItemCollectionPosition position = null;

int rowLimit = 4999;

var camlQuery = new CamlQuery();

            camlQuery.ViewXml = @"<View Scope='RecursiveAll'>

            <Query>

<OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy>              

            </Query>

            <ViewFields>

                <FieldRef Name='FileLeafRef'/><FieldRef Name='File_x0020_Type' /><FieldRef Name='FileRef' /><FieldRef Name='Editor' />

            </ViewFields>

            <RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>";

do

            {

ListItemCollection listItems = null;

                camlQuery.ListItemCollectionPosition = position;

                listItems = list.GetItems(camlQuery);

                ctx.Load(listItems);

                ctx.ExecuteQuery();

                position = listItems.ListItemCollectionPosition;

                items.AddRange(listItems.ToList());

            }

while (position != null);

            items = items.OrderBy(item => item.FieldValues["FileLeafRef"]).ToList();

return items;

        }


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;


}