protected ListItem SearchItemByName(List list, Folder folder, string pageName)
        {
            var context = list.Context;

            if (folder != null)
            {
                if (!folder.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    folder.Context.Load(folder, f => f.ServerRelativeUrl);
                    folder.Context.ExecuteQueryWithTrace();
                }
            }

            var dQuery = new CamlQuery();

            string QueryString = "<View><Query><Where>" +
                             "<Eq>" +
                               "<FieldRef Name=\"FileLeafRef\"/>" +
                                "<Value Type=\"Text\">" + pageName + "</Value>" +
                             "</Eq>" +
                            "</Where></Query></View>";

            dQuery.ViewXml = QueryString;

            if (folder != null)
                dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;

            var collListItems = list.GetItems(dQuery);

            context.Load(collListItems);
            context.ExecuteQueryWithTrace();

            return collListItems.FirstOrDefault();

        }
Пример #2
0
        private bool ThemeEntryExists(Web web, List themeList, string themeName)
        {

            CamlQuery query = new CamlQuery();
            string camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";
            // Let's update the theme name accordingly
            camlString = string.Format(camlString, themeName);
            query.ViewXml = camlString;
            var found = themeList.GetItems(query);
            web.Context.Load(found);
            web.Context.ExecuteQuery();
            if (found.Count > 0)
            {
                return true;
            }
            return false;
        }
        public int CreateSiteRequest(SiteCreationRequestArgs args, string listName)
        {
            _siteRequestList = _sharePoint.RootWeb.Lists.GetByTitle(listName);

            // Check to see we haven't already created a list item for this project.
            var query = string.Format(@"<View><Query><Where><Eq><FieldRef Name='UrdmsSiteId'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", args.SiteId);
            var camlQuery = new CamlQuery { ViewXml = query };

            var existingRequests = _siteRequestList.GetItems(camlQuery);
            _sharePoint.ClientContext.Load(existingRequests);
            _sharePoint.ClientContext.ExecuteQuery();

            int id;

            if (existingRequests.Count == 0)
            {
                id = CreateNewRequest(args.SiteId, args.Title, args.Description, args.Owners, args.Members, args.Visitors);
                Log.InfoFormat("Created new site request with ID: {0}", id);
            }
            else
            {
                id = existingRequests[0].Id;
            }

            return id;
        }
Пример #4
0
        private void BindData()
        {
            ClientContext clientContext = Util.GetContext();
            Web web = clientContext.Web;
            ListCollection spLists = web.Lists;
            spList = spLists.GetByTitle("Business Partner Survey");
            clientContext.Load(spList);

            listItems = spList.GetItems(CamlQuery.CreateAllItemsQuery());
            clientContext.Load(listItems);
            clientContext.ExecuteQueryAsync(GridSucceededCallback, webFailedCallback);
        }
Пример #5
0
 /// <summary>
 /// Function to verify if Folder already exists in Site Assets
 /// </summary>
 /// <param name="matterCenterAssetsFolder">Matter Center Assets Folder</param>
 /// <param name="clientContext">Client Context</param>
 /// <param name="siteAssets">Site Assets</param>
 /// <param name="matterLandingFolder">Matter Landing Folder</param>
 /// <param name="listFolders">List Folder</param>
 /// <returns>List of items in folder</returns>
 private static ListItemCollection CheckFolderExists(string matterCenterAssetsFolder, ClientContext clientContext, out List siteAssets, out ListItemCollection matterLandingFolder, out FolderCollection listFolders)
 {
     CamlQuery camlQuery = new CamlQuery();
     camlQuery.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Folder'>" + matterCenterAssetsFolder + "</Value></Eq></Where></Query><ViewFields><FieldRef Name='FileLeafRef' /></ViewFields></View>";
     siteAssets = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["LibraryName"]);
     matterLandingFolder = siteAssets.GetItems(camlQuery);
     listFolders = siteAssets.RootFolder.Folders;
     clientContext.Load(matterLandingFolder);
     clientContext.Load(siteAssets.RootFolder);
     clientContext.Load(listFolders);
     clientContext.ExecuteQuery();
     return matterLandingFolder;
 }
Пример #6
0
        public MainPage()
        {
            InitializeComponent();

            _clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite");

            Web site = _clientContext.Web;
            _list = site.Lists.GetByTitle("Important Documents");

            _items = _list.GetItems(new CamlQuery());
            _clientContext.Load(_items);
            _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);
        }
Пример #7
0
        private void GetListItemsClientObjectModel()
        {
            _clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite");

            Web site = _clientContext.Web;
            _list = site.Lists.GetByTitle("Death Star Inventory 2");

            _items = _list.GetItems(new CamlQuery());
            //_clientContext.Load(_items);
            _clientContext.Load(_items, items => items.Include(i => i["Item_x0020_Type"], i => i["Fire_x0020_Power"], i => i["Title"]));

            _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);
        }
        protected override ListItem FindListItem(List list, Folder folder, ListItemDefinition definition)
        {
            var context = list.Context;

            // by name
            var items = list.GetItems(new CamlQuery
            {
                FolderServerRelativeUrl = folder.ServerRelativeUrl,
                ViewXml = string.Format(@"<View>
                                          <Query>
                                             <Where>
                                                 <Eq>
                                                     <FieldRef Name='Name'/>
                                                     <Value Type='Text'>{0}</Value>
                                                 </Eq>
                                                </Where>
                                            </Query>
                                         </View>", definition.Title)
            });

            context.Load(items);
            context.ExecuteQueryWithTrace();

            if (items.Count > 0)
                return items[0];

            // by title
            items = list.GetItems(new CamlQuery
            {
                FolderServerRelativeUrl = folder.ServerRelativeUrl,
                ViewXml = string.Format(@"<View>
                                          <Query>
                                             <Where>
                                                 <Eq>
                                                     <FieldRef Name='Title'/>
                                                     <Value Type='Text'>{0}</Value>
                                                 </Eq>
                                                </Where>
                                            </Query>
                                         </View>", definition.Title)
            });

            context.Load(items);
            context.ExecuteQueryWithTrace();

            if (items.Count > 0)
                return items[0];

            return null;
        }
Пример #9
0
        static void Main()
        {
            //Added for O365
            SecureString password = GetPasswordFromConsoleInput();
            clientContext.Credentials = new SharePointOnlineCredentials(username, password);

              clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(site.Lists);
              clientContext.ExecuteQuery();

              listProducts = site.Lists.GetByTitle("Products");
              clientContext.Load(listProducts);

              listProductImages = site.Lists.GetByTitle("Product Images");
              //clientContext.Load(listProductImages, lib => lib.RootFolder.ServerRelativeUrl);
              clientContext.Load(listProductImages, lib => lib.RootFolder.Name);

              ListItemCollection products = listProducts.GetItems(new CamlQuery());
              clientContext.Load(products);
              clientContext.ExecuteQuery();

              Console.WriteLine();
              Console.WriteLine("Updating product image URL for all products");

              foreach (var product in products) {
            string title = product["Title"].ToString();
            string productCode = product["ProductCode"].ToString();
            //string productImageUrl = site.Url + listProductImages.RootFolder.ServerRelativeUrl + "/" + productCode + ".jpg";
            string productImageUrl = site.Url + "/" + listProductImages.RootFolder.Name + "/" + productCode + ".jpg";
            //
            Debug.WriteLine("Updating: " + productImageUrl);
            FieldUrlValue urlValue = new FieldUrlValue();

            urlValue.Url = productImageUrl;
            urlValue.Description = title;
            product["ProductImageUrl"] = urlValue;
            product.Update();
            Console.Write(".");
            clientContext.ExecuteQuery();
              }

              Console.WriteLine();
              Console.WriteLine();
              Console.WriteLine("Update complete. Press the ENTER key to continue.");
              Console.WriteLine();
              Console.WriteLine();
              Console.ReadLine();
        }
Пример #10
0
        static void Main()
        {
            clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(site.Lists);
              clientContext.ExecuteQuery();

              listProducts = site.Lists.GetByTitle("Products");
              clientContext.Load(listProducts);

              listProductImages = site.Lists.GetByTitle("Product Images");
              clientContext.Load(listProductImages, lib => lib.RootFolder.ServerRelativeUrl);

              ListItemCollection products = listProducts.GetItems(new CamlQuery());
              clientContext.Load(products);
              clientContext.ExecuteQuery();

              Console.WriteLine();
              Console.WriteLine("Updating product image URL for all products");

              foreach (var product in products) {
            string title = product["Title"].ToString();
            string productCode = product["ProductCode"].ToString();
            string productImageUrl = site.Url + listProductImages.RootFolder.ServerRelativeUrl + "/" + productCode + ".jpg";
            FieldUrlValue urlValue = new FieldUrlValue();

            urlValue.Url = productImageUrl;
            urlValue.Description = title;
            product["ProductImageUrl"] = urlValue;
            product.Update();
            Console.Write(".");
            clientContext.ExecuteQuery();
              }

              Console.WriteLine();
              Console.WriteLine();
              Console.WriteLine("Update complete. Press the ENTER ke to continue.");
              Console.WriteLine();
              Console.WriteLine();
              Console.ReadLine();
        }
Пример #11
0
        public MainViewModel(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;

            Search = new RelayCommand(SearchHandler);

            ClientContext clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite");
            _site = clientContext.Web;
            _personnelList = _site.Lists.GetByTitle("Personnel");
            _personnel = _personnelList.GetItems(new CamlQuery());
            //_items.Include(item => item["Title"], item => item["First_x0020_Name"], item => item["Last_x0020_Name"], item => item["Fun_x0020_Fact"], item => item["Office"], item => item["PersonnelTitle"], item => item["Image"]);
            clientContext.Load(_personnel);
            //clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);

            List officeList = _site.Lists.GetByTitle("Office");
            _officeSPItems = officeList.GetItems(new CamlQuery());
            clientContext.Load(_officeSPItems);

            List titleList = _site.Lists.GetByTitle("Titles");
            _titlesSPItems = titleList.GetItems(new CamlQuery());
            clientContext.Load(_titlesSPItems);

            clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);
        }
Пример #12
0
        private static IList<ListItem> GetAllItems(ClientRuntimeContext context, List list, int pageSize = MaxListPageSize)
        {
            ListItemCollectionPosition position = null;
            IEnumerable<ListItem> results = Enumerable.Empty<ListItem>();

            do
            {
                var query = new CamlQuery
                {
                    ListItemCollectionPosition = position,
                    ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query></Query><RowLimit>{0}</RowLimit></View>", pageSize)
                };

                var items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                position = items.ListItemCollectionPosition;
                results = results.Concat(items);
            }
            while (position != null);

            return results.ToList();
        }
Пример #13
0
        /// <summary>
        /// Send Email Job Main Method
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                string rootURL = BELDataAccessLayer.Instance.GetSiteURL(SiteURLs.ROOTSITEURL);
                using (ClientContext clientContext = BELDataAccessLayer.Instance.CreateClientContext(rootURL))
                {
                    Web       web = BELDataAccessLayer.Instance.CreateWeb(clientContext);
                    List      emailTemplateList = web.Lists.GetByTitle(ListNames.EmailNotification);
                    CamlQuery qry = new CamlQuery();
                    qry.ViewXml = @"<View>
                                    <Query>
                                        <Where>                                               
                                                <Eq>
                                                    <FieldRef Name='IsSent' />
                                                    <Value Type='Boolean'>0</Value>
                                                </Eq>                                         
                                        </Where>
                                    </Query>
                                    <RowLimit>" + Convert.ToInt32(BELDataAccessLayer.Instance.GetConfigVariable("MailsPerSchedule")) + @"</RowLimit>
                                </View>";
                    ////<Where><And>
                    ////                            <Eq>
                    ////                                <FieldRef Name='IsSent' />
                    ////                                <Value Type='Boolean'>0</Value>
                    ////                            </Eq>
                    ////                            <Eq>
                    ////                                <FieldRef Name='IsSentFail' />
                    ////                                <Value Type='Boolean'>0</Value>
                    ////                            </Eq>
                    ////                        </And>
                    ////                    </Where>
                    ListItemCollection items = emailTemplateList.GetItems(qry);
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();

                    Logger.Info("Item Count" + items.Count);
                    if (items.Count > 0)
                    {
                        foreach (ListItem item in items)
                        {
                            string mode = BELDataAccessLayer.Instance.GetConfigVariable("EmailMode");
                            if (mode.ToLower().Equals("live"))
                            {
                                bool mailstatus = SendMailEWS(clientContext, item);
                                item["IsSent"] = mailstatus;
                                if (!mailstatus)
                                {
                                    item["IsSentFail"] = !mailstatus;
                                }

                                Logger.Info("Item Count" + item["IsSent"]);
                            }
                            else
                            {
                                item["IsSent"] = SendMail(clientContext, item);
                            }
                            item.Update();
                            clientContext.ExecuteQuery();
                        }
                    }
                }
                Logger.Info("item  status " + ItemActionStatus.NEW);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error While Execute Main Method");
                Console.Write(ex.StackTrace + "==>" + ex.Message);
                Logger.Error("Error While Execute Main Method");
                Logger.Error(ex.Message);
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            // DateTime d1 = DateTime.Parse(DateTime.Now.ToShortDateString());
            // DateTime t = utility.NthOf(0, d1.DayOfWeek);
            ////  d1 = DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(7);
            // t = utility.NthOf(1, d1.DayOfWeek);
            // t = utility.NthOf(2, d1.DayOfWeek);
            // t = utility.NthOf(3, d1.DayOfWeek);
            //  t = utility.NthOf(4, d1.DayOfWeek);
            //  d1 = DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(14);
            //  t = utility.NthOf(1, d1.DayOfWeek);
            string logFilePath = ConfigurationManager.AppSettings["logFilePath"];

            string logFileName = "GCC-NthDay-log -" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + ".log";

            using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true))
            {
                writer.WriteLine("Data Time:" + DateTime.Now);
                writer.Close();
            }


            DateTime dateValue = DateTime.Now;


            ClientContext ctx        = spAuthentication(ConfigurationManager.AppSettings["url"]);
            Web           web        = ctx.Web;
            List          sourcelist = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["Library"]);
            string        we         = dateValue.DayOfWeek.ToString();
            string        caml       = @"<View><Query><Where><Eq><FieldRef Name='WeekDay' /><Value Type='Choice'>" + we + "</Value></Eq></Where></Query></View>";
            CamlQuery     query      = new CamlQuery();

            query.ViewXml = caml;
            ListItemCollection listItems = sourcelist.GetItems(query);

            ctx.Load(listItems);
            ctx.ExecuteQuery();

            //  Console.WriteLine("Total No of Items is:" + listItems.Count);
            try
            {
                foreach (var listItem in listItems)
                {
                    string rec            = listItem["Recurrence"].ToString();
                    string wd             = listItem["WeekDay"].ToString();
                    string title          = listItem["Title"].ToString();
                    double reportTime     = Convert.ToDouble(listItem["ReportTime"]);
                    string assignedTo     = listItem["AssignedTo"].ToString();
                    string criticality    = listItem["Criticality"].ToString();
                    string program        = listItem["Program"].ToString();
                    string subProgram     = listItem["SubProgram"].ToString();
                    string status         = Convert.ToString(listItem["Status"]);
                    string reportCategory = Convert.ToString(listItem["ReportCategory"]);
                    string distro         = Convert.ToString(listItem["Distro"]);


                    if (rec != "Last")
                    {
                        int       c  = int.Parse(rec);
                        DayOfWeek dd = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), wd);
                        bool      dt = utility.NthDayOfMonth(dateValue, dd, c);
                        //  Console.WriteLine(dt);
                        if (dt)
                        {
                            List      targetlist = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["DestinationList"]);
                            CamlQuery qry        = new CamlQuery();
                            qry.ViewXml = @"<Query><OrderBy><FieldRef Name='Title'  Ascending='TRUE' /></OrderBy></Query>";
                            ListItemCollection listItemss = targetlist.GetItems(qry);
                            ctx.Load(listItemss);
                            ctx.ExecuteQuery();
                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem oListItem = targetlist.AddItem(itemCreateInfo);
                            oListItem["Title"]      = title;
                            oListItem["ReportDate"] = DateTime.Now;
                            oListItem["Program"]    = program;
                            var dateTimeOnly = DateTime.Now.Date.AddHours(reportTime);
                            oListItem["ReportTime"]    = dateTimeOnly;
                            oListItem["AssignedTo"]    = assignedTo;
                            oListItem["Status"]        = status;
                            oListItem["Criticality"]   = criticality;
                            oListItem["SubProgram"]    = subProgram;
                            oListItem["TypeofReport1"] = reportCategory;
                            oListItem.Update();
                            ctx.ExecuteQuery();
                            // Console.Write(oListItem.Id);
                            using (var EmailclientContext = ctx)
                            {
                                var           emailprpoperties = new EmailProperties();
                                List <string> assignees        = assignedTo.Split(';').ToList();
                                emailprpoperties.To      = assignees;
                                emailprpoperties.From    = "*****@*****.**";
                                emailprpoperties.Body    = "<b>Good Day!!</b><br/>" + "Please note – the above said task has been assigned to you and is due by " + dateTimeOnly.ToString("MM/dd/yyyy HH:mm") + " hrs, upon completion respond on the same task mail.<br/>In event of delay click <a href=https://247incc.sharepoint.com/sites/GCC/Lists/GCCTransaction/EditForm.aspx?ID=" + oListItem.Id + "> here</a> to update status/ reason" + "<br/>" + "Refer doc #" + distro + "for email distro";
                                emailprpoperties.Subject = title + " ## " + oListItem.Id;

                                Utility.SendEmail(EmailclientContext, emailprpoperties);
                                EmailclientContext.ExecuteQuery();
                            }
                        }
                    }
                    else
                    {
                        DayOfWeek ddl = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), wd);
                        DateTime  de1 = utility.GetLastWeekdayOfTheMonth(DateTime.Now, ddl);
                        //  bool dtd = utility.LastDayOfMonth(DateTime.Now);
                        if (de1.Date.ToShortDateString() == dateValue.Date.ToShortDateString())
                        {
                            List      targetlist1 = ctx.Web.Lists.GetByTitle("GCCTransaction");
                            CamlQuery qry1        = new CamlQuery();
                            qry1.ViewXml = @"<Query><OrderBy><FieldRef Name='Title'  Ascending='TRUE' /></OrderBy></Query>";
                            ListItemCollection listItemss1 = targetlist1.GetItems(qry1);
                            ctx.Load(listItemss1);
                            ctx.ExecuteQuery();
                            ListItemCreationInformation itemCreateInfo1 = new ListItemCreationInformation();
                            ListItem oListItem1 = targetlist1.AddItem(itemCreateInfo1);
                            oListItem1["Title"]      = title;
                            oListItem1["ReportDate"] = DateTime.Now;
                            oListItem1["Program"]    = program;
                            var dateTimeOnly1 = DateTime.Now.Date.AddHours(reportTime);
                            oListItem1["ReportTime"]    = dateTimeOnly1;
                            oListItem1["AssignedTo"]    = assignedTo;
                            oListItem1["Status"]        = status;
                            oListItem1["Criticality"]   = criticality;
                            oListItem1["SubProgram"]    = subProgram;
                            oListItem1["TypeofReport1"] = reportCategory;
                            oListItem1.Update();
                            ctx.ExecuteQuery();
                            //  Console.WriteLine(oListItem1.Id);
                            using (var EmailclientContext1 = ctx)
                            {
                                var           emailprpoperties1 = new EmailProperties();
                                List <string> assignees1        = assignedTo.Split(';').ToList();
                                emailprpoperties1.To      = assignees1;
                                emailprpoperties1.From    = "*****@*****.**";
                                emailprpoperties1.Body    = "<b>Good Day!!</b><br/>" + "Please note – the above said task has been assigned to you and is due by " + dateTimeOnly1.ToString("MM/dd/yyyy HH:mm") + " hrs, upon completion respond on the same task mail.<br/>In event of delay click <a href=https://247incc.sharepoint.com/sites/GCC/Lists/GCCTransaction/EditForm.aspx?ID=" + oListItem1.Id + "> here</a> to update status/ reason" + "<br/>" + "Refer doc #" + distro + "&nbsp;for email distro";
                                emailprpoperties1.Subject = title + " ## " + oListItem1.Id;

                                Utility.SendEmail(EmailclientContext1, emailprpoperties1);
                                EmailclientContext1.ExecuteQuery();
                            }
                        }
                    }
                }

                using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true))
                {
                    writer.WriteLine("Data Time:" + DateTime.Now);
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                using (var EmailclientContext = ctx)
                {
                    var emailprpoperties = new EmailProperties();
                    emailprpoperties.To = new List <string> {
                        "*****@*****.**", "*****@*****.**"
                    };
                    emailprpoperties.From    = "*****@*****.**";
                    emailprpoperties.Body    = "<b>Nth Day data creation failed</b>" + ex;
                    emailprpoperties.Subject = "Nth Day data creation failed";

                    Utility.SendEmail(EmailclientContext, emailprpoperties);
                    EmailclientContext.ExecuteQuery();
                }
                using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true))
                {
                    writer.WriteLine("Exception Msg : " + ex.Message);
                    writer.WriteLine("Exception Msg : " + ex.StackTrace);
                    writer.Close();
                }
            }
        }
Пример #15
0
        public override TimeSpan Analyze(ClientContext cc)
        {
            try
            {
                base.Analyze(cc);

                // Only scan when it's a valid publishing portal
                var pageCount = ContinueScanning(cc);
                if (pageCount > 0 || pageCount == -1)
                {
                    try
                    {
                        PublishingWebScanResult scanResult = new PublishingWebScanResult()
                        {
                            SiteColUrl     = this.SiteCollectionUrl,
                            SiteURL        = this.SiteUrl,
                            WebRelativeUrl = this.SiteUrl.Replace(this.SiteCollectionUrl, ""),
                            WebTemplate    = this.webScanResult.WebTemplate,
                            BrokenPermissionInheritance = this.webScanResult.BrokenPermissionInheritance,
                            PageCount         = pageCount == -1 ? 0 : pageCount,
                            SiteMasterPage    = this.webScanResult.CustomMasterPage,
                            SystemMasterPage  = this.webScanResult.MasterPage,
                            AlternateCSS      = this.webScanResult.AlternateCSS,
                            Admins            = this.siteScanResult.Admins,
                            Owners            = this.webScanResult.Owners,
                            UserCustomActions = new List <UserCustomActionResult>()
                        };

                        // User custom actions will play a role in complexity calculation
                        if (this.siteScanResult.SiteUserCustomActions != null && this.siteScanResult.SiteUserCustomActions.Count > 0)
                        {
                            scanResult.UserCustomActions.AddRange(this.siteScanResult.SiteUserCustomActions);
                        }
                        if (this.webScanResult.WebUserCustomActions != null && this.webScanResult.WebUserCustomActions.Count > 0)
                        {
                            scanResult.UserCustomActions.AddRange(this.webScanResult.WebUserCustomActions);
                        }

                        Web web = cc.Web;

                        // Load additional web properties
                        web.EnsureProperties(p => p.Language);
                        scanResult.Language = web.Language;

                        // PageLayouts handling
                        var availablePageLayouts = GetPropertyBagValue <string>(web, AvailablePageLayouts, "");
                        var defaultPageLayout    = GetPropertyBagValue <string>(web, DefaultPageLayout, "");

                        if (string.IsNullOrEmpty(availablePageLayouts))
                        {
                            scanResult.PageLayoutsConfiguration = "Any";
                        }
                        else if (availablePageLayouts.Equals("__inherit", StringComparison.InvariantCultureIgnoreCase))
                        {
                            scanResult.PageLayoutsConfiguration = "Inherit from parent";
                        }
                        else
                        {
                            scanResult.PageLayoutsConfiguration = "Defined list";

                            try
                            {
                                availablePageLayouts = SanitizeXmlString(availablePageLayouts);

                                // Fill the defined list
                                var element = XElement.Parse(availablePageLayouts);
                                var nodes   = element.Descendants("layout");
                                if (nodes != null && nodes.Count() > 0)
                                {
                                    string allowedPageLayouts = "";

                                    foreach (var node in nodes)
                                    {
                                        allowedPageLayouts = allowedPageLayouts + node.Attribute("url").Value.Replace("_catalogs/masterpage/", "") + ",";
                                    }

                                    allowedPageLayouts = allowedPageLayouts.TrimEnd(new char[] { ',' });

                                    scanResult.AllowedPageLayouts = allowedPageLayouts;
                                }
                            }
                            catch (Exception ex)
                            {
                                scanResult.AllowedPageLayouts = "error_retrieving_pagelayouts";
                            }
                        }

                        if (!string.IsNullOrEmpty(defaultPageLayout))
                        {
                            if (defaultPageLayout.Equals("__inherit", StringComparison.InvariantCultureIgnoreCase))
                            {
                                scanResult.DefaultPageLayout = "Inherit from parent";
                            }
                            else
                            {
                                try
                                {
                                    defaultPageLayout = SanitizeXmlString(defaultPageLayout);
                                    var element = XElement.Parse(defaultPageLayout);
                                    scanResult.DefaultPageLayout = element.Attribute("url").Value.Replace("_catalogs/masterpage/", "");
                                }
                                catch (Exception ex)
                                {
                                    scanResult.DefaultPageLayout = "error_retrieving_defaultpagelayout";
                                }
                            }
                        }

                        // Navigation
                        var navigationSettings = web.GetNavigationSettings();
                        if (navigationSettings != null)
                        {
                            if (navigationSettings.GlobalNavigation.ManagedNavigation)
                            {
                                scanResult.GlobalNavigationType = "Managed";
                            }
                            else
                            {
                                scanResult.GlobalNavigationType = "Structural";
                                scanResult.GlobalStructuralNavigationMaxCount     = navigationSettings.GlobalNavigation.MaxDynamicItems;
                                scanResult.GlobalStructuralNavigationShowPages    = navigationSettings.GlobalNavigation.ShowPages;
                                scanResult.GlobalStructuralNavigationShowSiblings = navigationSettings.GlobalNavigation.ShowSiblings;
                                scanResult.GlobalStructuralNavigationShowSubSites = navigationSettings.GlobalNavigation.ShowSubsites;
                            }

                            if (navigationSettings.CurrentNavigation.ManagedNavigation)
                            {
                                scanResult.CurrentNavigationType = "Managed";
                            }
                            else
                            {
                                scanResult.CurrentNavigationType = "Structural";
                                scanResult.CurrentStructuralNavigationMaxCount     = navigationSettings.CurrentNavigation.MaxDynamicItems;
                                scanResult.CurrentStructuralNavigationShowPages    = navigationSettings.CurrentNavigation.ShowPages;
                                scanResult.CurrentStructuralNavigationShowSiblings = navigationSettings.CurrentNavigation.ShowSiblings;
                                scanResult.CurrentStructuralNavigationShowSubSites = navigationSettings.CurrentNavigation.ShowSubsites;
                            }

                            if (navigationSettings.GlobalNavigation.ManagedNavigation || navigationSettings.CurrentNavigation.ManagedNavigation)
                            {
                                scanResult.ManagedNavigationAddNewPages        = navigationSettings.AddNewPagesToNavigation;
                                scanResult.ManagedNavigationCreateFriendlyUrls = navigationSettings.CreateFriendlyUrlsForNewPages;

                                // get information about the managed nav term set configuration
                                var managedNavXml = GetPropertyBagValue <string>(web, WebNavigationSettings, "");

                                if (!string.IsNullOrEmpty(managedNavXml))
                                {
                                    var managedNavSettings          = XElement.Parse(managedNavXml);
                                    IEnumerable <XElement> navNodes = managedNavSettings.XPathSelectElements("./SiteMapProviderSettings/TaxonomySiteMapProviderSettings");
                                    foreach (var node in navNodes)
                                    {
                                        if (node.Attribute("Name").Value.Equals("CurrentNavigationTaxonomyProvider", StringComparison.InvariantCulture))
                                        {
                                            if (node.Attribute("TermSetId") != null)
                                            {
                                                scanResult.CurrentManagedNavigationTermSetId = node.Attribute("TermSetId").Value;
                                            }
                                            else if (node.Attribute("UseParentSiteMap") != null)
                                            {
                                                scanResult.CurrentManagedNavigationTermSetId = "Inherit from parent";
                                            }
                                        }
                                        else if (node.Attribute("Name").Value.Equals("GlobalNavigationTaxonomyProvider", StringComparison.InvariantCulture))
                                        {
                                            if (node.Attribute("TermSetId") != null)
                                            {
                                                scanResult.GlobalManagedNavigationTermSetId = node.Attribute("TermSetId").Value;
                                            }
                                            else if (node.Attribute("UseParentSiteMap") != null)
                                            {
                                                scanResult.GlobalManagedNavigationTermSetId = "Inherit from parent";
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // Pages library
                        List pagesLibrary = null;
                        var  lists        = web.GetListsToScan();
                        if (lists != null)
                        {
                            pagesLibrary = lists.Where(p => p.BaseTemplate == 850).FirstOrDefault();
                            if (pagesLibrary != null)
                            {
                                pagesLibrary.EnsureProperties(p => p.EnableModeration, p => p.EnableVersioning, p => p.EnableMinorVersions, p => p.EventReceivers, p => p.Fields, p => p.DefaultContentApprovalWorkflowId);
                                scanResult.LibraryEnableModeration        = pagesLibrary.EnableModeration;
                                scanResult.LibraryEnableVersioning        = pagesLibrary.EnableVersioning;
                                scanResult.LibraryEnableMinorVersions     = pagesLibrary.EnableMinorVersions;
                                scanResult.LibraryItemScheduling          = pagesLibrary.ItemSchedulingEnabled();
                                scanResult.LibraryApprovalWorkflowDefined = pagesLibrary.DefaultContentApprovalWorkflowId != Guid.Empty;
                            }
                        }

                        // Variations
                        if (scanResult.Level == 0)
                        {
                            var variationLabels = GetVariationLabels(cc);

                            string labels      = "";
                            string sourceLabel = "";
                            foreach (var label in variationLabels)
                            {
                                labels = labels + $"{label.Title} ({label.Language}),";

                                if (label.IsSource)
                                {
                                    sourceLabel = label.Title;
                                }
                            }

                            scanResult.VariationLabels      = labels.TrimEnd(new char[] { ',' });;
                            scanResult.VariationSourceLabel = sourceLabel;
                        }

                        // Scan pages inside the pages library
                        if (pagesLibrary != null && Options.IncludePublishingWithPages(this.ScanJob.Mode))
                        {
                            CamlQuery query = new CamlQuery
                            {
                                ViewXml = CAMLQueryByExtension,
                            };

                            var pages = pagesLibrary.GetItems(query);

                            // Load additional page related information
                            IEnumerable <ListItem> enumerable = web.Context.LoadQuery(pages.IncludeWithDefaultProperties((ListItem item) => item.ContentType));
                            web.Context.ExecuteQueryRetry();

                            if (enumerable.FirstOrDefault() != null)
                            {
                                foreach (var page in enumerable)
                                {
                                    string pageUrl = null;
                                    try
                                    {
                                        if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString()))
                                        {
                                            pageUrl = page[FileRefField].ToString();
                                        }
                                        else
                                        {
                                            //skip page
                                            continue;
                                        }

                                        // Basic information about the page
                                        PublishingPageScanResult pageScanResult = new PublishingPageScanResult()
                                        {
                                            SiteColUrl      = this.SiteCollectionUrl,
                                            SiteURL         = this.SiteUrl,
                                            WebRelativeUrl  = scanResult.WebRelativeUrl,
                                            PageRelativeUrl = scanResult.WebRelativeUrl.Length > 0 ? pageUrl.Replace(scanResult.WebRelativeUrl, "") : pageUrl,
                                        };

                                        // Page name
                                        if (page.FieldValues.ContainsKey(FileLeafRefField) && !String.IsNullOrEmpty(page[FileLeafRefField].ToString()))
                                        {
                                            pageScanResult.PageName = page[FileLeafRefField].ToString();
                                        }

                                        // Get page change information
                                        pageScanResult.ModifiedAt = page.LastModifiedDateTime();
                                        if (!this.ScanJob.SkipUserInformation)
                                        {
                                            pageScanResult.ModifiedBy = page.LastModifiedBy();
                                        }

                                        // Page layout
                                        pageScanResult.PageLayout     = page.PageLayout();
                                        pageScanResult.PageLayoutFile = page.PageLayoutFile().Replace(pageScanResult.SiteColUrl, "").Replace("/_catalogs/masterpage/", "");

                                        // Customization status
                                        if (this.MasterPageGalleryCustomization == null)
                                        {
                                            this.MasterPageGalleryCustomization = new Dictionary <string, CustomizedPageStatus>();
                                        }

                                        // Load the file to check the customization status, only do this if the file was not loaded before for this site collection
                                        string layoutFile = page.PageLayoutFile();
                                        if (!string.IsNullOrEmpty(layoutFile))
                                        {
                                            Uri uri = new Uri(layoutFile);
                                            var url = page.PageLayoutFile().Replace($"{uri.Scheme}://{uri.DnsSafeHost}".ToLower(), "");
                                            if (!this.MasterPageGalleryCustomization.ContainsKey(url))
                                            {
                                                try
                                                {
                                                    var publishingPageLayout = cc.Site.RootWeb.GetFileByServerRelativeUrl(url);
                                                    cc.Load(publishingPageLayout);
                                                    cc.ExecuteQueryRetry();

                                                    this.MasterPageGalleryCustomization.Add(url, publishingPageLayout.CustomizedPageStatus);
                                                }
                                                catch (Exception ex)
                                                {
                                                    // eat potential exceptions
                                                }
                                            }

                                            // store the page layout customization status
                                            if (this.MasterPageGalleryCustomization.TryGetValue(url, out CustomizedPageStatus pageStatus))
                                            {
                                                if (pageStatus == CustomizedPageStatus.Uncustomized)
                                                {
                                                    pageScanResult.PageLayoutWasCustomized = false;
                                                }
                                                else
                                                {
                                                    pageScanResult.PageLayoutWasCustomized = true;
                                                }
                                            }
                                            else
                                            {
                                                // If the file was not loaded for some reason then assume it was customized
                                                pageScanResult.PageLayoutWasCustomized = true;
                                            }
                                        }

                                        // Page audiences
                                        var audiences = page.Audiences();
                                        if (audiences != null)
                                        {
                                            pageScanResult.GlobalAudiences          = audiences.GlobalAudiences;
                                            pageScanResult.SecurityGroupAudiences   = audiences.SecurityGroups;
                                            pageScanResult.SharePointGroupAudiences = audiences.SharePointGroups;
                                        }

                                        // Contenttype
                                        pageScanResult.ContentType   = page.ContentType.Name;
                                        pageScanResult.ContentTypeId = page.ContentType.Id.StringValue;

                                        // Get page web parts
                                        var pageAnalysis = page.WebParts(this.ScanJob.PageTransformation);
                                        if (pageAnalysis != null)
                                        {
                                            pageScanResult.WebParts = pageAnalysis.Item2;
                                        }

                                        // Persist publishing page scan results
                                        if (!this.ScanJob.PublishingPageScanResults.TryAdd(pageUrl, pageScanResult))
                                        {
                                            ScanError error = new ScanError()
                                            {
                                                Error      = $"Could not add publishing page scan result for {pageScanResult.PageRelativeUrl}",
                                                SiteColUrl = this.SiteCollectionUrl,
                                                SiteURL    = this.SiteUrl,
                                                Field1     = "PublishingAnalyzer",
                                                Field2     = pageScanResult.PageRelativeUrl,
                                            };
                                            this.ScanJob.ScanErrors.Push(error);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ScanError error = new ScanError()
                                        {
                                            Error      = ex.Message,
                                            SiteColUrl = this.SiteCollectionUrl,
                                            SiteURL    = this.SiteUrl,
                                            Field1     = "MainPublishingPageAnalyzerLoop",
                                            Field2     = ex.StackTrace,
                                            Field3     = pageUrl
                                        };

                                        // Send error to telemetry to make scanner better
                                        if (this.ScanJob.ScannerTelemetry != null)
                                        {
                                            this.ScanJob.ScannerTelemetry.LogScanError(ex, error);
                                        }

                                        this.ScanJob.ScanErrors.Push(error);
                                        Console.WriteLine("Error for page {1}: {0}", ex.Message, pageUrl);
                                    }
                                }
                            }
                        }

                        // Persist publishing scan results
                        if (!this.ScanJob.PublishingWebScanResults.TryAdd(this.SiteUrl, scanResult))
                        {
                            ScanError error = new ScanError()
                            {
                                Error      = $"Could not add publishing scan result for {this.SiteUrl}",
                                SiteColUrl = this.SiteCollectionUrl,
                                SiteURL    = this.SiteUrl,
                                Field1     = "PublishingAnalyzer",
                            };
                            this.ScanJob.ScanErrors.Push(error);
                        }
                    }
                    catch (Exception ex)
                    {
                        ScanError error = new ScanError()
                        {
                            Error      = ex.Message,
                            SiteColUrl = this.SiteCollectionUrl,
                            SiteURL    = this.SiteUrl,
                            Field1     = "MainPublishingAnalyzerLoop",
                            Field2     = ex.StackTrace,
                        };

                        // Send error to telemetry to make scanner better
                        if (this.ScanJob.ScannerTelemetry != null)
                        {
                            this.ScanJob.ScannerTelemetry.LogScanError(ex, error);
                        }

                        this.ScanJob.ScanErrors.Push(error);
                        Console.WriteLine("Error for web {1}: {0}", ex.Message, this.SiteUrl);
                    }
                }
            }
            finally
            {
                this.StopTime = DateTime.Now;
            }

            // return the duration of this scan
            return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks)));
        }
 /// <summary>
 /// Check for the list item named Matter Center Briefcase already exists, if not then only create new folder
 /// </summary>
 /// <param name="clientContext">SP client context</param>
 /// <param name="list">Name of the list</param>
 /// <param name="usersMySite">My Site URL of the user</param>
 internal static void CreateBriefcaseIfNotExists(ClientContext clientContext, List list, string usersMySite)
 {
     CamlQuery briefcaseQuery = new CamlQuery();
     briefcaseQuery.ViewXml = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.BriefcaseFolderQuery, ServiceConstantStrings.LegalBriefcaseFolder);
     ListItemCollection briefcases = list.GetItems(briefcaseQuery);
     clientContext.Load(briefcases, listItems => listItems.Include(item => item.DisplayName));
     clientContext.ExecuteQuery();
     ListItem listItem = briefcases.Where(item => item.DisplayName == ServiceConstantStrings.LegalBriefcaseFolder).FirstOrDefault();
     if (null == listItem)      // Check for Matter Center Briefcase folder exists, if not then create
     {
         ListItemCreationInformation newItem = new ListItemCreationInformation();
         newItem.FolderUrl = string.Concat(usersMySite, ServiceConstantStrings.OneDriveDocumentLibraryTitle);
         newItem.LeafName = ServiceConstantStrings.LegalBriefcaseFolder;
         newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
         listItem = list.AddItem(newItem);
         listItem.Update();
         clientContext.Load(listItem, field => field.DisplayName);
         clientContext.ExecuteQuery();
     }
 }
Пример #17
0
        private ListItemCollection GetItemFromSP(List docList)
        {
            clientContextSharePoint.Load(docList);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View/>";

            ListItemCollection listItems = docList.GetItems(camlQuery);

            clientContextSharePoint.Load(listItems);
            clientContextSharePoint.ExecuteQuery();

            return listItems;
        }
Пример #18
0
        private ListItem GetItemFromListByUrl(ClientContext context, List list ,string Url)
        {
            CamlQuery camlQuery = new CamlQuery();
            StringBuilder sb = new StringBuilder();
            sb.Append("<View><Query><Where><Contains><FieldRef Name='FileLeafRef'/><Value Type='Text'>");
            sb.Append(Url);
            sb.Append("</Value></Contains></Where></Query><RowLimit>100</RowLimit></View>");

            camlQuery.ViewXml = sb.ToString();
            ListItemCollection items = list.GetItems(camlQuery);

            context.Load(items);
            context.ExecuteQuery();

            return items[0];
        }
        private void GetChildItem(ClientContext clientContext, string Id, string ParentGuid, string i_chronicle_id, string r_object_id, string content_id, string display_order, ref DataTable dtResponse)
        {
            string Name = string.Empty, guid = string.Empty, Version = string.Empty, ListId = string.Empty, title = string.Empty,
                   ThumbnailName = string.Empty; string ParentImageName = string.Empty;
            List list                = null;
            ListItemCollection items = null;

            try
            {
                list = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings.Get(SPOConstants.SPOFolderGalleryThumbnail));
                clientContext.Load(list);
                clientContext.ExecuteQuery();

                Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(ConfigurationManager.AppSettings.Get(SPOConstants.SPOSiteURL)
                                                                               + "/"
                                                                               + ConfigurationManager.AppSettings.Get(SPOConstants.SPOFolderGalleryThumbnailInternalName) + "/" + Id);
                clientContext.Load(folder);
                clientContext.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"<View Scope='Recursive'>
                                 <Query>
                                 </Query>
                             </View>";
                camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;

                items = list.GetItems(camlQuery);


                clientContext.Load(items);
                clientContext.ExecuteQuery();

                foreach (var obj in items)
                {
                    Dictionary <string, object> keyValuePairs = obj.FieldValues;
                    if (items.Count == 3)
                    {
                        Dictionary <string, object> keyValuePairsParenName = items[2].FieldValues;
                        ParentImageName = keyValuePairsParenName.ContainsKey(SPOConstants.Name) ? (keyValuePairsParenName[SPOConstants.Name] != null ? keyValuePairsParenName[SPOConstants.Name].ToString() : "") : "";
                    }

                    Name = keyValuePairs.ContainsKey(SPOConstants.Name) ? (keyValuePairs[SPOConstants.Name] != null ? keyValuePairs[SPOConstants.Name].ToString() : "") : "";
                    //title = keyValuePairs.ContainsKey(SPOConstants.Title) ? (keyValuePairs[SPOConstants.Title] != null ? keyValuePairs[SPOConstants.Title].ToString() : "") : "";
                    ListId  = keyValuePairs.ContainsKey(SPOConstants.Id) ? (keyValuePairs[SPOConstants.Id] != null ? keyValuePairs[SPOConstants.Id].ToString() : "") : "";
                    guid    = keyValuePairs.ContainsKey(SPOConstants.UniqueId) ? (keyValuePairs[SPOConstants.UniqueId] != null ? keyValuePairs[SPOConstants.UniqueId].ToString() : "") : "";
                    Version = keyValuePairs.ContainsKey(SPOConstants.UIVersionString) ? (keyValuePairs[SPOConstants.UIVersionString] != null ? keyValuePairs[SPOConstants.UIVersionString].ToString() : "") : "";


                    dtResponse.Rows.Add(Constants.Ir_article_image, r_object_id, i_chronicle_id, Constants.Article_images_r_folder_path, ParentImageName, FileFormatConstants.JPEG, Constants.Article_images + "/" + Name, ParentGuid, ParentGuid, guid + '@' + ParentGuid, Constants.Article_images, display_order, "NULL");
                }
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                {
                }
                else
                {
                    Console.WriteLine("Error in NewsPressRelease - GetChildItem :" + ex.Message);
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in NewsPressRelease - GetChildItem : " + ex.Message);
                throw ex;
            }
        }
Пример #20
0
        public static void AddDocumentLibItems(ClientContext clientContext, string listTitle, XmlDocument sampleData, string BaseFolderPath)
        {
            XmlNode items = sampleData.SelectSingleNode("//List[@name='" + listTitle + "']");
            List    list  = clientContext.Web.Lists.GetByTitle(listTitle);

            //remove list items
            var d_items = list.GetItems(new CamlQuery());

            clientContext.Load(d_items);
            clientContext.ExecuteQuery();

            var count = d_items.Count;

            if (count > 0)
            {
                while (count-- > 0)
                {
                    d_items[0].DeleteObject();
                }
                clientContext.ExecuteQuery();
            }

            foreach (XmlNode item in items)
            {
                var filePath = BaseFolderPath + item.Attributes["path"].Value;

                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        byte[] bytes = new byte[fs.Length];
                        fs.Read(bytes, 0, bytes.Length);

                        var newfile = new FileCreationInformation();
                        newfile.Url       = System.DateTime.Now.Ticks.ToString() + ".jpg";
                        newfile.Overwrite = true;
                        newfile.Content   = bytes;
                        Microsoft.SharePoint.Client.File uploadedFile = list.RootFolder.Files.Add(newfile);

                        foreach (XmlNode column in item.ChildNodes)
                        {
                            if (column.Attributes["name"].Value == "Id")
                            {
                                continue;
                            }
                            if (column.Attributes["Type"] != null && column.Attributes["Type"].Value == "Lookup" && !string.IsNullOrEmpty(column.InnerText))
                            {
                                FieldLookupValue fieldLookupValue = new FieldLookupValue();

                                fieldLookupValue.LookupId = int.Parse(sampleData.SelectSingleNode(
                                                                          string.Format("//List[@name='{0}']/item[{1}]/column[@name='Id']",
                                                                                        column.Attributes["Source"].Value,
                                                                                        column.InnerText)).InnerText);

                                uploadedFile.ListItemAllFields[column.Attributes["name"].Value] = fieldLookupValue;
                            }
                            else
                            {
                                uploadedFile.ListItemAllFields[column.Attributes["name"].Value] = column.InnerText;
                            }
                        }
                        uploadedFile.ListItemAllFields.Update();
                        clientContext.Load(uploadedFile);
                        clientContext.ExecuteQuery();
                    }
                    catch (Exception el)
                    {
                        el.ToString();
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Gets the DCN details.
        /// </summary>
        /// <param name="objDict">The object dictionary.</param>
        /// <returns>byte array</returns>
        public List <DCRDetails> RetrieveAllDCRNos(IDictionary <string, string> objDict)
        {
            List <DCRDetails> dcrs = new List <DCRDetails>();
            List      spList       = this.web.Lists.GetByTitle(DCRDCNListNames.DCRLIST);
            CamlQuery query        = new CamlQuery();

            if (objDict != null && objDict.ContainsKey("UserEmail"))
            {
                User loggedinuser = BELDataAccessLayer.EnsureUser(context, web, objDict["UserEmail"].ToString());
                query.ViewXml = @"<View>
                                        <Query>
                                                  <Where>
                                                        <And>
                                                            <Eq>
                                                                    <FieldRef Name='FinalDesignEngineer' /><Value Type='User'>" + loggedinuser.Title + @"</Value>
                                                            </Eq>
                                                        <And>
                                                            <Eq>
                                                                    <FieldRef Name='Status' />
                                                                    <Value Type='Text'>" + FormStatus.COMPLETED + @"</Value>
                                                            </Eq>
                                                            <Eq>
                                                                    <FieldRef Name='IsDCNGenerated' />
                                                                    <Value Type='Boolean'>0</Value>
                                                            </Eq>
                                                    </And>
                                                   </And>
                                                 </Where>
                                        </Query>
                            </View>";
            }
            else
            {
                query.ViewXml = @"<View>
                                                        <Query>
                                                                  <Where>
                                                                    <And>
                                                                      <Eq>
                                                                            <FieldRef Name='Status' />
                                                                            <Value Type='Text'>" + FormStatus.COMPLETED + @"</Value>
                                                                       </Eq>
                                                                       <Eq>
                                                                             <FieldRef Name='IsDCNGenerated' />
                                                                             <Value Type='Boolean'>0</Value>
                                                                       </Eq>
                                                                    </And>
                                                                 </Where>
                                                        </Query>
                                            </View>";
            }
            //  query.ViewXml = @"<View><ViewFields><FieldRef Name='ID' /><FieldRef Name='DCRNo' /><FieldRef Name='ProductName' /><FieldRef Name='RequestDate' /><FieldRef Name='ProposedBy' /></ViewFields></View>";
            ListItemCollection items = spList.GetItems(query);

            this.context.Load(items);
            this.context.ExecuteQuery();
            if (items != null && items.Count != 0)
            {
                foreach (ListItem item in items)
                {
                    DCRDetails dcr = new DCRDetails();
                    dcr.DCRNo = Convert.ToString(item["DCRNo"]);
                    dcr.ID    = item.Id;
                    FieldUserValue user = item["ProposedBy"] as FieldUserValue;
                    dcr.ProposedBy  = BELDataAccessLayer.GetNameFromPersonField(context, web, user);
                    dcr.ProductName = Convert.ToString(item["ProductName"]);
                    dcr.RequestDate = Convert.ToDateTime(item["RequestDate"]);
                    dcrs.Add(dcr);
                }
            }
            return(dcrs);
        }
Пример #22
0
        private void btnReadCard_Click(object sender, EventArgs e)
        {
            try
            {
                publicDataEx = new BLL.CardReader().ReadCard();

                txtArabicFullName.Text       = PublicDataUtils.RemoveCommas(Utils.ByteArrayToUTF8String(publicDataEx.ArabicFullName));
                txtFullName.Text             = PublicDataUtils.RemoveCommas(Utils.ByteArrayToUTF8String(publicDataEx.FullName));
                txtMotherFullNameArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.MotherFullNameArabic);
                txtIDNumber.Text             = Utils.ByteArrayToUTF8String(publicDataEx.IdNumber);
                picPhotography.Image         = (Image) new ImageConverter().ConvertFrom(publicDataEx.Photography);
                txtNationalityAr.Text        = Utils.ByteArrayToUTF8String(publicDataEx.ArabicNationality);
                txtIssueDate.Text            = Utils.ByteArrayToStringDate(publicDataEx.IssueDate);
                txtExpiryDate.Text           = Utils.ByteArrayToStringDate(publicDataEx.ExpiryDate);
                txtDateOfBirth.Text          = Utils.ByteArrayToStringDate(publicDataEx.DateOfBirth);

                txtPlaceOfBirthArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.PlaceOfBirthArabic);
                txtSex.Text           = PublicDataUtils.GetSex(Utils.ByteArrayToUTF8String(publicDataEx.Sex));
                txtMaritalStatus.Text = PublicDataUtils.GetMaritalStatus(Utils.ByteArrayToHex(publicDataEx.MaritalStatus, ""));
                txtQualificationLevelDescriptionArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.QualificationLevelDescriptionArabic);

                txtDegreeDescriptionArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.DegreeDescriptionArabic);
                txtMobilePhoneNumber.Text       = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.MobilePhoneNumber);
                txtResidentPhoneNumber.Text     = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.ResidentPhoneNumber);
                txtPOBox.Text       = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.POBox);
                txtEmail.Text       = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.Email);
                txtLandPhoneNo.Text = Utils.ByteArrayToUTF8String(publicDataEx.WorkAddress.LandPhoneNo);

                txtPassportNumber.Text     = Utils.ByteArrayToUTF8String(publicDataEx.PassportNumber);
                txtPassportIssueDate.Text  = Utils.ByteArrayToStringDate(publicDataEx.PassportIssueDate);
                txtPassportExpiryDate.Text = Utils.ByteArrayToStringDate(publicDataEx.PassportExpiryDate);
                txtPassportCountryDescriptionArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.PassportCountryDescriptionArabic);
                txtOccupation.Text               = PublicDataUtils.GetOccupation(Utils.ByteArrayToHex(publicDataEx.Occupation));
                txtCompanyNameArabic.Text        = Utils.ByteArrayToUTF8String(publicDataEx.WorkAddress.CompanyNameArabic);
                txtEmirateDescriptionArabic.Text = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.EmirateDescriptionArabic);
                txtCityDescriptionArabic.Text    = Utils.ByteArrayToUTF8String(publicDataEx.HomeAddress.CityDescriptionArabic);
                txtResidencyType.Text            = PublicDataUtils.GetResidencyType(Utils.ByteArrayToHex(publicDataEx.ResidencyType, ""));
                txtResidencyNumber.Text          = Utils.ByteArrayToUTF8String(publicDataEx.ResidencyNumber);
                txtResidencyExpiryDate.Text      = Utils.ByteArrayToStringDate(publicDataEx.ResidencyExpiryDate);

                #region Checking If User Existing

                ClientContext context = new ClientContext(ConfigFileData.SP_URL);

                List TestForClientsList = context.Web.Lists.GetByTitle(ConfigFileData.ListName);

                bool CheckIfUserExisting = get_CheckIfUserExisting_value();

                if (CheckIfUserExisting)
                {
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml =
                        @"<View>
                                <Query>
                                   <Where><Eq><FieldRef Name='IDNumber' /><Value Type='Text'>" + txtIDNumber.Text + @"</Value></Eq></Where>
                                </Query>
                                 <ViewFields><FieldRef Name='ID' /></ViewFields>
                          </View>";

                    ListItemCollection listItems = TestForClientsList.GetItems(camlQuery);
                    context.Load(listItems);
                    context.Credentials = new NetworkCredential(ConfigFileData.UserName, ConfigFileData.Password);
                    context.ExecuteQuery();

                    if (listItems.Count > 0)
                    {
                        IsUserExisting = true;
                        ExistingUserID = listItems[0]["ID"].ToString();
                        string PreviousRequestsLink = ConfigFileData.PreviousRequestsLink + ExistingUserID;
                        txtStatus.Text      = "البطاقة مسجلة مسبقا. اضغط الرابط التالى لعرض الطلبات السابقة " + "\n" + PreviousRequestsLink;
                        txtStatus.BackColor = Color.SkyBlue;
                        return;
                    }
                }

                #endregion Checking If User Existing

                txtStatus.BackColor = Color.LightGreen;
                txtStatus.Text      = "تم قراءة بيانات البطاقة بنجاح";
            }
            catch (Exception ex)
            {
                txtStatus.BackColor = Color.LightCoral;

                switch (ex.Message)
                {
                case "NO PCSC Readers":
                    txtStatus.Text = "خطأ : لا يوجد جهاز قارئ للبطاقة";
                    break;

                case "E_SELECT_CM_APPLICATION":
                    txtStatus.Text = "خطأ : لا توجد بطاقة هوية بداخل القارئ";
                    break;

                default:
                    txtStatus.Text = ex.Message;
                    break;
                }
            }
        }
Пример #23
0
        public async Task StartAsync(IDialogContext context)
        {
            //context.Wait(MessageReceivedAsync);

            //return Task.CompletedTask;
            ClientContext ctx = new ClientContext("https://wbsharepoint.sharepoint.com/sites/POCs/");
            Web           web = ctx.Web;

            string       pwd      = ConfigurationManager.AppSettings["SPPassword"].ToString();
            string       userName = ConfigurationManager.AppSettings["SPUserName"].ToString();
            SecureString passWord = new SecureString();

            foreach (char c in pwd.ToCharArray())
            {
                passWord.AppendChar(c);
            }
            ctx.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord);

            List      quizList = ctx.Web.Lists.GetByTitle("SPQuiz");
            CamlQuery query    = CamlQuery.CreateAllItemsQuery(100);

            query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Category'/>" +
                            "<Value Type='Text'>SharePoint</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>";
            ListItemCollection items = quizList.GetItems(query);

            ctx.Load(items);
            ctx.ExecuteQuery();
            foreach (ListItem listItem in items)
            {
                // We have all the list item data. For example, Title.
                quiz.Add(new QuizEntity
                {
                    Question = listItem["Title"].ToString(),
                    Option1  = listItem["Option1"].ToString(),
                    Option2  = listItem["Option2"].ToString(),
                    Option3  = listItem["Option3"]?.ToString(),
                    Option4  = listItem["Option4"]?.ToString(),
                    Answer   = listItem["Answer"].ToString()
                });
            }

            var heroCard = new ThumbnailCard
            {
                Title    = "SharePoint",
                Subtitle = "Welcome to SharePoint Quiz",
                Text     = "Total number of questions are " + quiz.Count + ". Type go to start the Quiz.",
                Images   = new List <CardImage> {
                    new CardImage("https://techquizbot.azurewebsites.net/images/SPIcon.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.ImBack, "Take Quiz", value: "Take Quiz")
                }
            };

            var message = context.MakeMessage();

            message.Attachments.Add(heroCard.ToAttachment());
            await context.PostAsync(message);

            context.Wait(MessageReceivedStartQuestions);
        }
Пример #24
0
        static void Main(string[] args)
        {
            #region Site Details - Read the details from app.config
            string URL      = ConfigurationManager.AppSettings["URL"];
            string username = ConfigurationManager.AppSettings["username"];
            string password = ConfigurationManager.AppSettings["password"];
            string listName = ConfigurationManager.AppSettings["listName"];
            string viewName = ConfigurationManager.AppSettings["viewName"];
            string path     = ConfigurationManager.AppSettings["path"];
            #endregion

            using (ClientContext context = new ClientContext(URL))
            {
                SecureString securePassword = GetSecureString(password);
                context.Credentials = new SharePointOnlineCredentials(username, securePassword);

                List list = context.Web.Lists.GetByTitle(listName);
                context.Load(list);
                context.ExecuteQuery();

                View view = list.Views.GetByTitle(viewName);
                context.Load(view);
                context.ExecuteQuery();


                CamlQuery query = CamlQuery.CreateAllItemsQuery();
                query.ViewXml = "<View><Query>" + view.ViewQuery + "</Query></View>";
                ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                //Console.WriteLine("Total Count: " + items.Count);

                /* foreach (ListItem item in items)
                 * {
                 *     Console.WriteLine("Title " + item["Title"]);
                 * }
                 *
                 */
                #region -- Datatable
                //new datatable
                DataTable data = new DataTable();

                //add column names - (Column headers as needed in csv file)
                data.Columns.Add("Title", typeof(string));
                data.Columns.Add("Actual_Units_Scanned", typeof(Int32));
                data.Columns.Add("Attainment", typeof(double));
                data.Columns.Add("Created_By", typeof(string));

                //add each row to datarow - (internal name of column from URL)
                foreach (ListItem item in items)
                {
                    data.Rows.Add(item["LineLead"], item["Actual_x0020_Units_x0020_Scanned"], item["Attainment"], item["Created"]);
                }

                //Just to display the data table
                foreach (DataRow row in data.Rows)
                {
                    Console.WriteLine();
                    for (int x = 0; x < data.Columns.Count; x++)
                    {
                        Console.Write(row[x].ToString() + " ");
                    }
                }
                #endregion


                #region --generate csv

                PutDataTableToCsv(path, data, true);

                #endregion


                Console.ReadKey();
            }
        }
Пример #25
0
        protected File SearchFileByName(List list, Folder folder, string pageName)
        {
            var context = list.Context;

            if (folder != null)
            {
                if (!folder.IsPropertyAvailable("ServerRelativeUrl")
                    // || !folder.IsPropertyAvailable("Properties"))
                    )
                {
                    folder.Context.Load(folder, f => f.ServerRelativeUrl);
                    //folder.Context.Load(folder, f => f.Properties);

                    folder.Context.ExecuteQueryWithTrace();
                }
            }

            // one more time..
            var dQuery = new CamlQuery();

            string QueryString = "<View><Query><Where>" +
                                 "<Eq>" +
                                 "<FieldRef Name=\"FileLeafRef\"/>" +
                                 "<Value Type=\"Text\">" + pageName + "</Value>" +
                                 "</Eq>" +
                                 "</Where></Query></View>";

            dQuery.ViewXml = QueryString;

            if (folder != null)
                dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;

            var collListItems = list.GetItems(dQuery);

            context.Load(collListItems);
            context.ExecuteQueryWithTrace();

            var item = collListItems.FirstOrDefault();
            if (item != null)
                return item.File;

            //one more time
            // by full path
            var fileServerRelativePath = UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName);

            File file = null;

            var scope = new ExceptionHandlingScope(context);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    file = list.ParentWeb.GetFileByServerRelativeUrl(fileServerRelativePath);

                    context.Load(file);

                }

                using (scope.StartCatch())
                {

                }
            }

            context.ExecuteQueryWithTrace();

            // Forms folder im the libraries
            // otherwise pure list items search
            if (!scope.HasException && file != null && file.ServerObjectIsNull != null)
            {
                context.Load(file);
                context.Load(file, f => f.Exists);

                context.ExecuteQueryWithTrace();

                if (file.Exists)
                    return file;
            }

            return null;
        }
Пример #26
0
		static void Main(string[] args)
		{
			
			#region Site Details - Read the details from config file  
			string siteURL = ConfigurationManager.AppSettings["siteURL"];
			string ListName = ConfigurationManager.AppSettings["listName"];
			string userName = ConfigurationManager.AppSettings["userName"];
			string password = ConfigurationManager.AppSettings["password"];
			string sitrUrl = siteURL;
			#endregion
			
			SecureString securePassword = new SecureString();
			foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
			/// Add the Folder object to List collection 
			#region Folder
			using (var ctx = new ClientContext(sitrUrl))
			{
				List<permissionItem> lstPermissionItem = new List<permissionItem>();
				ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
				ctx.Load(ctx.Web, a => a.Lists);
				ctx.ExecuteQuery();

				List list = ctx.Web.Lists.GetByTitle(ListName);
				var Folderitems = list.GetItems(CamlQuery.CreateAllFoldersQuery());
				ctx.Load(Folderitems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.DisplayName),
					a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
					permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
					roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
					roleDef => roleDef.Description))));
				ctx.Load(Folderitems);
				ctx.ExecuteQuery();

				string sPermissionLevel = string.Empty;

				foreach (var item in Folderitems)
				{
					//Console.WriteLine("{0} folder permissions", item.DisplayName);
					//permissionItem oFolderPermissionItem = null;
					//if (item.HasUniqueRoleAssignments)
					//{
					foreach (var assignment in item.RoleAssignments)
					{
						var oFolderPermissionItem = new permissionItem();
						Console.WriteLine(assignment.Member.Title);
						oFolderPermissionItem.Title = item["FileRef"].ToString();
						oFolderPermissionItem.Type = "Folder";
						oFolderPermissionItem.UserGroup = assignment.Member.Title;
						List<string> roles = new List<string>();
						foreach (var role in assignment.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							switch (role.Name)
							{
								case "Full Control":
									oFolderPermissionItem.FullControl = assignment.Member.Title;
									break;
								case "Contribute":
									oFolderPermissionItem.Contribute = assignment.Member.Title;
									break;
								case "Read":
									oFolderPermissionItem.Read = assignment.Member.Title;
									break;
							}
							sPermissionLevel += role.Name + ",";
						}
						if (item.HasUniqueRoleAssignments)
						{
							oFolderPermissionItem.Inherited = "No";
						}
						else
						{
							oFolderPermissionItem.Inherited = "Yes";
						}
						oFolderPermissionItem.PermissionLevel = sPermissionLevel.TrimEnd(',');
						oFolderPermissionItem.PrincipalType = assignment.Member.PrincipalType.ToString();

						if (oFolderPermissionItem.FullControl == string.Empty && oFolderPermissionItem.Contribute == string.Empty && oFolderPermissionItem.Read == string.Empty)
						{
							
						}
						else
						{
							lstPermissionItem.Add(oFolderPermissionItem);
						}
						sPermissionLevel = string.Empty;
					}

				}
				#region Sample
				//ctx.Load(Folderitems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.DisplayName));
				//ctx.Load(Folderitems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments), a => a.di);
				//	ctx.Load(Folderitems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
				//permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
				//roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
				//roleDef => roleDef.Description))));

				//else
				/*{
					foreach (var assignment in item.RoleAssignments)
					{
						oFolderPermissionItem.Title = item.DisplayName;
						oFolderPermissionItem.Type = "Folder";
						oFolderPermissionItem.UserGroup = assignment.Member.Title;

						Console.WriteLine(assignment.Member.Title);
						List<string> roles = new List<string>();
						foreach (var role in assignment.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							sPermissionLevel += role.Description + ",";
						}
						oFolderPermissionItem.PermissionLevel = sPermissionLevel;
						{
							oFolderPermissionItem.Inherited = "No";
						}
						oFolderPermissionItem.PrincipalType = assignment.Member.PrincipalType.ToString();
						lstPermissionItem.Add(oFolderPermissionItem);
						sPermissionLevel = string.Empty;
					}
				}

				//lstPermissionItem.Add(oFolderPermissionItem);
			}
			*/
				#endregion

				/// <remarks>
				/// Add the item object to List collection 
				/// </remarks>
				#endregion
			#region File
				CamlQuery camlQuery = new CamlQuery();
				camlQuery.ViewXml =
					@"<View Scope='Recursive' />";

				var listItems = list.GetItems(camlQuery);
				//load all list items with default properties and HasUniqueRoleAssignments property
				ctx.Load(listItems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.File.Name),
					a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
					permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
					roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
					roleDef => roleDef.Description))));
				ctx.ExecuteQuery();

				foreach (var item in listItems)
				{
					//Console.WriteLine("List item: " + item["FileRef"].ToString());
					//load permissions if item has unique permission
					foreach (var roleAsg in item.RoleAssignments)
					{
						var oItemPermissionItem = new permissionItem();
						Console.WriteLine(roleAsg.Member.Title);
						oItemPermissionItem.Title = item["FileRef"].ToString(); 
						oItemPermissionItem.Type = "File";
						oItemPermissionItem.UserGroup = roleAsg.Member.Title;

						Console.WriteLine("User/Group: " + roleAsg.Member.LoginName);
						List<string> roles = new List<string>();
						foreach (var role in roleAsg.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							switch (role.Name)
							{
								case "Full Control":
									oItemPermissionItem.FullControl = roleAsg.Member.Title;
									break;
								case "Contribute":
									oItemPermissionItem.Contribute = roleAsg.Member.Title;
									break;
								case "Read":
									oItemPermissionItem.Read = roleAsg.Member.Title;
									break;
							}
							sPermissionLevel += role.Name + ",";
						}
						if (item.HasUniqueRoleAssignments)
						{
							oItemPermissionItem.Inherited = "No";
						}
						else
						{
							oItemPermissionItem.Inherited = "Yes";
						}
						oItemPermissionItem.PermissionLevel = sPermissionLevel.TrimEnd(',');
						oItemPermissionItem.PrincipalType = roleAsg.Member.PrincipalType.ToString();
						if (oItemPermissionItem.FullControl == string.Empty && oItemPermissionItem.Contribute == string.Empty && oItemPermissionItem.Read == string.Empty)
						{

						}
						else
						{
							lstPermissionItem.Add(oItemPermissionItem);
						}
						sPermissionLevel = string.Empty;
					}
				}
				#endregion

			ExportToExcel(lstPermissionItem,ListName);
			Console.WriteLine("Report generated");
			Console.ReadLine();
			}
		} //Main  
        public ActionResult EmployeeForm()
        {
            Employee emp = new Employee();

            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        SetupManager.Provision(clientContext);

                        var web = clientContext.Web;

                        List desgList = web.Lists.GetByTitle("EmpDesignation");
                        ListItemCollection desgItems = desgList.GetItems(CamlQuery.CreateAllItemsQuery());

                        List countryList = web.Lists.GetByTitle("EmpCountry");
                        ListItemCollection countryItems = countryList.GetItems(CamlQuery.CreateAllItemsQuery());

                        string   itemID      = Request.QueryString["itemId"];
                        ListItem emplistItem = null;

                        if (itemID != null)
                        {
                            List lstEmployee = web.Lists.GetByTitle("Employees");
                            emplistItem = lstEmployee.GetItemById(itemID);
                            clientContext.Load(emplistItem);
                            emp.Id = itemID;
                        }

                        clientContext.Load(desgItems);
                        clientContext.Load(countryItems);
                        clientContext.ExecuteQuery();

                        List <SelectListItem> empDesgList = new List <SelectListItem>();
                        foreach (var item in desgItems)
                        {
                            empDesgList.Add(new SelectListItem {
                                Text = item["Title"].ToString()
                            });
                        }
                        emp.Designations = new SelectList(empDesgList, "Text", "Text");

                        List <SelectListItem> cList = new List <SelectListItem>();
                        foreach (var item in countryItems)
                        {
                            cList.Add(new SelectListItem {
                                Text = item["Title"].ToString(), Value = item["ID"].ToString()
                            });
                        }
                        emp.Countries = new SelectList(cList, "Value", "Text");

                        string empDesignation = string.Empty;
                        int    stateID        = 0;
                        int    countryId      = 0;

                        if (emplistItem != null)
                        {
                            emp.EmpNumber   = ConvertObjectToString(emplistItem["EmpNumber"]);
                            emp.Name        = ConvertObjectToString(emplistItem["Title"]);
                            emp.UserID      = ConvertObjectToString(emplistItem["UserID"]);
                            emp.EmpManager  = ConvertObjectToString(emplistItem["EmpManager"]);
                            emp.Designation = ConvertObjectToString(emplistItem["Designation"]);

                            string cityVal = ConvertObjectToString(emplistItem["Location"]);
                            ViewBag.JsCity    = "";
                            ViewBag.JsStateID = "";

                            if (cityVal != "")
                            {
                                ViewBag.JsCity = cityVal;
                                List      lstCity = web.Lists.GetByTitle("EmpCity");
                                CamlQuery query   = new CamlQuery();
                                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", cityVal);
                                ListItemCollection cityItems = lstCity.GetItems(query);
                                clientContext.Load(cityItems);
                                clientContext.ExecuteQuery();
                                if (cityItems.Count > 0)
                                {
                                    stateID = (cityItems[0]["State"] as FieldLookupValue).LookupId;
                                }
                                ViewBag.JsStateID = stateID;

                                List lstSate = web.Lists.GetByTitle("EmpState");
                                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>", stateID);
                                ListItemCollection stateItems = lstSate.GetItems(query);
                                clientContext.Load(stateItems);
                                clientContext.ExecuteQuery();
                                if (stateItems.Count > 0)
                                {
                                    countryId = (stateItems[0]["Country"] as FieldLookupValue).LookupId;
                                }
                                emp.CountryID = countryId.ToString();
                            }

                            string       skillsData = ConvertObjectToString(emplistItem["Skills"]);
                            string[]     skills     = skillsData.Split(';');
                            List <Skill> lsSkills   = new List <Skill>();
                            foreach (string skillData in skills)
                            {
                                if (skillData != "")
                                {
                                    string[] skill = skillData.Split(',');
                                    lsSkills.Add(new Skill {
                                        Technology = skill[0], Experience = skill[1]
                                    });
                                }
                            }
                            emp.Skills      = lsSkills;
                            emp.SkillsCount = lsSkills.Count;

                            string attachementID = ConvertObjectToString(emplistItem["AttachmentID"]);
                            if (attachementID != "")
                            {
                                List      lstAttachments   = web.Lists.GetByTitle("EmpAttachments");
                                CamlQuery queryAttachments = new CamlQuery();
                                queryAttachments.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='AttachmentID' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", attachementID);

                                ListItemCollection attachmentItems = lstAttachments.GetItems(queryAttachments);
                                clientContext.Load(attachmentItems);
                                clientContext.ExecuteQuery();

                                List <EmpAttachment> lsAttachments = new List <EmpAttachment>();
                                if (attachmentItems.Count > 0)
                                {
                                    foreach (ListItem item in attachmentItems)
                                    {
                                        lsAttachments.Add(new EmpAttachment
                                        {
                                            FileName        = item["Title"].ToString(),
                                            FileUrl         = Request.QueryString["SPHostUrl"] + "/Lists/EmpAttachments/" + item["FileLeafRef"].ToString(),
                                            FileRelativeUrl = item["FileRef"].ToString()
                                        });
                                    }
                                }
                                emp.AttachmentID     = attachementID;
                                emp.Attachments      = lsAttachments;
                                emp.AttachmentsCount = lsAttachments.Count;
                            }
                            else
                            {
                                emp.AttachmentID = Guid.NewGuid().ToString();
                            }

                            emp.ActionName       = "UpdateEmployeeToSPList";
                            emp.SubmitButtonName = "Update Employee";
                        }
                        else
                        {
                            PeopleManager    peopleManager    = new PeopleManager(clientContext);
                            PersonProperties personProperties = peopleManager.GetMyProperties();
                            clientContext.Load(personProperties, p => p.AccountName);
                            clientContext.ExecuteQuery();

                            if (personProperties != null && personProperties.AccountName != null)
                            {
                                emp.UserID = personProperties.AccountName;
                            }

                            List <Skill> lsSkills = new List <Skill>();
                            lsSkills.Add(new Skill {
                                Technology = "", Experience = ""
                            });
                            emp.Skills      = lsSkills;
                            emp.SkillsCount = lsSkills.Count;

                            emp.AttachmentID   = Guid.NewGuid().ToString();
                            emp.isFileUploaded = false;

                            emp.ActionName       = "AddEmployeeToSPList";
                            emp.SubmitButtonName = "Add Employee";
                        }

                        LoadUserSiteGroups(ref emp, clientContext);
                    } //  if (clientContext != null)
                }     // using (var clientContext

                ViewBag.SPURL = Request.QueryString["SPHostUrl"];
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message + "\n" + ex.StackTrace;
            }

            return(View(emp));
        }
Пример #28
0
        static void Main(string[] args)
        {
            DBM db = new DBM();

            foreach (DataRow dr in db.getRecordForMergingStatics().Rows)
            {
                string url = "http://*****:*****@"<View> <Query>  <Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + dr["BlogID"].ToString() + "</Value></Eq></Where> </Query></View>";

                ListItemCollection listItems = spList.GetItems(camlQuery);
                ctx.Load(listItems);
                ctx.ExecuteQuery();

                //ListItem lst = oWeb.Lists.GetByTitle(name).GetItemById(Convert.ToInt32(dr["BlogID"].ToString()));
                //ctx.Load(lst);
                //ctx.ExecuteQuery();
                foreach (ListItem lst in listItems)
                {
                    string like, comment, promote, dblike, dbcomment, dbpromote = string.Empty;
                    like    = (lst["TotalLikeCount"] == null ? "0" : lst["TotalLikeCount"].ToString());
                    comment = (lst["TotalCommentCount"] == null ? "0" : lst["TotalCommentCount"].ToString());
                    if (dr["Segment"].ToString().ToLower() != "root")
                    {
                        promote = (lst["TotalPromotedCount"] == null ? "0" : lst["TotalPromotedCount"].ToString());
                    }
                    else
                    {
                        promote = "0";
                    }
                    dblike    = dr["Like"].ToString();
                    dbcomment = dr["Comment"].ToString();
                    dbpromote = dr["Promote"].ToString();
                    Console.WriteLine(string.Format("List item {0} : DB {1}", like, dblike));
                    Console.WriteLine(string.Format("List item {0} : DB {1}", comment, dbcomment));
                    Console.WriteLine(string.Format("List item {0} : DB {1}", promote, dbpromote));

                    if (like == dblike && comment == dbcomment && promote == dbpromote)
                    {
                        break;
                    }
                    else
                    {
                        //update
                        //ctx.Load(lst);
                        lst["TotalLikeCount"]    = dblike;
                        lst["TotalCommentCount"] = dbcomment;
                        if (dr["Segment"].ToString().ToLower() != "root")
                        {
                            lst["TotalPromotedCount"] = dbpromote;
                        }
                        lst.Update();
                        ctx.ExecuteQuery();
                    }
                }
            }
        }
Пример #29
0
        public static void GetAndSetDurationOnPMPSubSiteTaskLists(string siteUrl, string sharepoint_Login, SecureString securePassword, string taskName, List <AllTimeSheetData> allMilestoneItems)
        {
            ClientContext clientContext = new ClientContext(siteUrl);

            List oList = clientContext.Web.Lists.GetByTitle("Schedule");

            CamlQuery          camlQuery    = new CamlQuery();
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem);

            var onlineCredentials = new SharePointOnlineCredentials(sharepoint_Login, securePassword);

            clientContext.Credentials = onlineCredentials;
            clientContext.ExecuteQuery();

            //var groupItem = allTimeSheetData.Where(x => x.jobcode_id == spItem.Select(y => y.id).FirstOrDefault()).GroupBy(x => x.id);

            float installation = 0; float projectManagement = 0; float fabrication = 0; float preProduction = 0;
            float installationVal = 0; float projectManagementVal = 0;
            float fabricationVal = 0; float preProductionVal = 0;

            foreach (var item in allMilestoneItems)
            {
                if (item.customfields.SecondColumn == "Installation")
                {
                    installation = installation + Convert.ToInt64(item.duration);
                }
                else if (item.customfields.SecondColumn == "Project Management")
                {
                    projectManagement = projectManagement + Convert.ToInt64(item.duration);
                }
                else if (item.customfields.SecondColumn == "Fabrication")
                {
                    fabrication = fabrication + Convert.ToInt64(item.duration);
                }
                else if (item.customfields.SecondColumn == "Pre Production")
                {
                    preProduction = preProduction + Convert.ToInt64(item.duration);
                }
            }

            float installhours = (float)System.Math.Round(installation / 3600, 2);

            installationVal = installhours;

            float projectMhours = (float)System.Math.Round(projectManagement / 3600, 2);

            projectManagementVal = projectMhours;

            float fabhours = (float)System.Math.Round(fabrication / 3600, 2);

            fabricationVal = fabhours;

            float prePhours = (float)System.Math.Round(preProduction / 3600, 2);

            preProductionVal = prePhours;

            foreach (ListItem oListItem in collListItem)
            {
                if (Convert.ToString(oListItem["Title"]) == taskName)
                {
                    ListItemCreationInformation itemInfo = new ListItemCreationInformation();
                    ListItem myItem = oList.GetItemById(Convert.ToString(oListItem["ID"]));
                    myItem["Actual_x0020_Install"]             = installationVal;
                    myItem["Actual_x0020_Project_x0020_Manag"] = projectManagementVal;
                    myItem["Actual_x0020_Fabrication"]         = fabricationVal;
                    myItem["Actual_x0020_Pre_x0020_Productio"] = preProductionVal;
                    try
                    {
                        //myItem.Update();
                        clientContext.Credentials = onlineCredentials;
                        //clientContext.ExecuteQuery();
                        Console.WriteLine("Item Updated Successfully name: " + taskName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Пример #30
0
        public static void GetAllProjectIdForProjectId()
        {
            int             currentPage  = 1;
            bool            moreData     = true;
            List <string>   projectNames = new List <string>();
            List <Projects> projects     = new List <Projects>();
            var             tsheetsApi   = new RestClient(_connection, _authProvider);

            while (moreData)
            {
                var filters = new Dictionary <string, string>();
                filters.Add("parent_ids", "0");
                filters["per_page"] = "50";
                filters["page"]     = Convert.ToString(currentPage);

                var projectData      = tsheetsApi.Get(ObjectType.Jobcodes, filters);
                var projectDataObj   = JObject.Parse(projectData);
                var ienumProjectData = projectDataObj.SelectTokens("results.jobcodes.*");
                foreach (var ie in ienumProjectData)
                {
                    projects.Add(JsonConvert.DeserializeObject <Projects>(Convert.ToString(ie)));
                }
                // see if we have more pages to retrieve
                moreData = bool.Parse(projectDataObj.SelectToken("more").ToString());

                // increment to the next page
                currentPage++;
            }

            //NOTE: Get all the projects lists
            string        PMPSiteUrl    = "https://leonlebeniste.sharepoint.com/sites/PMP";
            ClientContext clientContext = new ClientContext(PMPSiteUrl);

            List oList = clientContext.Web.Lists.GetByTitle("LL Projects List");

            CamlQuery          camlQuery    = new CamlQuery();
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem);

            string sharepoint_Login    = ConfigurationManager.AppSettings.Get("sharepoint_Login_PMP");
            string sharepoint_Password = ConfigurationManager.AppSettings.Get("sharepoint_Password_PMP");
            var    securePassword      = new SecureString();

            foreach (char c in sharepoint_Password)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(sharepoint_Login, securePassword);

            clientContext.Credentials = onlineCredentials;
            clientContext.ExecuteQuery();

            foreach (var project in projects)
            {
                //NOTE: Process updating project id

                string projectName = project.name.Substring(0, 5);
                if (!projectNames.Contains(projectName))
                {
                    projectNames.Add(projectName);

                    foreach (ListItem oListItem in collListItem)
                    {
                        if (projectName == Convert.ToString(oListItem["ProjectNumber"]))
                        {
                            if (project.id != Convert.ToInt64(oListItem["ProjID"]))
                            {
                                //NOTE: Update Project ID in list.
                                ListItem myItem = oList.GetItemById(Convert.ToString(oListItem["ID"]));
                                myItem["ProjID"] = project.id;
                                try
                                {
                                    myItem.Update();
                                    clientContext.Credentials = onlineCredentials;
                                    clientContext.ExecuteQuery();
                                    Console.WriteLine("Project ID Successfully Update for: " + projectName);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                            //NOTE: Process updating timesheet hours.
                            GetAllJobCodeIdForProjectId(project.id);
                        }
                    }
                }
            }
        }
 private bool ClauseExists(ClientContext clientContext, List list, XElement clauseId)
 {
     const string clauseQueryTemplate = "<Query><Where><Eq><FieldRef Name=\"ClauseID\" /><Value Type=\"Number\">{0}</Value></Eq></Where></Query>";
     var query = new CamlQuery
     {
         ViewXml = string.Format(CultureInfo.InvariantCulture, clauseQueryTemplate, clauseId)
     };
     ListItemCollection queryResults = list.GetItems(query);
     clientContext.Load(queryResults);
     clientContext.ExecuteQuery();
     return queryResults.Count > 0;
 }
Пример #32
0
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }

            var template = ReadProvisioningTemplate
                           .LoadProvisioningTemplateFromFile(Path,
                                                             TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }
            //We will remove a list if it's found so we can get the list

            ListInstance listInstance = template.Lists.Find(l => l.Title == List.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file!");
            }

            List spList = List.GetList(SelectedWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            if (TokenizeUrls.IsPresent)
            {
                ClientContext.Load(ClientContext.Web, w => w.Url, w => w.ServerRelativeUrl, w => w.Id);
                ClientContext.Load(ClientContext.Site, s => s.Url, s => s.ServerRelativeUrl, s => s.Id);
                ClientContext.Load(ClientContext.Web.Lists, lists => lists.Include(l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            }

            CamlQuery query = new CamlQuery();

            var viewFieldsStringBuilder = new StringBuilder();

            if (Fields != null)
            {
                viewFieldsStringBuilder.Append("<ViewFields>");
                foreach (var field in Fields)
                {
                    viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field);
                }
                viewFieldsStringBuilder.Append("</ViewFields>");
            }

            query.ViewXml = string.Format("<View>{0}{1}</View>", Query, viewFieldsStringBuilder);
            var listItems = spList.GetItems(query);

            ClientContext.Load(listItems, lI => lI.Include(l => l.HasUniqueRoleAssignments, l => l.ContentType.StringId));
            ClientContext.ExecuteQueryRetry();

            Microsoft.SharePoint.Client.FieldCollection fieldCollection = spList.Fields;
            ClientContext.Load(fieldCollection, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.ReadOnlyField));
            ClientContext.ExecuteQueryRetry();

            var rows = new DataRowCollection(template);

            foreach (var listItem in listItems)
            {
                //Make sure we don't pull Folders.. Of course this won't work
                if (listItem.ServerObjectIsNull == false)
                {
                    ClientContext.Load(listItem);
                    ClientContext.ExecuteQueryRetry();
                    if (!(listItem.FileSystemObjectType == FileSystemObjectType.Folder))
                    {
                        DataRow row = new DataRow();
                        if (IncludeSecurity && listItem.HasUniqueRoleAssignments)
                        {
                            row.Security.ClearSubscopes      = true;
                            row.Security.CopyRoleAssignments = false;

                            var roleAssignments = listItem.RoleAssignments;
                            ClientContext.Load(roleAssignments);
                            ClientContext.ExecuteQueryRetry();

                            ClientContext.Load(roleAssignments, r => r.Include(a => a.Member.LoginName, a => a.Member, a => a.RoleDefinitionBindings));
                            ClientContext.ExecuteQueryRetry();

                            foreach (var roleAssignment in roleAssignments)
                            {
                                var principalName = roleAssignment.Member.LoginName;
                                var roleBindings  = roleAssignment.RoleDefinitionBindings;
                                foreach (var roleBinding in roleBindings)
                                {
                                    row.Security.RoleAssignments.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.RoleAssignment()
                                    {
                                        Principal = principalName, RoleDefinition = roleBinding.Name
                                    });
                                }
                            }
                        }
                        if (Fields != null)
                        {
                            foreach (var fieldName in Fields)
                            {
                                Microsoft.SharePoint.Client.Field dataField = fieldCollection.FirstOrDefault(f => f.InternalName == fieldName);

                                if (dataField != null)
                                {
                                    var defaultFieldValue = GetFieldValueAsText(ClientContext.Web, listItem, dataField);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        defaultFieldValue = Tokenize(defaultFieldValue, ClientContext.Web, ClientContext.Site);
                                    }

                                    row.Values.Add(fieldName, defaultFieldValue);
                                }
                            }
                        }
                        else
                        {
                            //All fields are added except readonly fields and unsupported field type
                            var fieldsToExport = fieldCollection.AsEnumerable()
                                                 .Where(f => !f.ReadOnlyField && !_unsupportedFieldTypes.Contains(f.FieldTypeKind));
                            foreach (var field in fieldsToExport)
                            {
                                var fldKey = (from f in listItem.FieldValues.Keys where f == field.InternalName select f).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fldKey))
                                {
                                    var fieldValue = GetFieldValueAsText(ClientContext.Web, listItem, field);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        fieldValue = Tokenize(fieldValue, ClientContext.Web, ClientContext.Site);
                                    }
                                    row.Values.Add(field.InternalName, fieldValue);
                                }
                            }
                        }

                        rows.Add(row);
                    }
                }
            }
            template.Lists.Remove(listInstance);
            listInstance.DataRows.AddRange(rows);
            template.Lists.Add(listInstance);

            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
Пример #33
0
        // (Compare with ContentIterator for Server OM)
        static void ProcessListItems(List list, IList<string> fieldNames, Action<ListItem> action)
        {
            CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(5, fieldNames.ToArray());

            var retrievalsList = new List<Expression<Func<ListItem, object>>>();
            foreach (string fieldName in fieldNames)
                retrievalsList.Add(listItemArg => listItemArg[fieldName]);
            var retrievals = retrievalsList.ToArray();

            ListItemCollectionPosition itemPosition = null;

            int itemCount = 0;
            for (; ; )
            {
                camlQuery.ListItemCollectionPosition = itemPosition;

                ListItemCollection listItems = list.GetItems(camlQuery);
                clientContext.Load(listItems,
                  listItemsArg => listItemsArg.ListItemCollectionPosition,
                  listItemsArg => listItemsArg.Include(retrievals)
                );
                clientContext.ExecuteQuery();

                itemPosition = listItems.ListItemCollectionPosition;

                foreach (ListItem listItem in listItems)
                {
                    action(listItem);
                    ++itemCount;
                }

                Log("Processed batch: " + itemCount);

                if (itemPosition == null)
                    break;
            }
        }
Пример #34
0
        public void UpdateInspectionAndIncidentListItems(DateTime demodate)
        {
            List      inspctionlist      = clientContext.Web.Lists.GetByTitle("Inspections");
            CamlQuery inspectionquery    = new CamlQuery();
            String    inspectionqueryxml = "<View><Query><OrderBy><FieldRef Name=\"ID\" Ascending=\"FALSE\"></FieldRef></OrderBy></Query><ViewFields><FieldRef Name=\"ID\"/><FieldRef Name=\"sl_datetime\"/><FieldRef Name=\"sl_finalized\"/></ViewFields><RowLimit>5</RowLimit></View>";

            inspectionquery.ViewXml = inspectionqueryxml;

            List      incidentlist     = clientContext.Web.Lists.GetByTitle("Incidents");
            CamlQuery incidentquery    = new CamlQuery();
            String    incidentqueryxml = "<View><Query><OrderBy><FieldRef Name=\"ID\" Ascending=\"FALSE\"></FieldRef></OrderBy></Query><ViewFields><FieldRef Name=\"ID\"/><FieldRef Name=\"sl_date\"/></ViewFields><RowLimit>3</RowLimit></View>";

            incidentquery.ViewXml = incidentqueryxml;

            ListItemCollection inspectionitems = inspctionlist.GetItems(inspectionquery);
            ListItemCollection incidentitems   = incidentlist.GetItems(incidentquery);

            clientContext.Load(inspectionitems);
            clientContext.Load(incidentitems);
            clientContext.ExecuteQuery();

            if (inspectionitems.Count == 5)
            {
                ListItem listItem0 = inspectionitems[0];
                listItem0["sl_datetime"] = this.getNewDateTime(1, 20, 0, demodate);
                listItem0.Update();

                ListItem listItem1 = inspectionitems[1];
                listItem1["sl_datetime"] = this.getNewDateTime(1, 19, 0, demodate);
                listItem1.Update();

                ListItem listItem2 = inspectionitems[2];
                listItem2["sl_datetime"] = this.getNewDateTime(0, 21, 0, demodate);
                //listItem2["sl_finalized"] = this.getNewDateTime(0, 21, 30, demodate);
                listItem2.Update();

                ListItem listItem3 = inspectionitems[3];
                listItem3["sl_datetime"] = this.getNewDateTime(0, 20, 0, demodate);
                //listItem3["sl_finalized"] = this.getNewDateTime(0, 20, 30, demodate);
                listItem3.Update();

                ListItem listItem4 = inspectionitems[4];
                listItem4["sl_datetime"] = this.getNewDateTime(0, 19, 0, demodate);
                //listItem4["sl_finalized"] = this.getNewDateTime(0, 19, 30, demodate);
                listItem4.Update();
                clientContext.ExecuteQuery();
            }
            if (incidentitems.Count == 3)
            {
                ListItem listItem2 = incidentitems[0];
                listItem2["sl_date"] = this.getNewDateTime(0, 21, 10, demodate);
                listItem2.Update();

                ListItem listItem3 = incidentitems[1];
                listItem3["sl_date"] = this.getNewDateTime(0, 20, 10, demodate);
                listItem3.Update();

                ListItem listItem4 = incidentitems[2];
                listItem4["sl_date"] = this.getNewDateTime(0, 19, 10, demodate);
                listItem4.Update();
                clientContext.ExecuteQuery();
            }
        }
Пример #35
0
        public ActionResult FoldersInfo(string path)
        {
            if (Session["context"] == null)
            {
            }

            List <DocumentsInfo> documents       = new List <DocumentsInfo>();
            SharePointContext    spContext       = (SharePointContext)Session["context"];
            ListItemCollection   myDiffrentInfos = null;

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    Web  myWeb         = clientContext.Web;
                    List differentInfo = myWeb.Lists.GetByTitle("Documents");
                    clientContext.Load(differentInfo);
                    clientContext.Load(differentInfo.RootFolder);
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View>                   
                       <Query>
                      <OrderBy>
                      <FieldRef Name='FolderChildCount' Ascending='False' />
                      </OrderBy>
                      </Query>
                    <ViewFields>
                       <FieldRef Name='FileLeafRef' />
                       <FieldRef Name='ID' />
                       <FieldRef Name='Modified' />
                       <FieldRef Name='Created' />
                       <FieldRef Name='ItemChildCount' />
                       <FieldRef Name='FolderChildCount' />
                       <FieldRef Name='File_x0020_Type' />
                       <FieldRef Name='FSObjType' />
                    </ViewFields>
                    <QueryOptions />
                    </View>";

                    camlQuery.FolderServerRelativeUrl = path;
                    myDiffrentInfos = differentInfo.GetItems(camlQuery);

                    clientContext.Load(myDiffrentInfos);
                    clientContext.ExecuteQuery();

                    foreach (var item in myDiffrentInfos)
                    {
                        documents.Add(new DocumentsInfo
                        {
                            ID                       = item["ID"].ToString(),
                            FileLeafRef              = item["FileLeafRef"].ToString(),
                            Modified                 = item["Modified"].ToString(),
                            Created                  = item["Created"].ToString(),
                            ItemChildCount           = Convert.ToInt32(item["ItemChildCount"]),
                            FolderChildCount         = Convert.ToInt32(item["FolderChildCount"]),
                            fileType                 = (item["File_x0020_Type"] == null) ? "" : item["File_x0020_Type"].ToString(),
                            FileRef                  = item["FileRef"].ToString(),
                            FSObjType                = Convert.ToInt32(item["FSObjType"]),
                            ServerRedirectedEmbedUri = (item["ServerRedirectedEmbedUri"] == null) ? "" : item["ServerRedirectedEmbedUri"].ToString()
                        });
                    }
                }
            }



            return(Json(documents, JsonRequestBehavior.AllowGet));
        }
Пример #36
0
        private ListItem EnsureListItem(List list, ListItemDefinition listItemModel)
        {
            var context = list.Context;

            // TODO, lazy to query
            var items = list.GetItems(CamlQuery.CreateAllItemsQuery());

            context.Load(items);
            context.ExecuteQuery();

            // BIG TODO, don't tell me, I know that
            var currentItem = items.FirstOrDefault(i => i["Title"] != null &&
                    (i["Title"].ToString() == listItemModel.Title));

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentItem,
                ObjectType = typeof(ListItem),
                ObjectDefinition = listItemModel,
                ModelHost = list
            });

            if (currentItem == null)
            {
                var newItem = list.AddItem(new ListItemCreationInformation());

                newItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                newItem.Update();

                context.ExecuteQuery();

                return newItem;
            }
            else
            {
                currentItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = currentItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                currentItem.Update();

                context.ExecuteQuery();

                return currentItem;
            }
        }
Пример #37
0
        private void ProcessAction(List <Web> webs)
        {
            bool processAction;
            int  webCount = webs.Count;

            for (int webIndex = 0; webIndex < webCount; webIndex++)
            {
                Web currentWeb = webs[webIndex];

                //Update current connection context to the web that is beeing process
                //So commands like Get-SPOList returns the correct list for the current web beeing proccess
                SPOnlineConnection.CurrentConnection.Context = (ClientContext)currentWeb.Context;

                currentWeb.LoadProperties(_webActions.Properties);

                UpdateWebProgressBar(webs, webIndex, webCount, 0, _totalExecutionTimeStopWatch);

                if (!_webActions.ShouldProcessAnyAction(currentWeb))
                {
                    continue;
                }

                processAction = ProccessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessAction, _webActions.Action, ref _currentWebsProcessed, ref _averageWebTime, ref _averageShouldProcessWebTime);

                if (!processAction)
                {
                    continue;
                }

                if (_listActions.HasAnyAction || _listItemActions.HasAnyAction)
                {
                    ListCollection lists     = currentWeb.Lists;
                    int            listCount = lists.Count;

                    for (int listIndex = 0; listIndex < listCount; listIndex++)
                    {
                        List currentList = lists[listIndex];

                        if (_isListNameSpecified && !currentList.Title.Equals(_listName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }

                        UpdateWebProgressBar(webs, webIndex, webCount, listIndex, _totalExecutionTimeStopWatch);

                        UpdateListProgressBar(lists, listIndex, listCount);

                        processAction = ProccessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessAction, _listActions.Action, ref _currentListsProcessed, ref _averageListTime, ref _averageShouldProcessListTime);

                        if (!processAction)
                        {
                            continue;
                        }

                        if (_listItemActions.HasAnyAction)
                        {
                            ListItemCollection listItems = currentList.GetItems(CamlQuery.CreateAllItemsQuery());
                            currentList.Context.Load(listItems);
                            currentList.Context.ExecuteQueryRetry();

                            int listItemCount = listItems.Count;

                            for (int listItemIndex = 0; listItemIndex < listItemCount; listItemIndex++)
                            {
                                ListItem currentListItem = listItems[listItemIndex];

                                WriteIterationProgress(ListItemProgressBarId, ListProgressBarId, "Iterating list items", GetTitle(currentListItem), listItemIndex, listItemCount, CalculateRemainingTimeForListItems(listItemCount, listItemIndex));

                                ProccessAction(currentListItem, GetTitle, _listItemActions.Properties, _listItemActions.ShouldProcessAction, _listItemActions.Action, ref _currentListItemsProcessed, ref _averageListItemTime, ref _averageShouldProcessListItemTime);
                            }

                            CompleteProgressBar(ListItemProgressBarId);
                        }

                        processAction = ProccessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessPostAction, _listActions.PostAction, ref _currentPostListsProcessed, ref _averagePostListTime, ref _averageShouldProcessPostListTime);
                    }

                    CompleteProgressBar(ListProgressBarId);
                }

                processAction = ProccessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessPost, _webActions.PostAction, ref _currentPostWebsProcessed, ref _averagePostWebTime, ref _averageShouldProcessPostWebTime);
            }

            CompleteProgressBar(WebProgressBarId);
        }
Пример #38
0
        public ActionResult MenuInfo()
        {
            User spUser = null;
            List <DocumentsInfo> documents = new List <DocumentsInfo>();
            UserDocuments        info      = new UserDocuments();

            SharePointContext spContext = null;

            if (Session["context"] != null)
            {
                spContext = (SharePointContext)Session["context"];
            }



            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    spUser = clientContext.Web.CurrentUser;
                    clientContext.Load(spUser, user => user.Title);
                    clientContext.ExecuteQuery();
                }
            }


            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    Web       myWeb         = clientContext.Web;
                    List      differentInfo = myWeb.Lists.GetByTitle("Documents");
                    CamlQuery myQuery       = new CamlQuery();


                    myQuery.ViewXml = @"<View>                   
                       <Query>
                      <OrderBy>
                      <FieldRef Name='FolderChildCount' Ascending='False' />
                      </OrderBy>
                      </Query>
                    <ViewFields>
                       <FieldRef Name='FileLeafRef' />
                       <FieldRef Name='ID' />
                       <FieldRef Name='Modified' />
                       <FieldRef Name='Created' />
                       <FieldRef Name='ItemChildCount' />
                       <FieldRef Name='FolderChildCount' />
                       <FieldRef Name='File_x0020_Type' />
                       <FieldRef Name='FSObjType' />
                    </ViewFields>
                    <QueryOptions />
                    </View>";


                    ListItemCollection myDiffrentInfos = differentInfo.GetItems(myQuery);
                    clientContext.Load(myDiffrentInfos);
                    clientContext.ExecuteQuery();

                    foreach (var item in myDiffrentInfos)
                    {
                        documents.Add(new DocumentsInfo
                        {
                            ID                       = item["ID"].ToString(),
                            FileLeafRef              = item["FileLeafRef"].ToString(),
                            Modified                 = item["Modified"].ToString(),
                            Created                  = item["Created"].ToString(),
                            ItemChildCount           = Convert.ToInt32(item["ItemChildCount"]),
                            FolderChildCount         = Convert.ToInt32(item["FolderChildCount"]),
                            fileType                 = (item["File_x0020_Type"] == null) ? "" : item["File_x0020_Type"].ToString(),
                            FileRef                  = item["FileRef"].ToString(),
                            FSObjType                = Convert.ToInt32(item["FSObjType"]),
                            ServerRedirectedEmbedUri = (item["ServerRedirectedEmbedUri"] == null) ? "" : item["ServerRedirectedEmbedUri"].ToString()
                        });
                    }
                }
            }

            info.currentUser = spUser.Title;
            info.document    = documents;


            return(Json(info, JsonRequestBehavior.AllowGet));
        }
Пример #39
0
        /// <summary>
        /// This method executes a CAML query to get all old documents by content type
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="documentLibrary"></param>
        /// <param name="contentTypeName"></param>
        /// <param name="retentionPeriod"></param>
        private static void ApplyRetentionPolicy(ClientContext clientContext, List documentLibrary,
            object contentTypeId, int retentionPeriodDays)
        {
            //Calculate validation date. Any document modified before that date is considered old
            var validationDate = DateTime.Now.AddDays(-retentionPeriodDays);
            var camlDate = validationDate.ToString("yyyy-MM-ddTHH:mm:ssZ");

            //Get old documents in the library that are matching requested content type
            if (documentLibrary.ItemCount > 0)
            {
                var camlQuery = new CamlQuery();

                //This CAML query uses Content Type ID with BeginsWith.
                //You can replace with ContentType for CT Display Name, for example
                //<Eq><FieldRef Name='ContentType' /><Value Type='Computed'>{0}</Value></Eq>
                camlQuery.ViewXml = String.Format(
                    @"<View>
                        <Query>
                            <Where><And>
                                <BeginsWith><FieldRef Name='ContentTypeId'/><Value Type='ContentTypeId'>{0}</Value></BeginsWith>
                                <Lt><FieldRef Name='Modified' /><Value Type='DateTime'>{1}</Value></Lt>
                            </And></Where>
                        </Query>
                    </View>", contentTypeId, camlDate);

                var listItems = documentLibrary.GetItems(camlQuery);
                clientContext.Load(listItems,
                    items => items.Include(
                        item => item.Id,
                        item => item.DisplayName,
                        item => item.ContentType));

                //clientContext.ExecuteQuery(); // Commented out in favor of next line and execution throttling
                clientContext.ExecuteQueryWithExponentialRetry(10, 30000); //10 retries, with a base delay of 30 secs.

                foreach (var listItem in listItems)
                {
                    Console.WriteLine("Document '{0}' has been modified earlier than {1}. Retention policy will be applied.", listItem.DisplayName, validationDate);
                    ApplyRetentionActions(clientContext, listItem);
                }

                //perform Retention Actions
                clientContext.ExecuteQueryWithExponentialRetry(10, 30000);
            }
        }
        private void ApplyRetentionPolicy(ClientContext clientContext, List documentLibrary, object contentTypeId, int retentionPeriodDays)
        {
            //Calculate validation date. Any document modified before that date is considered old
            var validationDate = DateTime.Now.AddDays(-retentionPeriodDays);
            var camlDate = validationDate.ToString("yyyy-MM-ddTHH:mm:ssZ");

            //Get old documents in the library that are matching requested content type
            if (documentLibrary.ItemCount > 0)
            {
                var camlQuery = new CamlQuery();

                //This CAML query uses Content Type ID with BeginsWith.
                //You can replace with ContentType for CT Display Name, for example
                //<Eq><FieldRef Name='ContentType' /><Value Type='Computed'>{0}</Value></Eq>
                camlQuery.ViewXml = String.Format(
                    @"<View>
                        <Query>
                            <Where><And>
                                <BeginsWith><FieldRef Name='ContentTypeId'/><Value Type='ContentTypeId'>{0}</Value></BeginsWith>
                                <Lt><FieldRef Name='Modified' /><Value Type='DateTime'>{1}</Value></Lt>
                            </And></Where>
                        </Query>
                    </View>", contentTypeId, camlDate);

                var listItems = documentLibrary.GetItems(camlQuery);
                clientContext.Load(listItems,
                    items => items.Include(
                        item => item.Id,
                        item => item.DisplayName,
                        item => item.ContentType));

                clientContext.ExecuteQueryRetry(); 

                foreach (var listItem in listItems)
                {
                    Log.Info("ContentTypeRetentionEnforcementJob", "Document '{0}' has been modified earlier than {1}. Retention policy will be applied.", listItem.DisplayName, validationDate);
                    Console.WriteLine("Document '{0}' has been modified earlier than {1}. Retention policy will be applied.", listItem.DisplayName, validationDate);
                    
                    //Apply your retention actions here: e.g. archive document, start a disposition workflow,...
                }
            }
        }
Пример #41
0
        public ActionResult ChangeGrades()
        {
            // The following code does not work - use the default code that comes with HomeController. There
            //      seems to be an issue with the ClientContext object.
            //// Start with ClientContext - the constructor requires a URL to the server running SharePoint.
            //// This opens Context to the web, in a similar way to opening a connection to a database.
            //// Copy the URL of the website the Add-In is linked to.
            //ClientContext context = new ClientContext("https://agtivcaonsulting1.sharepoint.com/sites/trainingsite/SzunK/TrainingDay4/");

            User spUser = null;

            var             spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
            GradesViewModel vm        = new GradesViewModel();

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    spUser = clientContext.Web.CurrentUser;

                    clientContext.Load(spUser, user => user.Title);

                    clientContext.ExecuteQuery();

                    ViewBag.UserName = spUser.Title;
                }

                // The SharePoint web site contains a list called "Student Gradebook" - grab and store it in a List variable.
                // Linking to the list, like finding a table in a database
                List studentGradebook = clientContext.Web.Lists.GetByTitle("Student Gradebook");

                // CAML = Collaborative Application Markup Language
                // Query allows you to query for specific items from a list, using the ViewXml property.
                // Using CamlQuery.CreateAllItemsQuery() creates a query that retrieves all list items.
                CamlQuery query = CamlQuery.CreateAllItemsQuery();

                // This line grabs items from the studentGradebook List object based on the specified query, and
                //      stores them all in a ListItemCollection object.
                ListItemCollection studentGradebookCollection = studentGradebook.GetItems(query);

                // This line ties the ListItemCollection to the ClientContext object, providing a line of communication
                //      between the program and the SharePoint server. Without this line, the items queried for will
                //      not be retrieved from SharePoint.
                clientContext.Load(studentGradebookCollection);

                // Call ExecuteQuery() to perform the query, loading the specified items from SharePoint.
                clientContext.ExecuteQuery();

                foreach (ListItem grade in studentGradebookCollection)
                {
                    string courseTitle = (string)grade["Title"];
                    string passed      = (string)grade["Result"];
                    vm.GradeBook.Add(new Grade(courseTitle, passed));
                }

                // Call ExecuteQuery to commit changes made to the list.
                clientContext.ExecuteQuery();
            }

            // Changing display ResultColour of Grade Passed string
            // This is done in the controller because it has direct access to the GradeBook List of Grade objects.
            foreach (Grade grade in vm.GradeBook)
            {
                grade.ResultColor = grade.Passed.ToLower() == "pass" ? "color:Green" : "color:Red";
            }

            // Logic done here
            // Check for click of Save button, and execute whatever is required (aka copy from slides and notebook)
            // You might need to make [HttpGet] and [HttpPost] attributed methods
            // Upon obtaining the list, remember to update the colour of the text
            // Might also need to populate a local list based on data obtained from controller

            // Need to have both read and write functionality.

            // Pass the View Model object into the View. Why must this be done?
            return(View(vm));
        }
Пример #42
0
        /// <summary>
        /// 通过查询语句获取表单所有数据
        /// </summary>
        /// <param name="website">站点地址</param>
        /// <param name="listName">指定列表名称</param>
        /// <param name="querystring">指定查询语句</param>
        /// <returns>返回子项的集合</returns>
        public List <Dictionary <string, object> > ClientGetDic(string website, string listName, string querystring)
        {
            List <Dictionary <string, object> > dicList = new List <Dictionary <string, object> >();

            try
            {
                if (clientContext != null)
                {
                    //创建客户端对象模型
                    using (clientContext)
                    {
                        //获取列表
                        List oList = clientContext.Web.Lists.GetByTitle(listName);

                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = querystring;

                        //获取当前列表的所有项
                        Microsoft.SharePoint.Client.ListItemCollection collListItem = oList.GetItems(camlQuery);
                        //执行
                        clientContext.Load(collListItem);
                        clientContext.ExecuteQuery();

                        foreach (var item in collListItem)
                        {
                            dicList.Add(item.FieldValues);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MethodLb.CreateLog(this.GetType().FullName, "ClientGetDic", ex.ToString(), website, listName, querystring);
            }
            finally
            {
            }

            return(dicList);
        }
Пример #43
0
        static void Main(string[] args)
        {
            DateTime lastRefreshDate = DateTime.Now;

            while (true)
            {
                DateTime newRefreshDate = DateTime.Now;

                ClientContext context = new ClientContext("{sharepoint site url, e.g. https://microsoft.sharepoint.com/xyz}");

                // auth
                SecureString password = new SecureString();
                foreach (char c in "{sharepoint password}".ToCharArray())
                {
                    password.AppendChar(c);
                }
                var spCredentials = new SharePointOnlineCredentials("sharepoint username", password);
                context.Credentials = spCredentials;

                List docs = context.Web.Lists.GetByTitle("C&E News");
                context.Load(docs);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View Scope='RecursiveAll'></View>";
                ListItemCollection listItems = docs.GetItems(camlQuery);

                context.Load(listItems,
                             items => items.Include(
                                 item => item.FieldValuesAsText,
                                 item => item["fodb"],
                                 item => item["Category"],
                                 item => item["iisx"],
                                 item => item["Title"],
                                 item => item["Created"],
                                 item => item.DisplayName
                                 ));
                context.ExecuteQuery();

                foreach (ListItem listItem in listItems)
                {
                    Console.WriteLine("Headline: {0}", listItem["Title"]);
                    Console.WriteLine("Details: {0}", listItem.FieldValuesAsText.FieldValues["fodb"]);
                    Console.WriteLine("Category: {0}", listItem.FieldValuesAsText.FieldValues["Category"]);
                    Console.WriteLine("Author: {0}", listItem.FieldValuesAsText.FieldValues["iisx"]);

                    // if datetime created is after stored datetime, send notification
                    DateTime itemDate = Convert.ToDateTime(listItem["Created"]).ToLocalTime();
                    Console.WriteLine("Item time: {0}", itemDate);
                    Console.WriteLine("Last Refresh Time: {0}", lastRefreshDate);
                    Console.WriteLine("----------------");

                    if (DateTime.Compare(itemDate, lastRefreshDate) > 0)
                    {
                        var message = listItem["Title"] + " By " + listItem.FieldValuesAsText.FieldValues["iisx"];
                        SendNotificationAsync(message, new[] { listItem.FieldValuesAsText.FieldValues["Category"] });
                        Console.WriteLine("*****Sending notification......");
                    }
                }

                lastRefreshDate = newRefreshDate;
                Console.WriteLine("Sharepoint pull complete");
                Thread.Sleep(10000);
                Console.Clear();
            }
        }
Пример #44
0
        /// <summary>
        /// Assign Full control permission to items of specified list
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="list">SharePoint List object to assign full control over list-items</param>
        private static void AssignFullControltoListItem(ClientContext clientContext, List list)
        {
            try
            {
                CamlQuery query = new CamlQuery();
                query.ViewXml = ConfigurationManager.AppSettings["ListQuery"];
                ListItemCollection listItems = list.GetItems(query);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();

                clientContext.Load(list, lst => lst.EntityTypeName);
                clientContext.ExecuteQuery();

                RoleDefinition fullControl = clientContext.Web.RoleDefinitions.GetByType(RoleType.Administrator);
                clientContext.Load(fullControl);
                clientContext.ExecuteQuery();
                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ItemNotFound"], listItems.Count, list.EntityTypeName), ErrorMessage.MessageType.Notification);

                UpdateItems(clientContext, listItems, fullControl);
            }
            catch (Exception exception)
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, string.Concat(exception.Message, "\n", exception.StackTrace));
            }
        }
Пример #45
0
        public void CleanUp()
        {
            Console.WriteLine("BrandingExtensionsTests.CleanUp");

            if (System.IO.File.Exists(customColorFilePath))
            {
                System.IO.File.Delete(customColorFilePath);
            }
            if (System.IO.File.Exists(customBackgroundFilePath))
            {
                System.IO.File.Delete(customBackgroundFilePath);
            }

            using (var context = TestCommon.CreateClientContext())
            {
                var web = context.Web;

                // Remove composed looks from server
                List      themeGallery = web.GetCatalog((int)ListTemplateType.DesignCatalog);
                CamlQuery query        = new CamlQuery();
                string    camlString   = @"
                    <View>
                        <Query>                
                            <Where>
                                <Contains>
                                    <FieldRef Name='Name' />
                                    <Value Type='Text'>Test_</Value>
                                </Contains>
                            </Where>
                        </Query>
                    </View>";
                query.ViewXml = camlString;
                var found = themeGallery.GetItems(query);
                web.Context.Load(found);
                web.Context.ExecuteQueryRetry();
                Console.WriteLine("{0} matching looks found to delete", found.Count);
                var looksToDelete = found.ToList();
                foreach (var item in looksToDelete)
                {
                    Console.WriteLine("Delete look item '{0}'", item["Name"]);
                    item.DeleteObject();
                    context.ExecuteQueryRetry();
                }

                // Remove Theme Files
                List             themesList  = web.GetCatalog((int)ListTemplateType.ThemeCatalog);
                Folder           rootFolder  = themesList.RootFolder;
                FolderCollection rootFolders = rootFolder.Folders;
                web.Context.Load(rootFolder);
                web.Context.Load(rootFolders, f => f.Where(folder => folder.Name == "15"));
                web.Context.ExecuteQueryRetry();

                Folder folder15 = rootFolders.FirstOrDefault();

                try
                {
                    Microsoft.SharePoint.Client.File customColorFile = folder15.Files.GetByUrl("custom.spcolor");
                    customColorFile.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }

                try
                {
                    Microsoft.SharePoint.Client.File customBackgroundFile = folder15.Files.GetByUrl("custombg.jpg");
                    customBackgroundFile.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }

                // Remove webs
                var webCollection1 = web.Webs;
                context.Load(webCollection1, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl));
                context.ExecuteQueryRetry();
                var websToDelete = new List <Web>();
                foreach (var web1 in webCollection1)
                {
                    if (web1.Title.StartsWith("Test_"))
                    {
                        var webCollection2 = web1.Webs;
                        context.Load(webCollection2, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl));
                        context.ExecuteQueryRetry();
                        var childrenToDelete = new List <Web>(webCollection2);
                        foreach (var web2 in childrenToDelete)
                        {
                            Console.WriteLine("Deleting site {0}", web2.ServerRelativeUrl);
                            web2.DeleteObject();
                            context.ExecuteQueryRetry();
                        }
                        websToDelete.Add(web1);
                    }
                }

                foreach (var web1 in websToDelete)
                {
                    Console.WriteLine("Deleting site {0}", web1.ServerRelativeUrl);
                    web1.DeleteObject();
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception cleaning up: {0}", ex);
                    }
                }

                // Remove pagelayouts
                List   masterPageGallery             = context.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                Folder rootFolderInMasterPageGallery = masterPageGallery.RootFolder;
                context.Load(rootFolderInMasterPageGallery, f => f.ServerRelativeUrl);
                context.ExecuteQueryRetry();

                try
                {
                    var fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, publishingPageWithoutExtension);
                    var file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl));
                    context.Load(file);
                    context.ExecuteQueryRetry();
                    file.DeleteObject();
                    context.ExecuteQueryRetry();

                    fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, "test/test", publishingPageWithoutExtension);
                    file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl));
                    context.Load(file);
                    context.ExecuteQueryRetry();
                    file.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }
            }

            Teardown();
        }
        private static void MigreateContent_DiscussionBoard(ClientContext clientContext, List listToBeReplaced, List newList)
        {
            // Source Discussion Board List
            CamlQuery Query_SourceTopics = CamlQuery.CreateAllFoldersQuery();
            ListItemCollection Source_Topics = listToBeReplaced.GetItems(Query_SourceTopics);
            clientContext.Load(Source_Topics);
            clientContext.ExecuteQuery();

            foreach (ListItem Source_Topic in Source_Topics)
            {
                ListItem Target_Topic = Microsoft.SharePoint.Client.Utilities.Utility.CreateNewDiscussion(clientContext, newList, Source_Topic["Title"].ToString());

                Target_Topic["Body"] = Source_Topic["Body"];
                Target_Topic["Author"] = Source_Topic["Author"];
                Target_Topic["Created"] = Source_Topic["Created"];
                Target_Topic["Modified"] = Source_Topic["Modified"];

                Target_Topic.Update();
                clientContext.ExecuteQuery();

                // Target Discussion Board List
                CamlQuery Query_TargetTopics = CamlQuery.CreateAllFoldersQuery();
                ListItemCollection Target_Topics = newList.GetItems(Query_TargetTopics);
                clientContext.Load(Target_Topics);
                clientContext.ExecuteQuery();

                foreach (ListItem Target_Topics_Item in Target_Topics)
                {
                    if ((Source_Topic["Title"].ToString()).Equals(Target_Topics_Item["Title"].ToString()))
                    {
                        Query_SourceTopics = CamlQuery.CreateAllItemsQuery();
                        Query_SourceTopics.FolderServerRelativeUrl = Source_Topic["FileRef"].ToString();
                        Query_SourceTopics.ViewXml = "<View Scope='RecursiveAll'></View>";

                        //Updating/Loading the target list
                        ListItemCollection SourceTopics_Replies = listToBeReplaced.GetItems(Query_SourceTopics);
                        clientContext.Load(SourceTopics_Replies);
                        clientContext.ExecuteQuery();

                        //Copying the responses....
                        foreach (ListItem SourceTopics_reply in SourceTopics_Replies)
                        {
                            ListItem TargetTopics_reply = Microsoft.SharePoint.Client.Utilities.Utility.CreateNewDiscussionReply(clientContext, Target_Topics_Item);
                            TargetTopics_reply["Body"] = SourceTopics_reply["Body"];
                            TargetTopics_reply["Created"] = SourceTopics_reply["Created"];
                            TargetTopics_reply["Modified"] = SourceTopics_reply["Modified"];
                            TargetTopics_reply["Author"] = SourceTopics_reply["Author"];
                            TargetTopics_reply["ParentFolderId"] = SourceTopics_reply["ParentFolderId"];

                            TargetTopics_reply.Update();
                            clientContext.ExecuteQuery();
                        }
                    }
                }
            }
        }
Пример #47
0
        private void ExtractModel(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, ExtractSyntexModelsModelsConfiguration extractConfiguration, ListItem model, List trainingLibrary)
        {
            bool excludeTrainingData = false;

            if (extractConfiguration != null)
            {
                excludeTrainingData = extractConfiguration.ExcludeTrainingData;
            }

            // Add the model file to the template
            (bool fileAdded, string filePath, string fileName) = LoadAndAddSyntexFile(web, model.File, template, creationInfo, scope);

            // Export model metadata
            var templateFile = template.Files.FirstOrDefault(p => p.Src == $"{filePath}/{fileName}");

            if (templateFile != null)
            {
                if (model.FieldValues[Field_ModelExplanations] != null)
                {
                    templateFile.Properties.Add(Field_ModelExplanations, model.FieldValues[Field_ModelExplanations].ToString());
                }
                if (model.FieldValues[Field_ModelSchemas] != null)
                {
                    templateFile.Properties.Add(Field_ModelSchemas, model.FieldValues[Field_ModelSchemas].ToString());
                }
                if (model.FieldValues[Field_ModelDescription] != null)
                {
                    templateFile.Properties.Add(Field_ModelDescription, model.FieldValues[Field_ModelDescription].ToString());
                }
                if (model.FieldValues[Field_ModelMappedClassifierName] != null)
                {
                    templateFile.Properties.Add(Field_ModelMappedClassifierName, model.FieldValues[Field_ModelMappedClassifierName].ToString());
                }
                if (model.FieldValues[Field_ModelLastTrained] != null)
                {
                    templateFile.Properties.Add(Field_ModelLastTrained, model.FieldValues[Field_ModelLastTrained].ToString());
                }
                if (model.FieldValues[Field_ModelSettings] != null)
                {
                    templateFile.Properties.Add(Field_ModelSettings, model.FieldValues[Field_ModelSettings].ToString());
                }
                if (model.FieldValues[Field_ModelConfidenceScore] != null)
                {
                    templateFile.Properties.Add(Field_ModelConfidenceScore, model.FieldValues[Field_ModelConfidenceScore].ToString());
                }
                if (model.FieldValues[Field_ModelAccuracy] != null)
                {
                    templateFile.Properties.Add(Field_ModelAccuracy, model.FieldValues[Field_ModelAccuracy].ToString());
                }
                if (model.FieldValues[Field_ModelClassifiedItemCount] != null)
                {
                    templateFile.Properties.Add(Field_ModelClassifiedItemCount, model.FieldValues[Field_ModelClassifiedItemCount].ToString());
                }
                if (model.FieldValues[Field_ModelMismatchedItemCount] != null)
                {
                    templateFile.Properties.Add(Field_ModelMismatchedItemCount, model.FieldValues[Field_ModelMismatchedItemCount].ToString());
                }
            }

            // Extract training files
            if (trainingLibrary != null && !excludeTrainingData)
            {
                var camlQuery = new CamlQuery
                {
                    ViewXml = string.Format(
                        @"<View Scope='RecursiveAll'>
                                    <Query>
                                        <Where>
                                            <Eq>
                                                <FieldRef Name='SampleModelId' LookupId='TRUE'/>
                                                <Value Type='text'>{0}</Value>
                                            </Eq>
                                        </Where>
                                    </Query>
                                    <ViewFields>
                                        <FieldRef Name='Title'/>
                                        <FieldRef Name='SampleMarkups' />
                                        <FieldRef Name='SampleDescription' />
                                        <FieldRef Name='SampleExtractedText' />
                                        <FieldRef Name='SampleFileType' />
                                        <FieldRef Name='SampleLabelUptime' />
                                        <FieldRef Name='SampleTokenEndPosition' />
                                        <FieldRef Name='SampleTokenStartPosition' />
                                    </ViewFields>
                                  </View>", model.Id)
                };

                // Load training files associated to this model
                var trainingFiles = trainingLibrary.GetItems(camlQuery);
                web.Context.Load(trainingFiles, p => p.IncludeWithDefaultProperties(p => p.File, p => p.FieldValuesAsText));
                web.Context.ExecuteQueryRetry();

                foreach (var trainingFile in trainingFiles)
                {
                    // Export training files
                    (bool trainingFileAdded, string trainingFilePath, string trainingFileName) = LoadAndAddSyntexFile(web, trainingFile.File, template, creationInfo, scope);
                    var templateTrainingFile = template.Files.FirstOrDefault(p => p.Src == $"{trainingFilePath}/{trainingFileName}");
                    if (templateTrainingFile != null)
                    {
                        // Export training file metadata
                        templateTrainingFile.Properties.Add(Field_SampleModelId, $"{{filelistitemid:{templateFile.Src}}}");
                        if (trainingFile.FieldValues[Field_SampleMarkups] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleMarkups, TokenizeSampleMarkups(trainingFile.FieldValues[Field_SampleMarkups].ToString(), model.Id, $"{{filelistitemid:{templateFile.Src}}}"));
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleDescription) && trainingFile.FieldValues[Field_SampleDescription] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleDescription, trainingFile.FieldValues[Field_SampleDescription].ToString());
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleExtractedText) && trainingFile.FieldValues[Field_SampleExtractedText] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleExtractedText, trainingFile.FieldValues[Field_SampleExtractedText].ToString());
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleFileType) && trainingFile.FieldValues[Field_SampleFileType] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleFileType, trainingFile.FieldValues[Field_SampleFileType].ToString());
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleLabelUptime) && trainingFile.FieldValues[Field_SampleLabelUptime] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleLabelUptime, trainingFile.FieldValues[Field_SampleLabelUptime].ToString());
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleTokenEndPosition) && trainingFile.FieldValues[Field_SampleTokenEndPosition] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleTokenEndPosition, trainingFile.FieldValues[Field_SampleTokenEndPosition].ToString());
                        }
                        if (trainingFile.FieldValues.ContainsKey(Field_SampleTokenStartPosition) && trainingFile.FieldValues[Field_SampleTokenStartPosition] != null)
                        {
                            templateTrainingFile.Properties.Add(Field_SampleTokenStartPosition, trainingFile.FieldValues[Field_SampleTokenStartPosition].ToString());
                        }
                    }
                }
            }
        }
        private static void MigrateContent_List(ClientContext clientContext, List listToBeReplaced, List newList)
        {
            try
            {
                ListItemCollection sourceListItems = listToBeReplaced.GetItems(CamlQuery.CreateAllItemsQuery());
                FieldCollection sourceListFields = listToBeReplaced.Fields;

                clientContext.Load(sourceListItems, sListItems => sListItems.IncludeWithDefaultProperties(li => li.AttachmentFiles));
                clientContext.Load(sourceListFields);
                clientContext.ExecuteQuery();

                var sourceItemEnumerator = sourceListItems.GetEnumerator();
                while (sourceItemEnumerator.MoveNext())
                {
                    var sourceItem = sourceItemEnumerator.Current;
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem targetItem = newList.AddItem(itemCreateInfo);
                    object sourceModifiedDate = null;
                    object sourceModifiledBy = null;

                    foreach (Field sourceListField in sourceListFields)
                    {
                        try
                        {
                            //[START]Copy all except Attachments,ReadOnlyField,ContentType
                            if (!sourceListField.ReadOnlyField && sourceListField.InternalName != "Attachments" && sourceListField.InternalName != "ContentType" && null != sourceItem[sourceListField.InternalName])
                            {
                                //[START] Calendar and Event List
                                if (listToBeReplaced.BaseTemplate.ToString().Equals("106"))
                                {
                                    if (sourceListField.InternalName.Equals("EndDate"))
                                    {
                                        continue;
                                    }
                                    else if (sourceListField.InternalName.Equals("EventDate"))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem["EndDate"] = sourceItem["EndDate"];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                    else if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                }
                                //[END] Calendar and Event List
                                else
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                }
                            }
                            //[END]Copy all except Attachments, ReadOnlyField, ContentType

                            //Created, Author Field
                            if (sourceItem.FieldValues.Keys.Contains(sourceListField.InternalName))
                            {
                                //Created By
                                if (sourceListField.InternalName.Equals("Author"))
                                {
                                    //newList.Fields.GetByInternalNameOrTitle("Author").ReadOnlyField = false;
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                    }
                                }
                                //Created Date
                                if (sourceListField.InternalName.Equals("Created"))
                                {
                                    //newList.Fields.GetByInternalNameOrTitle("Created").ReadOnlyField = false;
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                    }
                                }

                                //Modified Date
                                if (sourceListField.InternalName.Equals("Modified"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        sourceModifiedDate = sourceItem["Modified"];
                                    }
                                }
                                //Modified By
                                if (sourceListField.InternalName.Equals("Editor"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        sourceModifiledBy = sourceItem["Editor"];
                                    }
                                }
                            }
                            //Created, Author Field
                        }
                        catch (Exception ex)
                        {
                            ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Items", ex.GetType().ToString(), "Not initialized: " + sourceListField.Title);
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List]  Copy Items, Exception Message: " + ex.Message + ", Exception Comment: Not initialized: " + sourceListField.Title);

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("[EXCEPTION] [MigrateContent_List]  Copy Items, Exception Message: " + ex.Message + ", ExceptionComments: Not initialized: " + sourceListField.Title);
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                    }

                    #region Copy Attachments

                    //Copy attachments
                   foreach (Attachment fileName in sourceItem.AttachmentFiles)
                    {
                        try
                        {
                            Microsoft.SharePoint.Client.File oAttachment = clientContext.Web.GetFileByServerRelativeUrl(fileName.ServerRelativeUrl);
                            clientContext.Load(oAttachment);
                            clientContext.ExecuteQuery();

                            FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, oAttachment.ServerRelativeUrl);
                            AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation();

                            Byte[] buffer = new Byte[oAttachment.Length];
                            int bytesRead = fInfo.Stream.Read(buffer, 0, buffer.Length);

                            MemoryStream stream = new MemoryStream(buffer);
                            attachFileInfo.ContentStream = stream;
                            attachFileInfo.FileName = oAttachment.Name;
                            targetItem.AttachmentFiles.Add(attachFileInfo);
                            targetItem.Update();
                            clientContext.ExecuteQuery();
                            stream.Dispose();

                            //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                            targetItem = newList.GetItemById(targetItem.Id);
                            clientContext.Load(targetItem);
                            clientContext.ExecuteQuery();
                            //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                        }
                        catch (Exception ex)
                        {
                            if (!ex.Message.Equals("Version conflict.", StringComparison.CurrentCultureIgnoreCase))
                            {
                                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Attachments", ex.GetType().ToString(), "");
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message);

                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message);
                                Console.ForegroundColor = ConsoleColor.Gray;
                            }
                        }
                    }
                    #endregion

                   //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                   targetItem = newList.GetItemById(targetItem.Id);
                   clientContext.Load(targetItem);
                   clientContext.ExecuteQuery();
                   //[END] [Load "Target Items" After Update, to avoid Version Conflict]

                   targetItem["Modified"] = sourceModifiedDate;
                   targetItem["Editor"] = sourceModifiledBy;
                   targetItem.Update();
                   clientContext.ExecuteQuery();

                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List", ex.GetType().ToString(), "");
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        private static void MigrateContent_Library(ClientContext clientContext, List listToBeReplaced, List newList)
        {
            try
            {
                ListItemCollection items = listToBeReplaced.GetItems(CamlQuery.CreateAllItemsQuery());
                Folder destination = newList.RootFolder;
                Folder source = listToBeReplaced.RootFolder;

                FieldCollection sourceListFields = listToBeReplaced.Fields;
                clientContext.Load(sourceListFields);

                clientContext.Load(destination,
                                    d => d.ServerRelativeUrl);
                clientContext.Load(source,
                                    s => s.Files,
                                    s => s.ServerRelativeUrl);
                clientContext.Load(items,
                                    i => i.IncludeWithDefaultProperties(item => item.File));
                clientContext.ExecuteQuery();

                foreach (Microsoft.SharePoint.Client.File file in source.Files)
                {
                    string newUrl = file.ServerRelativeUrl.Replace(source.ServerRelativeUrl, destination.ServerRelativeUrl);
                    file.CopyTo(newUrl, true);

                    ListItemCollection newListItems = newList.GetItems(CamlQuery.CreateAllItemsQuery());
                    clientContext.Load(destination,
                                    d => d.Files,
                                    d => d.ServerRelativeUrl);
                    clientContext.Load(newListItems,
                                        i => i.IncludeWithDefaultProperties(item => item.File));
                    clientContext.ExecuteQuery();

                    object sourceModifiedDate = null;

                    foreach (ListItem newListItem in newListItems)
                    {
                        if (newListItem.File.Name.Equals(file.Name, StringComparison.CurrentCultureIgnoreCase))
                        {
                            foreach (Field sourceListField in sourceListFields)
                            {
                                if (sourceListField.InternalName.Equals("Modified"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        sourceModifiedDate = file.TimeLastModified;
                                    }
                                }

                                if (sourceListField.InternalName.Equals("Editor"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        newListItem[sourceListField.InternalName] = file.ModifiedBy;
                                        newListItem.Update();
                                        clientContext.Load(newListItem);
                                        clientContext.ExecuteQuery();
                                    }
                                }
                            }
                            newListItem["Modified"] = sourceModifiedDate;
                            newListItem.Update();
                            clientContext.Load(newListItem);
                            clientContext.ExecuteQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_Library", ex.GetType().ToString(), "");
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_Library] Exception Message: " + ex.Message);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION] [MigrateContent_Library] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="docs"></param>
        /// <returns></returns>
        public async Task <IActionResult> Test([FromBody] DocumentModel[] docs)
        {
            if (docs.Length == 0)
            {
                return(new NoContentResult());
            }

            SMB2Client client = new SMB2Client();

            string site     = docs[0].site;
            string url      = _baseurl + "sites/" + site;
            string listname = docs[0].list;
            Guid   listGuid = new Guid(listname);

            using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(url, _username, _password))
                try
                {
                    ///SMBCredential SMBCredential = new SMBCredential(){
                    ///    username = Environment.GetEnvironmentVariable("smb_username"),
                    ///    password = Environment.GetEnvironmentVariable("smb_password"),
                    ///    domain = Environment.GetEnvironmentVariable("domain"),
                    ///    ipaddr = Environment.GetEnvironmentVariable("ipaddr"),
                    ///    share = Environment.GetEnvironmentVariable("share"),
                    ///};
///
                    ///var serverAddress = System.Net.IPAddress.Parse(SMBCredential.ipaddr);
                    ///bool success = client.Connect(serverAddress, SMBTransportType.DirectTCPTransport);
///
                    ///NTStatus nts = client.Login(SMBCredential.domain, SMBCredential.username, SMBCredential.password);
                    ///ISMBFileStore fileStore = client.TreeConnect(SMBCredential.share, out nts);


                    List list = cc.Web.Lists.GetById(listGuid);

                    var fieldcollection = list.Fields;
                    cc.Load(fieldcollection);
                    cc.ExecuteQuery();
                    var cquery = new CamlQuery();
                    cquery.ViewXml = string.Format(@"<View>  
                                <Query> 
                                    <Where>
                                        <Eq><FieldRef Name='Title' />
                                        <Value Type='Text'>{0}</Value></Eq>
                                    </Where> 
                                </Query> 
                            </View>", "dummy.pdf");
                    var listitems = list.GetItems(cquery);
                    cc.Load(listitems);
                    cc.ExecuteQuery();
                    ListItem item = listitems[0];
                    var      clientRuntimeContext = item.Context;
                    string[] SPORDocPropertyNo    =
                    {
                        "4223-7/1",
                        "4223-7/3",
                        "4223-7/4",
                        "4223-7/5"
                    };

                    foreach (var fieldObj in fieldcollection)
                    {
                        if (fieldObj.InternalName.Equals("SPORDocPropertyNo"))
                        {
                            var  taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(fieldObj);
                            Guid _id             = taxKeywordField.TermSetId;

                            List <string> ListTermString = new List <string>();
                            for (int i = 0; i < SPORDocPropertyNo.Length; i++)
                            {
                                string _termID = TermHelper.GetTermIdByName(cc, SPORDocPropertyNo[i], _id);

                                ListTermString.Add(string.Format("-1;#{0}{1}{2}", SPORDocPropertyNo[i], "|", _termID));
                            }
                            string tax = string.Join(";#", ListTermString);
                            Console.WriteLine(tax);


                            taxKeywordField.SetFieldValueByValueCollection(item, new TaxonomyFieldValueCollection(cc, tax, taxKeywordField));
                            taxKeywordField.Update();
                            break;
                        }
                    }
                    item.Update();
                    await cc.ExecuteQueryAsync();
                }
                catch (System.Exception)
                {
                    throw;
                }
            finally
            {
                //client.Logoff();
                //client.Disconnect();
            }

            return(new NoContentResult());
        }
 private ListItemCollection GetDesignCatalogItems(Web web,List designCatalogList)
 {
     CamlQuery query = new CamlQuery();
     query.ViewXml = "<View><OrderBy><FieldRef Name='Name'/></OrderBy></View>";
     ListItemCollection itemCollection = designCatalogList.GetItems(query);
     web.Context.Load(designCatalogList);
     web.Context.Load(itemCollection);
     web.Context.ExecuteQuery();
     return itemCollection;
 }
        protected void BackupButton_Click(object sender, EventArgs e)
        {
            DestSiteName = SiteNameTextBox.Text;

            ClientContext SourceCC      = new ClientContext("https://acuvatehyd.sharepoint.com/teams/FirstSite");
            ClientContext DestinationCC = new ClientContext("https://acuvatehyd.sharepoint.com/teams/" + DestSiteName);

            string UserName = "******";
            string Password = "******";

            SecureString securepwd = new SecureString();


            foreach (char c in Password)
            {
                securepwd.AppendChar(c);
            }



            SourceCC.Credentials      = new SharePointOnlineCredentials(UserName, securepwd);
            DestinationCC.Credentials = new SharePointOnlineCredentials(UserName, securepwd);


            ListCollection listcollection = SourceCC.Web.Lists;         //getting list colectiom

            SourceCC.Load(listcollection);
            List SourceList = listcollection.GetByTitle("newlistforbackup");

            SourceCC.Load(SourceList);
            SourceCC.ExecuteQuery();

            //------creating list in dest



            ListCreationInformation NewList = new ListCreationInformation();

            NewList.Title        = SourceList.Title + "asdfghjkxvzsdf";
            NewList.TemplateType = SourceList.BaseTemplate;
            NewList.Description  = SourceList.Description;
            List Destlist = DestinationCC.Web.Lists.Add(NewList);

            DestinationCC.Load(Destlist.Fields);
            DestinationCC.ExecuteQuery();

            //-----------adding list item

            ListItemCollection listitemcollection = SourceList.GetItems(CamlQuery.CreateAllItemsQuery());

            SourceCC.Load(listitemcollection);
            SourceCC.ExecuteQuery();

            foreach (ListItem li in listitemcollection)
            {
                ListItemCreationInformation NewListItem = new ListItemCreationInformation();
                List     destlistitem = Destlist.ParentWeb.Lists.GetByTitle(NewList.Title);
                ListItem listItem     = Destlist.AddItem(NewListItem);
                listItem["Title"] = li["Title"];
                listItem.Update();
                DestinationCC.ExecuteQuery();
            }
        }
Пример #53
0
        /// <summary>
        /// Used to check if the theme option already exists in the site
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="web"></param>
        /// <param name="themeList"></param>
        /// <returns></returns>
        private bool ContosoThemeEntryExists(ClientContext clientContext, Web web, List themeList)
        {

            CamlQuery query = new CamlQuery();
            query.ViewXml = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>Contoso</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";
            var found = themeList.GetItems(query);
            clientContext.Load(found);
            clientContext.ExecuteQuery();
            if (found.Count > 0)
            {
                return true;
            }
            return false;
        }
Пример #54
0
        private void lbLists_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var sList = Lists.Where(x => x.Title == lbLists.SelectedItem.ToString());
            //Get view
            //Views.Clear();
            List list = clientContext.Web.Lists.GetByTitle(sList.First().Title.ToString());

            //ViewCollection viewColl = list.Views;
            //clientContext.Load(viewColl,
            //    views => views.Include(
            //        view => view.Title,
            //        view => view.Id));
            //clientContext.ExecuteQuery();
            //foreach (SP.View view in viewColl)
            //{

            //    lbViews.Items.Add(view.Title);
            //    Views.Add(new AllView { Name = view.Title, Id = view.Id });
            //}


            SP.List oList     = clientContext.Web.Lists.GetByTitle(sList.First().Title.ToString());
            var     camlQuery = new CamlQuery {
                ViewXml = "<View><RowLimit>100000</RowLimit></View>"
            };
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem,
                               items => items.Include(
                                   item => item.Id,
                                   item => item.DisplayName,
                                   item => item.HasUniqueRoleAssignments));

            clientContext.ExecuteQuery();

            //  MessageBox.Show("In list "+sList.First().Id.ToString()+Environment.NewLine+"Found items: "+ collListItem.Count);

            DialogResult dialogResult = MessageBox.Show("Really delete " + collListItem.Count + " items?", "Deleting items list " + sList.First().Title.ToString(), MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                //Delete items
                CamlQuery q = new CamlQuery();
                q.ViewXml = "<View><RowLimit>10000</RowLimit></View>";
                // We get the results
                SP.ListItemCollection coll = list.GetItems(q);

                clientContext.Load(coll);
                clientContext.ExecuteQuery();


                if (coll.Count > 0)
                {
                    for (int i = coll.Count - 1; i >= 0; i--)
                    {
                        coll[i].DeleteObject();

                        progressBar1.Value = (int)(i / collListItem.Count) * 100;
                        int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
                        progressBar1.Refresh();
                        progressBar1.CreateGraphics().DrawString(percent.ToString() + "%",
                                                                 new Font("Arial", (float)8.25, FontStyle.Regular),
                                                                 Brushes.Black,
                                                                 new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
                    }
                    clientContext.ExecuteQuery();
                }
                MessageBox.Show("Done!");
                progressBar1.Value = 0;
            }
            else if (dialogResult == DialogResult.No)
            {
                //do something else
                DialogResult dialogResult2 = MessageBox.Show("Import rows?", "Import from Excel in list " + sList.First().Title.ToString(), MessageBoxButtons.YesNo);
                if (dialogResult2 == DialogResult.Yes)
                {
                    // Create an instance of the open file dialog box.
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();

                    // Set filter options and filter index.
                    openFileDialog1.Filter      = "Excel File (.xlsx)|*.xlsx";
                    openFileDialog1.FilterIndex = 1;

                    openFileDialog1.Multiselect = false;

                    // Call the ShowDialog method to show the dialog box.
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            var            bookFileNULL = new LinqToExcel.ExcelQueryFactory(openFileDialog1.FileName);
                            List <AllItem> PoliciesNULL =
                                (from row in bookFileNULL.Worksheet("Table1")
                                 let item = new AllItem
                            {
                                Name = row["Title"].Cast <string>()
                            }
                                 // where item.Supplier == "Walmart"
                                 select item).ToList();

                            MessageBox.Show("Found items for import: " + PoliciesNULL.Count());
                            //Add items
                            int i = 0;
                            foreach (AllItem pol in PoliciesNULL)
                            {
                                i++;
                                AddItems(sList.First().Title.ToString(), Views.First().Id.ToString(), pol);

                                progressBar1.Value = (int)(i / PoliciesNULL.Count) * 100;
                                int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
                                progressBar1.Refresh();
                                progressBar1.CreateGraphics().DrawString(percent.ToString() + "%",
                                                                         new Font("Arial", (float)8.25, FontStyle.Regular),
                                                                         Brushes.Black,
                                                                         new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
                            }
                            MessageBox.Show("Done!");
                            progressBar1.Value = 0;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                        }
                    }
                }
                else if (dialogResult2 == DialogResult.No)
                {
                    //do something else
                }
            }
        }
 public ListItemCollection GetListItems(List list)
 {
     var camlQuery = new CamlQuery();
     camlQuery.ViewXml = "<View Scope='RecursiveAll'></View>";
     var listItemCol = list.GetItems(camlQuery);
     ctx.Load(list, l => l.Title);
     ctx.Load(listItemCol, item => item.Count);
     ctx.ExecuteQuery();
     return listItemCol;
 }
Пример #56
0
        public ActionResult Index()
        {
            User spUser = null;

            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    spUser = clientContext.Web.CurrentUser;
                    clientContext.Load(spUser, user => user.Title);

                    Web myWeb = clientContext.Web;
                    clientContext.Load(myWeb);

                    List myList = myWeb.Lists.GetByTitle("Uppgift2Lista");
                    clientContext.Load(myList);

                    var webListsTitles = myWeb.Lists;
                    clientContext.Load(webListsTitles);

                    CamlQuery          query = CamlQuery.CreateAllItemsQuery(100);
                    ListItemCollection items = myList.GetItems(query);
                    clientContext.Load(items);

                    int counter  = 0;
                    int counter2 = 0;
                    int counter3 = 0;

                    List <string> Titles = new List <string>();

                    List <string> WebTitles = new List <string>();


                    clientContext.ExecuteQuery();

                    foreach (var lists in webListsTitles)
                    {
                        WebTitles.Add(lists.Title);
                    }

                    foreach (var item in items)
                    {
                        if (item["Status"].ToString() == "Started" && item["Priority"].ToString() == "Hög")
                        {
                            Titles.Add(item["Title"].ToString());
                        }
                        if (item["Priority"].ToString() == "Hög" && item["Status"].ToString() == "Created")
                        {
                            counter++;
                        }
                        if (item["Priority"].ToString() == "Medel" || item["Priority"].ToString() == "Låg" &&
                            (item["Status"].ToString() == "Created" || item["Status"].ToString() == "Started"))
                        {
                            counter2++;
                        }
                        if (item["Priority"].ToString() != "Hög" && item["Status"].ToString() != "Finished")
                        {
                            counter3++;
                        }
                    }

                    ViewBag.UserName = spUser.Title;

                    ViewBag.WebTitle = myWeb.Title;

                    ViewBag.MyList = myList.Title;

                    ViewBag.ItemTitle = Titles;

                    ViewBag.ListTitles = WebTitles;

                    ViewBag.Counter = counter;

                    ViewBag.Counter2 = counter2;
                    ViewBag.Counter3 = counter3;
                }
            }

            return(View());
        }
Пример #57
0
        public void RenameFolder(string siteUrl, string listName, string relativePath, string folderName, string folderNewName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web  web  = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);

                //  string FolderFullPath = GetFullPath(listName, relativePath, folderName);

                CamlQuery query = new CamlQuery();
                query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                                "<Query>" +
                                "<Where>" +
                                "<And>" +
                                "<Eq>" +
                                "<FieldRef Name=\"FSObjType\" />" +
                                "<Value Type=\"Integer\">1</Value>" +
                                "</Eq>" +
                                "<Eq>" +
                                "<FieldRef Name=\"Title\"/>" +
                                "<Value Type=\"Text\">" + folderName + "</Value>" +
                                "</Eq>" +
                                "</And>" +
                                "</Where>" +
                                "</Query>" +
                                "</View>";

                /* if (relativePath.Equals(string.Empty))
                 * {
                 *   query.FolderServerRelativeUrl = "/lists/" + listName;
                 * }
                 * else
                 * {
                 *   query.FolderServerRelativeUrl = "/lists/" + listName + "/" + relativePath;
                 * }*/

                //query.FolderServerRelativeUrl = "/"+listName;

                var folders = list.GetItems(query);

                clientContext.Load(list);
                clientContext.Load(list.Fields);
                clientContext.Load(folders, fs => fs.Include(fi => fi["Title"],
                                                             fi => fi["DisplayName"],
                                                             fi => fi["FileLeafRef"]));
                // clientContext.ExecuteQuery();

                clientContext.ExecuteQueryAsync((s, ee) =>
                {
                    if (folders.Count == 1)
                    {
                        folders[0]["Title"]       = folderNewName;
                        folders[0]["FileLeafRef"] = folderNewName;
                        folders[0].Update();
                        clientContext.ExecuteQueryAsync((ss, eee) =>
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("Success", "Success", MessageBoxButton.OK);
                            });
                        },
                                                        (ss, eee) =>
                        {
                            Console.WriteLine(eee.Message);
                        });
                    }
                },
                                                (s, ee) =>
                {
                    Console.WriteLine(ee.Message);
                });
            }
        }
Пример #58
0
        /// <summary>
        /// Updating Previous Documents Recursively using CAML Query
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="list">List of Matters</param>
        /// <param name="practiceGroupMetadataDefaultValue">Default Value to be Set for practice group</param>
        /// <param name="areaOfLawMetadataDefaultValue">Default Value to be Set for Area of Law</param>
        /// <param name="subAreaOfLawMetadataDefaultValue">default Value to be Set for Sub Area of Law</param>
        /// <param name="clientName">Current Client name</param>
        public static void UpdatePreviousDocuments(ClientContext clientContext, List list, string practiceGroupMetadataDefaultValue, string areaOfLawMetadataDefaultValue, string subAreaOfLawMetadataDefaultValue, string clientName)
        {
            try
            {
                Web site = clientContext.Web;
                User currentUser = site.CurrentUser;
                clientContext.Load(currentUser);
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.ProcessingMessageDocuments, list.Title));
                CamlQuery CAMLQuery = new CamlQuery();
                CAMLQuery.ViewXml = string.Format(CultureInfo.InvariantCulture, Constants.CAMLQueryRetrieveAllDocuments, practiceGroupFieldName, areaOfLawFieldName, subAreaOfLawFiedName);;
                ListItemCollection listItems = list.GetItems(CAMLQuery);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
                foreach (ListItem item in listItems)
                {
                    bool checkoutByCurrent = false;
                    if (null != item[Constants.CheckOutFieldKey])
                    {
                        string checkOutUser = ((Microsoft.SharePoint.Client.FieldLookupValue)(item[Constants.CheckOutFieldKey])).LookupValue;

                        if (currentUser.Title == checkOutUser)
                        {
                            checkoutByCurrent = true;
                        }
                        else
                        {
                            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.FailureMessageUpdationDocument, item[Constants.DocNameFieldKey], checkOutUser));
                        }
                    }
                    if (null == item[Constants.CheckOutFieldKey] || checkoutByCurrent)// Checkout Functionality
                    {
                        TaxonomyFieldValueCollection practicegroupTaxanomyColl = item[practiceGroupFieldName] as TaxonomyFieldValueCollection;
                        if (0 >= practicegroupTaxanomyColl.Count)
                        {
                            item[practiceGroupFieldName] = practiceGroupMetadataDefaultValue;
                            item.Update();
                        }
                        TaxonomyFieldValueCollection areaOfLawTaxanomyColl = item[areaOfLawFieldName] as TaxonomyFieldValueCollection;
                        if (0 >= areaOfLawTaxanomyColl.Count)
                        {
                            item[areaOfLawFieldName] = areaOfLawMetadataDefaultValue;
                            item.Update();
                        }
                        TaxonomyFieldValueCollection subAreaOfLawTaxanomyColl = item[subAreaOfLawFiedName] as TaxonomyFieldValueCollection;
                        if (0 >= subAreaOfLawTaxanomyColl.Count)
                        {
                            item[subAreaOfLawFiedName] = subAreaOfLawMetadataDefaultValue;
                            item.Update();
                        }
                        clientContext.ExecuteQuery();
                        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.SucessMessageUpdationDocument, item[Constants.DocNameFieldKey]));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.FailureMessageDocument, clientName, list.Title, e.Message));
            }
        }
 /// <summary>
 /// Create a Web Part page of matter in its document library
 /// </summary>
 /// <param name="sitePageLib">SharePoint List of matter library</param>
 /// <param name="clientContext">SharePoint Client Context</param>
 /// <param name="objFileInfo">Object of FileCreationInformation</param>
 /// <param name="matter">Matter object containing Matter data</param>
 /// <param name="web">Web object containing Web data</param>
 /// <returns>true if success else false</returns>
 internal static string CreateWebPartPage(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Matter matter, Web web)
 {
     string response = string.Empty;
     //// Find Default Layout from Master Page Gallery to create Web Part Page
     sitePageLib = web.Lists.GetByTitle(Constants.MasterPageGallery);
     clientContext.Load(sitePageLib);
     clientContext.ExecuteQuery();
     CamlQuery camlQuery = new CamlQuery();
     camlQuery.ViewXml = Constants.DMSRoleQuery;
     ListItemCollection collection = sitePageLib.GetItems(camlQuery);
     clientContext.Load(
        collection,
             items => items.Include(
             item => item.DisplayName,
             item => item.Id));
     clientContext.ExecuteQuery();
     response = WebPartsCreation(sitePageLib, clientContext, objFileInfo, matter, web, collection);
     return response;
 }
Пример #60
0
        public void DeleteFolder(string siteUrl, string listName, string relativePath, string folderName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web  web  = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);

                CamlQuery query = new CamlQuery();
                query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                                "<Query>" +
                                "<Where>" +
                                "<And>" +
                                "<Eq>" +
                                "<FieldRef Name=\"FSObjType\" />" +
                                "<Value Type=\"Integer\">1</Value>" +
                                "</Eq>" +
                                "<Eq>" +
                                "<FieldRef Name=\"Title\"/>" +
                                "<Value Type=\"Text\">" + folderName + "</Value>" +
                                "</Eq>" +
                                "</And>" +
                                "</Where>" +
                                "</Query>" +
                                "</View>";

                /*if (relativePath.Equals(string.Empty))
                 * {
                 *  query.FolderServerRelativeUrl = "/lists/" + listName;
                 * }
                 * else
                 * {
                 *  query.FolderServerRelativeUrl = "/lists/" + listName + "/" + relativePath;
                 * }*/

                var folders = list.GetItems(query);

                clientContext.Load(list);
                clientContext.Load(folders);

                clientContext.ExecuteQueryAsync((s, ee) =>
                {
                    if (folders.Count == 1)
                    {
                        folders[0].DeleteObject();
                        clientContext.ExecuteQueryAsync((ss, eee) =>
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("Deleted Folder", "Deleted", MessageBoxButton.OK);
                                selectedFiles.Clear();

                                RemoveButton.IsEnabled = false;
                            });
                        },
                                                        (ss, eee) =>
                        {
                            Console.WriteLine(eee.Message);
                        });
                    }


                    Dispatcher.BeginInvoke(() =>
                    {
                    });
                },
                                                (s, ee) =>
                {
                    Console.WriteLine(ee.Message);
                });
            }
        }