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();

        }
        public static FieldLookupValue GetLookupFieldValue(string lookupName, string lookupListName, ClientContext clientContext)
        {
            //Ref: Karine Bosch - https://karinebosch.wordpress.com/2015/05/11/setting-the-value-of-a-lookup-field-using-csom/
            var lookupList = clientContext.Web.Lists.GetByTitle(lookupListName);
            CamlQuery query = new CamlQuery();
            string lookupFieldName = ConfigurationManager.AppSettings["LookupFieldName"].ToString();
            string lookupFieldType = ConfigurationManager.AppSettings["LookupFieldType"].ToString();

            query.ViewXml = string.Format(@"<View><Query><Where><Eq><FieldRef Name='{0}'/><Value Type='{1}'>{2}</Value></Eq>" +
                                            "</Where></Query></View>", lookupFieldName, lookupFieldType, lookupName);

            ListItemCollection listItems = lookupList.GetItems(query);
            clientContext.Load(listItems, items => items.Include
                                                (listItem => listItem["ID"],
                                                listItem => listItem[lookupFieldName]));
            clientContext.ExecuteQuery();

            if (listItems != null)
            {
                ListItem item = listItems[0];
                FieldLookupValue lookupValue = new FieldLookupValue();
                lookupValue.LookupId = int.Parse(item["ID"].ToString());
                return lookupValue;
            }

            return null;
        }
Example #3
1
        public ActionResult Featured(int maxCount = 5) {
            using (var clientContext = HttpContext.GetUserClientContextForSPHost()) {
                ViewBag.SPHostUrl = HttpContext.Request.QueryString["SPHostUrl"];

                var caml = new CamlQuery() {
                    ViewXml = CAML.ViewQuery(
                        CAML.Where(
                            CAML.And(
                                CAML.Geq(
                                    CAML.FieldValue(Event.FIELD_DATE, "Date", CAML.Today())
                                ),
                                CAML.Eq(
                                    CAML.FieldValue(Event.FIELD_CATEGORY, "Text", "Featured")
                                )
                            )
                        ),
                        CAML.OrderBy(new OrderByField(Event.FIELD_DATE)))
                };

                var list = clientContext.Web.Lists.GetByTitle(ListDetails.EventsListName);
                clientContext.Load(list);
                clientContext.ExecuteQuery();

                var items = list.GetItems(caml);
                clientContext.Load(items);
                clientContext.ExecuteQuery();

                var result = items.Cast<ListItem>()
                                  .Select(i => new Event(i)).ToList();
                return View(result);
            }
        } 
Example #4
0
        private void button1_Click(object sender, EventArgs e)
        {

            string siteUrl = "https://hp-27b0ee14ded081.sharepoint.com/teams/spohub/ACSMigrationManager/";

            ClientContext clientContext = new ClientContext(siteUrl);
            System.Security.SecureString pwd = new System.Security.SecureString();
            pwd.AppendChar('p');
            pwd.AppendChar('a');
            pwd.AppendChar('s');
            pwd.AppendChar('s');
            pwd.AppendChar('@');
            pwd.AppendChar('w');
            pwd.AppendChar('o');
            pwd.AppendChar('r');
            pwd.AppendChar('d');
            pwd.AppendChar('1');
            clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", pwd);
            Web site = clientContext.Web;
            clientContext.Load(site);
            clientContext.ExecuteQuery();

            SP.List oList = clientContext.Web.Lists.GetByTitle("Migration Tasks");
            CamlQuery query;
            string sitesText = "" + textBox1.Text;
            sitesText = sitesText.Replace("\r", "");
            sitesText = sitesText.Replace("\n", ",");
            string[] sites = null;
            if (sitesText.Length > 0)
            {
                sites = sitesText.Split(',');

                for (int i = 0; i < sites.Length; i++)
                {
                    if (sites[i].Trim().Length > 0)
                    {
                        query = new CamlQuery();
                        query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='ContentSource'/><Value Type='Text'>" +
                            sites[i] + "</Value></Contains></Where></Query></View>";
                        ListItemCollection collListItem = oList.GetItems(query);

                        clientContext.Load(collListItem);
                        clientContext.ExecuteQuery();



                        if (collListItem.Count == 1)
                        {
                            ListItem oListItem = collListItem[0];
                            //listBox1.DataSource = collListItem;
                            textBox3.Text += oListItem["Title"].ToString() + @"
";
                            oListItem["MigrationStatus"] = textBox2.Text;
                            oListItem.Update();
                            clientContext.ExecuteQuery();
                        }
                    }
                }
            }
        }
		internal static Customer GetCustomer (this ClientContext ctx, int id) {
			if (ctx.Web.ListExists("Customer") && ctx.Web.ListExists("Order")) {
				//get Customer
				var customers = ctx.Web.Lists.GetByTitle("Customer");
				var cQuery = new CamlQuery();
				cQuery.ViewXml = $@"<View><Query><Where><Eq>
					<FieldRef Name='ID' /><Value Type='Counter'>{id}</Value>
				</Eq></Where></Query></View>";
				var customer = customers.GetItems(cQuery);

				//Get Orders
				var orders = ctx.Web.Lists.GetByTitle("Order");
				var oQuery = new CamlQuery();
				oQuery.ViewXml = $@"<View><Query><Where><Eq>
					<FieldRef Name='Customer' LookupId='TRUE'/><Value Type='Lookup'>{id}</Value>
				</Eq></Where></Query></View>";
				var customerOrders = orders.GetItems(oQuery);

				//Loading
				ctx.Load(customer);
				ctx.Load(customerOrders);

				ctx.ExecuteQuery();
				var ret = customer[0].ParseCustomer();
				ret.Orders = customerOrders.ParseOrders();
				return ret; 
			}
			return null;

		}
        /// <summary>
        /// Returns the last used site collection number
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <returns>last used site collection number</returns>
        public int GetLastSiteCollectionNumber(ClientContext cc, Web web, string siteDirectoryHost, string listName)
        {
            int lastNumber = 0;

            List listToInsertQuery = web.Lists.GetByTitle(listName);

            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View>"
               + "<Query>"
               + String.Format("<Where><Eq><FieldRef Name='CreateYear' /><Value Type='Int'>{0}</Value></Eq></Where>", DateTime.Now.ToString("yyyy"))
               + "<OrderBy><FieldRef Name='CreateSeq' Ascending='FALSE'/></OrderBy>"
               + "</Query>"
               + "<RowLimit>1</RowLimit>"
               + "</View>";
            // execute the query
            ListItemCollection listItems = listToInsertQuery.GetItems(query);
            cc.Load(listItems);
            cc.ExecuteQuery();

            if (listItems.Count == 1)
            {
                int.TryParse(listItems[0]["CreateSeq"].ToString(), out lastNumber);
            }

            return lastNumber;
        }
Example #7
0
        static void Main(string[] args)
        {
            using (var context = new ClientContext(Constants.URL))
            {
                context.Credentials = new SharePointOnlineCredentials(Constants.User, GetPassSecure(Constants.Pass));
                // Assume that the web has a list named "Announcements".
                List twitterList = context.Web.Lists.GetByTitle(Constants.ListTwitter);

                var query= new CamlQuery{
                    ViewXml = @"<View>
                                <Query>
                               <Where><IsNull><FieldRef Name='Sexo' /></IsNull>
                                </Where>
                                </Query>
                                <RowLimit>1</RowLimit>
                                </View>"
                };

               var collection= twitterList.GetItems(query);
                context.Load(collection);
                context.ExecuteQuery();

                foreach(var item in collection)
                {
                   Function.DetecFacesAndDisplayResult(item["Foto"].ToString(),item.Id.ToString());

                }

                Console.ReadLine();
                Console.WriteLine("Actualizado");

            }
        }
Example #8
0
        public ActionResult Index(string category = "") {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = HttpContext.GetUserClientContextForSPHost()) {
                ViewBag.SPHostUrl = spContext.SPHostUrl;
                ViewBag.Category = category;

                var list = clientContext.Web.GetListByTitle(ListDetails.EventsListName);
                var categoryQuery = string.Empty;
                if (!string.IsNullOrEmpty(category)) {
                    categoryQuery = CAML.Where(CAML.Eq(CAML.FieldValue(Event.FIELD_CATEGORY, "Text", category)));
                }
                var orderByQuery = CAML.OrderBy(new OrderByField("Title"));

                var caml = new CamlQuery() {
                    ViewXml = CAML.ViewQuery(categoryQuery, orderByQuery, rowLimit: 50)
                };
                var events = list.GetItems(caml);
                clientContext.Load(events);
                clientContext.ExecuteQuery();

                var eventsList = events.Cast<ListItem>().Select(item => new Event(item)).ToList();
                return View(eventsList);
            }
        } 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SPQuery qry = new SPQuery();
            SPWeb rootWeb = Site.RootWeb;
            SPList list = rootWeb.Lists["Articles"];
            CamlQuery caml = new CamlQuery();
            SPQuery articleQuery = new SPQuery();
            articleQuery.Query = CAML.Where(
                                CAML.Contains(
                                    CAML.FieldRef("Title"),
                                    CAML.Value(txtTitleSearch.Text)));

            //articleQuery.ViewFields = CAML.ViewFields(CAML.FieldRef("Title"), CAML.FieldRef("Modified By"));
            //articleQuery.ViewFields = string.Concat(
            //                    "<FieldRef Name='Title' />",
            //                   "<FieldRef Name='Modified' />");

            //articleQuery.ViewFieldsOnly = true;
            //articleQuery.ViewFields = "<ViewFields><FieldRef Name=\"Title\"/></ViewFields>";

            SPListItemCollection col;

            if (txtTitleSearch.Text.Length == 0)
            {
                col = list.Items;
            }
            else
            {
                col = list.GetItems(articleQuery);
            }

            ViewState["AtricleSearchResults"] = col.GetDataTable();
            gvResult.DataSource = col.GetDataTable();
            gvResult.DataBind();
        }
Example #10
0
        private void ConnectStore(int listitemid, int groupid) {
            List listConnect = _ctx.Web.Lists.GetByTitle("Grupper för försäljningsställen");
            CamlQuery cq = new CamlQuery();

            cq.ViewXml = @"<View>  
        <Query> 
            <Where><Eq><FieldRef Name='F_x00f6_rs_x00e4_ljningsst_x00e4' LookupId='True' /><Value Type='Lookup'>" + listitemid.ToString() + @"</Value></Eq></Where> 
        </Query> 
    </View>";
            ListItemCollection items = listConnect.GetItems(cq);
            _ctx.Load(items);
            _ctx.ExecuteQuery();
            if (items.Count == 0) {
                ListItem item = listConnect.AddItem(new ListItemCreationInformation { });
                item["F_x00f6_rs_x00e4_ljningsst_x00e4"] = listitemid;
                item["Grupp"] = groupid;
                item.Update();
            }
            else {
                foreach (ListItem item in items) {
                    item["Grupp"] = groupid;
                    item.Update();
                }
            }

        }
Example #11
0
        static void Main(string[] args)
        {
            Uri siteUri = new Uri(ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]);

            //Get the realm for the URL
            string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);

            //Get the access token for the URL.
            //   Requires this app to be registered with the tenant
            string accessToken = TokenHelper.GetAppOnlyAccessToken(
                TokenHelper.SharePointPrincipal,
                siteUri.Authority, realm).AccessToken;

            //Get client context with access token
            using (var ctx =
                TokenHelper.GetClientContextWithAccessToken(
                    siteUri.ToString(), accessToken))
            {
                // Get items which are in requested status
                List list = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SiteCollectionRequests_List"]);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Status'/>" +
                                    "<Value Type='Text'>Requested</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>";
                ListItemCollection listItems = list.GetItems(camlQuery);
                ctx.Load(listItems);
                ctx.ExecuteQuery();

                foreach (ListItem item in listItems)
                {
                    // get item one more time and check that it's still in requested status
                    ListItem listItem = list.GetItemById(item.Id);
                    ctx.Load(listItem);
                    ctx.ExecuteQuery();

                    if (listItem["Status"].ToString().ToLowerInvariant() == "Requested".ToLowerInvariant())
                    {
                        try
                        {
                            // Mark it as provisioning
                            UpdateStatusToList(ctx, listItem.Id, "Provisioning", "Started provisioning at " + DateTime.Now.ToString());

                            // Process request
                            string newUrl = ProcessSiteCreationRequest(ctx, listItem);

                            // Mark it as provisioning
                            UpdateStatusToList(ctx, listItem.Id, "Ready", "Created at " + DateTime.Now.ToString());

                            // Send email
                            SendEmailToRequestorAndNotifiedEmail(ctx, listItem, newUrl);

                        }
                        catch (Exception ex)
                        {
                            // Store the exception information to the list for viewing from browser
                            UpdateStatusToList(ctx, listItem.Id, "Failed", ex.Message);
                        }
                    }
                }
            }
        }
        public IEnumerable<Person> GetAll()
        {
            var spContext = SharePointContext.GetClientContext();

            var spList = spContext.Web.Lists.GetByTitle("Person");
            spContext.Load(spList);
            spContext.ExecuteQuery();
            if (spList == null || spList.ItemCount <= 0) return null;
            var camlQuery = new CamlQuery
            {
                ViewXml = @"<View>
                                <RowLimit>20</RowLimit>
                             </View>",
                DatesInUtc = true
            };
            var listItems = spList.GetItems(camlQuery);
            spContext.Load(listItems);
            spContext.ExecuteQuery();
            var resultItems = new List<Person>();

            foreach (var item in listItems)
            {
                var personItem = new Person
                {
                    Id = item.Id,
                    Name = item["Name"].ToString(),
                    LastName = item["LastName"].ToString()
                };
                resultItems.Add(personItem);
            }

            return resultItems;
        }
Example #13
0
 static void Main(string[] args)
 {
     ClientContext context = new ClientContext("http://sp.weiyun.com/sites/Doc");
     context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
     FormsAuthenticationLoginInfo formsAuthinfo = new FormsAuthenticationLoginInfo("DEL00001", "1234!qwer");
     context.FormsAuthenticationLoginInfo = formsAuthinfo;
     //context.Credentials = new NetworkCredential("DEL00001", "1234!qwer");
     Web web = context.Web;
     List list = web.Lists.GetByTitle("DocLib");
     CamlQuery camlQuery = new CamlQuery();
     camlQuery.ViewXml =
         @"<View>
             <Query>
                 <Where>
                     <Eq>
                         <FieldRef Name = 'Title' />
                         <Value Type='Text'>71342245-c3c8-4094-a555-842a6763b201_081464afff6f457eac23e2168c82a974</Value>
                     </Eq>
                 </Where>
             </Query>
         </View>";
     ListItemCollection items = list.GetItems(camlQuery);
     //context.Load(web,w=>w.Title,w=>w.Description);
     context.Load(items, s => s.Include(item => item["Title"]));
     //context.LoadQuery
     context.ExecuteQuery();
     //string Title = web.Title;
    //Console.WriteLine(string.Format("Web Title is {0}, Descript is {1}!",Title,web.Description));
     int i = items.Count;
     foreach (ListItem item in items)
     {
         Console.WriteLine("Title:{0}",item["Title"]);
     }
 }
Example #14
0
        public IEnumerable<Item> GetItems()
        {
            using (var clientContext = WebAPIHelper.GetClientContext(ControllerContext))
            { 
                if (clientContext != null)
                {
                    List demoList = clientContext.Web.Lists.GetByTitle("WebAPIDemo");
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = "<View><Query></Query></View>";
                    ListItemCollection demoItems = demoList.GetItems(camlQuery);
                    clientContext.Load(demoItems);
                    clientContext.ExecuteQuery();  
                    
                    Item[] items = new Item[demoItems.Count];

                    int i=0;
                    foreach (ListItem item in demoItems)
                    {
                        items[i] = new Item() { Id = item.Id, Title = item["Title"].ToString() };
                        i++;
                    }

                    return items;
                }
                else
                {
                    return new Item[0];
                }
            }
        }
        public Publications Get(int id)
        {
            var list = context.Web.Lists.GetByTitle(Title);
            var query = new CamlQuery() { ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + id + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>" };
            var items = list.GetItems(query);
            context.Load(items);
            context.ExecuteQuery();

            if (items.Count > 0)
            {
                string[] lines = items[0]["_x0422__x044d__x0433__x0438_"].ToString().Split(',');

                var tags = new List<Tag>();

                foreach (var line in lines)
                {
                    tags.Add(mapTag(line));
                }

                return new Publications()
                {
                    Title = items[0]["Title"].ToString(),
                    Article = items[0]["_x0421__x0442__x0430__x0442__x04"].ToString(),
                    PublicationDate = ((DateTime)items[0]["_x0414__x0430__x0442__x0430__x00"]).AddDays(1),
                    Source = items[0]["_x0418__x0441__x0442__x043e__x04"].ToString(),
                    Subtitle = items[0]["_x041f__x043e__x0434__x0437__x04"].ToString(),
                    Tags = tags
                };
            }
            else
            {
                return null;
            }
        }
Example #16
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;
        }
Example #17
0
        public void UpdateSuppliers(string country, string[] supplierNames)
        {
            string camlStringFormat = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Country' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                        </Query>
                </View>";
            CamlQuery query = new CamlQuery();
            query.ViewXml = string.Format(camlStringFormat, country);

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

            if (items.Count > 0)
            {
                var item = items[0];
                string commaSeparatedList = String.Join(",", supplierNames);
                item["Suppliers"] = commaSeparatedList;
                item.Update();
                clientContext.ExecuteQuery();
            }
        }
        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;
        }
        public override int Perform(OptionSet optionSet)
        {
            using (var clientContext = new ClientContext(site))
            {
                var list = clientContext.Web.Lists.GetByTitle(listName);

                var camlQuery = new CamlQuery
                                    {
                                        ViewXml =
                                            string.Format("<View><Query><Where><Eq><FieldRef Name='PackageVersion'/>" +
                                                          "<Value Type='Text'>{0}</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>",
                                                          version)
                                    };
                var items = list.GetItems(camlQuery);
                clientContext.Load(items);
                clientContext.ExecuteQuery();

                if (items.Count == 0)
                {
                    throw new InvalidOperationException("No such version: "+version);
                }
                if (items.Count > 1)
                {
                    throw new InvalidOperationException("Ambiguous version: " + version);
                }
                var item = items[0];
                item["PackageState"] = state;
                item.Update();
                clientContext.ExecuteQuery();
            }
            return 0;
        }
        public static List<Product> GetProducts(SharePointContext spContext, CamlQuery camlQuery)
        {
            List<Product> products = new List<Product>();

            using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
            {
                if (clientContext != null)
                {
                    List lstProducts = clientContext.Web.Lists.GetByTitle("Products");

                    ListItemCollection lstProductItems = lstProducts.GetItems(camlQuery);

                    clientContext.Load(lstProductItems);

                    clientContext.ExecuteQuery();

                    if (lstProductItems != null)
                    {
                        foreach (var lstProductItem in lstProductItems)
                        {
                            products.Add(
                                new Product
                                {
                                    Id = lstProductItem.Id,
                                    Title = lstProductItem["Title"].ToString(),
                                    Description = lstProductItem["ProductDescription"].ToString(),
                                    Price = lstProductItem["Price"].ToString()
                                });
                        }
                    }
                }
            }

            return products;
        }
        public DCTFolder DCMGetFolderByUri(string uri)
        {
            using (DocLibContext clientContext = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(uri);
                clientContext.Load(folder);

                CamlQuery query = new CamlQuery();
                query.ViewXml = Caml.SimpleView(Caml.Field("FileRef").Eq(Caml.Value("Text", uri)), CamlBuilder.ViewType.RecursiveAll).ToCamlString();

                ListItemCollection items = clientContext.BaseList.GetItems(query);

                clientContext.Load(items);

                DCTFolder result;
                try
                {
                    clientContext.ExecuteQuery();
                    if (string.Compare(folder.ServerRelativeUrl, this.DCMGetRootFolder().Uri, true) == 0)
                        result = new DCTFolder() { ID = 0, IsRootFolder = true };
                    else
                        result = new DCTFolder() { ID = items[0].Id, IsRootFolder = false };

                    DCTConverterHelper.Convert(folder, result);
                }
                catch
                {

                    result = null;
                }

                return result;
            }
        }
Example #22
0
        static void GetSPList(string URL, string userName, string password, string domain)
        {
            Console.WriteLine("started to get List from Sharepoint...");
            try
            {
                clientContext = new ClientContext(URL);
                webClient = new WebClient();
                System.Net.NetworkCredential nck = new System.Net.NetworkCredential(userName, password, domain);
                clientContext.Credentials = nck;
                webClient.Credentials = nck;
                List phase3 = clientContext.Web.Lists.GetByTitle("Phase 3 SSO App Status");
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"
                <View/>
                ";
                listItems = phase3.GetItems(camlQuery);

                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fail" + ex.Message);
            }
            Console.WriteLine("Done!");
        }
Example #23
0
        public static ListItemCollection GetItemsFromListName(string listName)
        {
            ListItemCollection items = null;
            var spContext = SharePointContextProvider.Current.GetSharePointContext(CurrentHttpContext);
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    List list = clientContext.Web.Lists.GetByTitle(listName);
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"
                                        <View>
                                            <Query>
                                                <Where>
                                                    <IsNotNull>
                                                        <FieldRef Name='Title' />
                                                    </IsNotNull>
                                                </Where>
                                            </Query>
                                        </View>";
                    items = list.GetItems(camlQuery);

                    clientContext.Load(items);
                    clientContext.ExecuteQuery();
                }
            }
            return items;
        }
Example #24
0
        public void SetThemeBasedOnName(ClientContext ctx, Web web, Web rootWeb, string themeName)
        {
            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);
            ctx.Load(themeList);
            ctx.ExecuteQuery();

            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);
            ctx.Load(found);
            ctx.ExecuteQuery();
            if (found.Count > 0)
            {
                Microsoft.SharePoint.Client.ListItem themeEntry = found[0];
                //Set the properties for applying custom theme which was jus uplaoded
                string spColorURL = null;
                if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                {
                    spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                }
                string spFontURL = null;
                if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                {
                    spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                }
                string backGroundImage = null;
                if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                {
                    backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                }

                // Set theme for demonstration
                web.ApplyTheme(spColorURL,
                                    spFontURL,
                                    backGroundImage,
                                    false);

                // Let's also update master page, if needed
                if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                {
                    web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url); ;
                }

                ctx.ExecuteQuery();
            }
        }
		public BaseCollection<DCTFile> DCMQueryDocByField(BaseCollection<DCTFileField> fields)
		{
			BaseCollection<DCTFile> files = new BaseCollection<DCTFile>();
			using (DocLibContext clientContext = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
			{
				CamlQuery query = new CamlQuery();
				CamlExpression caml = null;
				foreach (DCTFileField item in fields)
				{
					string valueText = string.Empty;
					switch (item.Field.ValueType)
					{
						case DCTFieldType.Boolean:
							break;
						case DCTFieldType.DateTime:
							break;
						case DCTFieldType.Decimal:
							break;
						case DCTFieldType.Integer:
							valueText = "Counter";
							break;
						case DCTFieldType.Note:
							break;
						case DCTFieldType.Text:
							valueText = "Text";
							break;
						case DCTFieldType.User:
							break;
						default:
							break;
					}
					if (caml == null)
					{
						caml = Caml.Field(item.Field.InternalName).Eq(Caml.Value(valueText, item.FieldValue));
					}
					else
					{
						caml = caml.And(Caml.Field(item.Field.InternalName).Eq(Caml.Value(valueText, item.FieldValue)));
					}
				}

				query.ViewXml = Caml.SimpleView(caml, CamlBuilder.ViewType.RecursiveAll).ToCamlString();

				ListItemCollection items = clientContext.BaseList.GetItems(query);
				clientContext.Load(items);

				clientContext.ExecuteQuery();

				foreach (ListItem item in items)
				{
					DCTFile file = new DCTFile();
					DCTConverterHelper.Convert(item, file);
					files.Add(file);
				}
			}
			return files;
		}
Example #26
0
        protected override void ExecuteCmdlet()
        {
            var list = this.SelectedWeb.GetList(List);

            if (Id != -1)
            {
                var listItem = list.GetItemById(Id);
                if (Fields != null)
                {
                    foreach (var field in Fields)
                    {
                        ClientContext.Load(listItem, l => l[field]);
                    }
                }
                else
                {
                    ClientContext.Load(listItem);
                }
                ClientContext.ExecuteQuery();
                WriteObject(listItem);
            }
            else if (UniqueId != null && UniqueId.Id != Guid.Empty)
            {
                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><Query><Where><Eq><FieldRef Name='GUID'/><Value Type='Guid'>{0}</Value></Eq></Where></Query>{1}</View>", UniqueId.Id, viewFieldsStringBuilder);
                var listItem = list.GetItems(query);
                ClientContext.Load(listItem);
                ClientContext.ExecuteQuery();
                WriteObject(listItem);
            }
            else if (Query != null)
            {
                CamlQuery query = new CamlQuery();
                query.ViewXml = Query;
                var listItems = list.GetItems(query);
                ClientContext.Load(listItems);
                ClientContext.ExecuteQuery();
                WriteObject(listItems, true);
            }
            else
            {
                var listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
                ClientContext.Load(listItems);
                ClientContext.ExecuteQuery();
                WriteObject(listItems, true);
            }
        }
 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;
 }
        public IEnumerable<MediaAsset> GetMediaToProcess()
        {
            ClientContext ctx = new ClientContext(webFullUrl);
            Web web = ctx.Web;

            List list = web.Lists.GetByTitle(mediaAssetsList);

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml =
                         @"<View>
                            <Query>
                              <Where>
                                <Eq>
                                    <FieldRef Name='MediaProcStatus'/>
                                    <Value Type='Text'>Pending</Value>
                                </Eq>
                              </Where>
                            </Query>
                            <RowLimit>100</RowLimit>
                          </View>";
            ListItemCollection listItems = list.GetItems(camlQuery);
            ctx.Load(
                    listItems,
                    items => items
                        .Include(
                            item => item.Id,
                            item => item["Title"],
                            item => item.ContentType,
                            item => item["MediaTempLocation"],
                            item => item["Author"]));
            ctx.ExecuteQuery();
            foreach (ListItem item in listItems)
            {
                MediaAsset asset = new MediaAsset();
                asset.Id = item.Id;
                asset.Title = item["Title"].ToString();
                asset.TempLocation = item["MediaTempLocation"] != null ? item["MediaTempLocation"].ToString() : String.Empty;
                if (item.ContentType.Name.Contains(MediaType.Audio.ToString()))
                {
                    asset.MediaType = MediaType.Audio;
                }
                else if (item.ContentType.Name.Contains(MediaType.Image.ToString()))
                {
                    asset.MediaType = MediaType.Image;
                }
                else
                {
                    asset.MediaType = MediaType.Video;
                }
                var user = item.FieldValues["Author"] as FieldUserValue;
                asset.UploaderEmail = GetUserEmail(user.LookupId);
                yield return asset;

            }
        }
        public bool LoadTimeOffTypes()
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            //using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken))
            var spContext =    SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle(WebConfigurationManager.AppSettings["TimeOffTypes"]);
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where></Query><FieldRef Name='Title' /><FieldRef Name='Description' /><FieldRef Name='ApprovalRequired' /></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();

                    StringBuilder timeofftypes = new StringBuilder();
                    timeofftypes.Append("OTP Overtime Pay,LVC Vacation Pay,LSK Sick Leave Pay,LCL Consulting,LFN Funeral Leave,LJD Jury Duty,LJR Jury Duty Reversal,");
                    timeofftypes.Append("LML Military Leave ,LUB Union Business,LPR Person Leave,LPS Personal Leave Charge to Sick,LCE Compensation Hours Earned,");
                    timeofftypes.Append("LCU Compensation Hours Used,LST Short Term Disability,LWP Leave Without Pay,LMW FMLA Leave Without Pay,LMV FMLA Vacation");
                    timeofftypes.Append("LMS FMLA Sick,LMC FMLA Comp,LMB FMLA Leave w/o Pay w/Benefits,LMN FMLA Leave w/o Pay w/o Benefits,LMR FMLA Personal,");
                    timeofftypes.Append("LMP FMLA Personal Charge to Sick,LMD FMLA Short Term Disability,FST Substitute Teaching,FTV Travel Increment,PAD Additional Compensation");

                    if (listItems == null || listItems.Count == 0)
                    {
                        ListItemCreationInformation itemCreateInfo;
                        Microsoft.SharePoint.Client.ListItem newItem;
                        foreach (string item in timeofftypes.ToString().Split(','))
                        {
                            itemCreateInfo = new ListItemCreationInformation();
                            newItem = selectedList.AddItem(itemCreateInfo);
                            newItem["Title"] = item.Trim();
                            newItem["Description"] = item.Trim();
                            newItem["ApprovalRequired"] = true;
                            newItem.Update();
                        }
                        clientContext.ExecuteQuery();
                        return true;
                    }
                    return false;
                }
                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return false;
                }
            }
        }
        public List<Tarefa> ObterTodos()
        {
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View/>";
            ListItemCollection itens = ListaTarefas.GetItems(camlQuery);

            Contexto.Load(itens);
            Contexto.ExecuteQuery();

            return TarefaConverterHelper.ItensParaTarefas(itens);
        }
Example #31
0
        private static Boolean MapVoucher(DataTable dtVouchers, List listHeader)
        {
            Logger.log.Info("Mapping Process Started..");
            bool mappingDone = false;

            try
            {
                int mappingCounter = 0;
                if (listHeader != null)
                {
                    Logger.log.Info("Mapping file contains " + dtVouchers.Rows.Count + " entries ");
                    foreach (DataRow dr in dtVouchers.Rows)
                    {
                        Logger.log.Info("Processing mapping for vendor Invoice number : " + dr["Vendor invoice number"].ToString().Trim());
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/>" +
                                            "<Value Type='Text'>" + dr["Vendor invoice number"].ToString().Trim() + " </Value></Eq></Where></Query></View>";
                        ListItemCollection collection = listHeader.GetItems(camlQuery);
                        context.Load(collection, items => items.Include(
                                         item => item.Id, item => item["Title"],
                                         item => item["Vendor_x0020_Name"],
                                         item => item["Vendor_x0020_Number"],
                                         item => item["Invoice_x0020_Amount"],
                                         item => item["Voucher_x0020_Date"],
                                         item => item["Payment_x0020_Status"],
                                         item => item["Accounting_x0020_Approval"]
                                         ));
                        context.ExecuteQuery();
                        if (collection.Count > 0)
                        {
                            Logger.log.Info("Found " + collection.Count + " entriesin the header " + dr["Vendor invoice number"].ToString().Trim());
                            foreach (ListItem item in collection)
                            {
                                if (item["Accounting_x0020_Approval"].ToString() == "Accounting Approval Approved")
                                {
                                    if (item["Vendor_x0020_Number"] != null && item["Vendor_x0020_Number"].ToString().Equals(dr["Vendor ID"].ToString().Trim(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (item["Invoice_x0020_Amount"] != null && item["Invoice_x0020_Amount"].ToString().Equals(dr["Gross amt relieved ICUR"].ToString().Trim(), StringComparison.OrdinalIgnoreCase))
                                        {
                                            item["Voucher_x0020_Number"] = dr["Payment Reference"].ToString();
                                            item["Voucher_x0020_Date"]   = dr[" Payment Date Filter"];// do +1
                                            item["Payment_x0020_Status"] = "Paid";
                                            item.Update();
                                            context.Load(item);
                                            context.ExecuteQuery();
                                            Logger.log.Info("Mapping is completed for item with Voucher Number " + item["Voucher_x0020_Number"].ToString() + " Vendor Number " + item["Vendor_x0020_Number"].ToString() + "Vendor ID " + dr["Vendor ID"].ToString());
                                            mappingCounter++;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            Logger.log.Info("No entries found in the header with Invoice Number : " + dr["Vendor invoice number"].ToString());
                        }
                    }
                    if (mappingCounter > 0)
                    {
                        mappingDone = true;
                    }
                    else
                    {
                        mappingDone = false;
                    }
                }
            }
            catch (Exception ex)
            {
                mappingDone = false;
                Console.WriteLine(" Error {0}", ex);
                Logger.log.Info("Error in mapping the vouchers " + ex.Message);
                BrokenInvoicesLog = BrokenInvoicesLog + "<br /><br />" + "Error in mapping the vouchers " + "Error " + ex.Message;
            }

            return(mappingDone);
        }
Example #32
0
        static void Main(string[] args)
        {
            try
            {
                #region InvoiceSplit
                //log the start time
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Started Processing..");
                Logger.log.Info("=========== Started Invoice Processing ====================");
                BrokenInvoicesLog = BrokenInvoicesLog + "<p>Hi Admin, </p>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<p>Coversheet Processing Status Report: <strong>" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Day + ", " + DateTime.Now.Year + "</strong></p>";

                BrokenInvoicesLog = BrokenInvoicesLog + "<table border=1 style='width: 100 %; border - style: solid; border - width: 1px;' > ";
                BrokenInvoicesLog = BrokenInvoicesLog + "<tr style='background-color:#7FFFD4' >";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > ID </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice # </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Vendor Name </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Vendor No </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Company </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Date </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Amount </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Status </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Error </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "</tr>";

                Utils.ReadConfigurationValues();

                dtInvoices = ConstructDataTable();
                if (!string.IsNullOrEmpty(Invoice._siteUrl))
                {
                    context = new ClientContext(Invoice._siteUrl);
                }
                else
                {
                    Logger.log.Info("The site url is empty in configuration.");
                }
                if (Invoice._runforCloud)
                {
                    Logger.log.Info("Configuration set to run for Sharepoint Online.");
                    System.Security.SecureString pwdSecureString = new System.Security.SecureString();
                    if (!string.IsNullOrEmpty(Invoice._password))
                    {
                        foreach (char c in Invoice._password)
                        {
                            pwdSecureString.AppendChar(c);
                        }
                        context.Credentials = new SharePointOnlineCredentials(Invoice._userName, pwdSecureString);
                    }
                }
                else
                {
                    Logger.log.Info("Configuration set to run for SharePoint On Premise.");
                    context.Credentials = new NetworkCredential(Invoice._userName, Invoice._password, Invoice._domain);
                }

                Web web = context.Web;
                context.ExecuteQuery();
                Logger.log.Info("Context created for given site " + Invoice._siteUrl);

                listCoversheet = web.Lists.GetByTitle(Invoice._invoiceSourceLibraryName);
                List listHeader  = web.Lists.GetByTitle(Invoice._invoceDestinationListName);
                List listDetails = web.Lists.GetByTitle(Invoice._coversheetDetailsListName);//To push

                Logger.log.Info("Reading items from List : " + Invoice._invoiceSourceLibraryName);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='processed'/><Value Type='Choice'>False</Value></Eq></Where></Query></View>";

                ListItemCollection coversheetCollection = listCoversheet.GetItems(camlQuery);

                Logger.log.Info("CamlQuery: " + camlQuery.ViewXml);

                context.Load(
                    coversheetCollection,
                    items => items.Include(
                        item => item.Id,
                        item => item["Vendor_x0020_Name"],
                        item => item["Vendor"],
                        item => item["PO"],
                        item => item["Invoice_x0020_Co"],
                        item => item["Invoice_x0020_DIV"],
                        item => item["Invoice_x0020__x0023_"],//Invoice#
                        item => item["Invoice_x0020_Date"],
                        item => item["Invoice_x0020_Amt"],
                        item => item["Company"],
                        item => item["Division"],
                        item => item["Dept_x002d_3_x0020_CH"],
                        item => item["Account_x002d_5_x0020_CH"],
                        item => item["Expense_x0020_Amt"],
                        item => item["Job"],
                        item => item["CER"],
                        //item => item["Monetary_Unit"],
                        item => item["Acct_x0020_Date"],
                        item => item["processed"],
                        item => item["Account_x0020_String"]
                        ));
                context.ExecuteQuery();
                dtInvoices.Clear();

                //"Filling datatable with CS Invoice data if invoice alreadey not exist in header list;
                FillCoversheetInfotoDataTable(dtInvoices, coversheetCollection);

                //Console.WriteLine("Invoice Processing Completed!");
                if (dtInvoices != null && dtInvoices.Rows.Count > 0)
                {
                    Logger.log.Info("Retrieved " + dtInvoices.Rows.Count + " Invoices from CoverSheet ");
                    PushtoHeaderList(dtInvoices, listHeader, listDetails);
                }
                else
                {
                    Logger.log.Info("Retrieved " + dtInvoices.Rows.Count + " Invoices from CoverSheet ");
                }
                Console.WriteLine("Invoice Processing Completed!");
                Console.WriteLine("Splitting is Completed.");
                Logger.log.Info("Splitting Process is Completed.. ");
                if (Invoice._mapVouchers)
                {
                    Logger.log.Info("Starting Mapping the Voucher Numbers");
                    Console.WriteLine("Started Mapping Voucher Number!");

                    if (!string.IsNullOrEmpty(Invoice._filePath))
                    {
                        string filepath = string.Empty;
                        if (System.IO.File.Exists(Invoice._filePath))
                        {
                            Logger.log.Info("Getting voucher mappings file from filepath");
                            filepath = Invoice._filePath;
                        }
                        else
                        {
                            Logger.log.Info("Getting voucher mappings file from folder path");
                            Console.WriteLine("Getting file from folder  :" + Invoice._filePath);
                            filepath = GetFileFromFolderPath(Invoice._filePath);
                        }
                        if (!string.IsNullOrEmpty(filepath))
                        {
                            string destinationPath = string.Empty;
                            if (System.IO.File.Exists(Invoice._repository))
                            {
                                Logger.log.Info("Reading destination mapping vouchers filepath ");
                                destinationPath = Invoice._repository;
                            }
                            else
                            {
                                Logger.log.Info("Reading destination mapping vouchers filepath from folder");
                                string fileName = Path.GetFileName(filepath);
                                if (Invoice._repository.ToString().ToLower().Contains(fileName.ToLower()))
                                {
                                    destinationPath = Invoice._repository;
                                }
                                else
                                {
                                    destinationPath = Invoice._repository + fileName;
                                }
                            }

                            Logger.log.Info("Reading voucher map data from given file " + filepath);
                            DataTable dtVouchers = new DataTable();

                            /*dtVouchers = Utils.ReadExcelData(filepath);
                             * bool mappingCompleted = MapVoucher(dtVouchers, listHeader);
                             * try
                             * {
                             *  if (mappingCompleted)
                             *  {
                             *      Logger.log.Info("Mapping is completed.");
                             *      MoveFile(filepath, destinationPath);
                             *      Console.WriteLine("Voucher Mapping Process Completed.!");
                             *  }
                             * }
                             * catch (Exception)
                             * {
                             *  Console.WriteLine("Error in moving the file");
                             * }*/
                        }
                        else
                        {
                            Console.WriteLine("Unable to map the voucher, reason could be the file path is not correct or the file doenst exist in the specified locaton : " + filepath);
                            Logger.log.Info("Unable to map the voucher, reason could be the file path is not correct or the file doenst exist in the specified locaton : " + filepath);
                        }
                    }
                }
                else
                {
                    Logger.log.Info("Mapping Voucher set to false in configuration.");
                }
                Console.WriteLine("Please Close the Window to exit Process..!");
                #endregion InvoiceSplit
                if (!string.IsNullOrEmpty(BrokenInvoicesLog))
                {
                    BrokenInvoicesLog = BrokenInvoicesLog + " </table><br />";
                    string LogFileName = DateTime.Now.ToString("yyyyMMdd");
                    BrokenInvoicesLog = BrokenInvoicesLog + "<p>Complete log file: C:\\Dayton Rogers Log History\\InvoiceSplit_" + LogFileName + ".log </p>";
                    BrokenInvoicesLog = BrokenInvoicesLog + "<p>Thank you</p>";
                    Utils.SendEmail(BrokenInvoicesLog, Invoice._toadrress);
                }
                Logger.log.Info("============= Completed Invoice Processing ====================");
                //Console.ReadLine();
            } catch (Exception ex) {
                //Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error in Processing Invoice, Please check all the configurations and try again..{0}", ex);
                Logger.log.Error("Error in Processing Invoices, Message : " + ex.ToString());
                try
                {
                    if (!string.IsNullOrEmpty(BrokenInvoicesLog))
                    {
                        //BrokenInvoices Email Body is not Empty then send Email
                        BrokenInvoicesLog = BrokenInvoicesLog + " </table><br />";
                        string LogFileName = DateTime.Now.ToString("yyyyMMdd");
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>Complete log file: C:\\Dayton Rogers Log History\\InvoiceSplit_" + LogFileName + ".log </p>";
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>" + " <b> Error in Processing Invoice </b>  " + ex.ToString() + "</p>";
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>Thank you</p>";
                        Utils.SendEmail(BrokenInvoicesLog, Invoice._toadrress);
                    }
                }
                catch (Exception)
                {
                    //Leave
                }
            }
            Console.ReadLine();
        }
        public void InsertData(ClientContext clientContext, DKBSDbContext dbContext)
        {
            try
            {
                SP.List   oListData = clientContext.Web.Lists.GetByTitle("Email templates");
                CamlQuery camlQuery = new CamlQuery();
                // camlQuery.ViewXml = "<View Scope='Recursive'><Query></Query></View>";
                camlQuery.ViewXml = "<View><Query></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Author' /><FieldRef Name='Editor' /><FieldRef Name='Subject' /><FieldRef Name='EmailBody' /><FieldRef Name='MailLanguage' /><FieldRef Name='Created' /><FieldRef Name='Modified' /></ViewFields></View>";
                ListItemCollection oListDataItem = oListData.GetItems(camlQuery);

                clientContext.Load(oListDataItem);
                clientContext.ExecuteQuery();

                foreach (ListItem oItem in oListDataItem)
                {
                    Console.WriteLine("ID: {0} \nTitle: {1}", oItem["ID"], oItem["Title"]);
                    Console.WriteLine(((SP.FieldUserValue)(oItem["Author"])).LookupValue);
                    Console.WriteLine(((SP.FieldUserValue)(oItem["Editor"])).LookupValue);
                    Console.WriteLine(oItem["Created"].ToString());
                    Console.WriteLine(oItem["Modified"].ToString());
                    Console.WriteLine(oItem["Subject"]);
                    Console.WriteLine(oItem["EmailBody"]);
                    // Console.WriteLine(oItem["MailLanguage"]);
                    //  Console.WriteLine(((SP.FieldUserValue)(oItem["MailLanguage"])).LookupValue);

                    EmailTemplate emailtemp = new EmailTemplate();
                    // if (oItem["ID"] != null)
                    //  if (Convert.ToInt32(oItem["ID"])>13)
                    var x = Convert.ToDateTime(oItem["Modified"].ToString());
                    if (x.Year >= 2018)
                    {
                        if (oItem["Subject"] != null)
                        {
                            emailtemp.Subject = oItem["Subject"].ToString();
                        }

                        else
                        {
                            emailtemp.Subject = "Missing Subject";
                        }

                        emailtemp.Name = oItem["Title"].ToString();
                        // emailtemp.Subject = oItem["Subject"].ToString();
                        emailtemp.Content        = oItem["EmailBody"].ToString();
                        emailtemp.CreatedDate    = Convert.ToDateTime(oItem["Created"].ToString());
                        emailtemp.LastModified   = Convert.ToDateTime(oItem["Modified"].ToString());
                        emailtemp.CreatedBy      = (((SP.FieldUserValue)(oItem["Author"])).LookupValue).ToString();
                        emailtemp.LastModifiedBy = (((SP.FieldUserValue)(oItem["Editor"])).LookupValue).ToString();
                        emailtemp.Language       = "DK";
                        emailtemp.IsActive       = true;

                        dbContext.Add(emailtemp);
                        dbContext.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public override void Provision(ClientContext context, Web web)
        {
            //create the group
            createYammerGroup(txtGroupName.Text, (cboNewsfeedType.SelectedValue == "Private") ? true : false);

            //get user details
            var     response  = getYammerJson(String.Format("https://www.yammer.com/api/v1/users/current.json?access_token={0}", hdnYammerAccessToken.Value));
            JObject oResponse = JObject.Parse(response);
            var     network   = oResponse.SelectToken("network_domains[0]").ToString();
            var     userId    = oResponse.SelectToken("id").ToString();

            //get the users groups to check for the group
            response = getYammerJson(String.Format("https://www.yammer.com/api/v1/groups/for_user/{0}.json", userId));
            var    groups  = JsonConvert.DeserializeObject <List <YamGroup> >(response);
            string groupId = null;

            for (int i = 0; i < groups.Count; i++)
            {
                if (groups[i].full_name.Equals(txtGroupName.Text, StringComparison.CurrentCultureIgnoreCase))
                {
                    groupId = groups[i].Id;
                    break;
                }
            }

            if (groupId != null)
            {
                string wpXML = @"
<?xml version='1.0' encoding='utf-8'?>
<webParts>
<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
<metaData>
<type name='Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
<properties>
<property name='Title' type='string'>$Resources:core,ScriptEditorWebPartTitle;</property>
<property name='Description' type='string'>$Resources:core,ScriptEditorWebPartDescription;</property>
<property name='ChromeType' type='chrometype'>None</property>
<property name='Content' type='string'>
<![CDATA[
<div id='embedded-feed' style='height: 500px;'></div>
<script type='text/javascript' src='https://assets.yammer.com/assets/platform_embed.js'></script>
<script type='text/javascript'>  yam.connect.embedFeed({ container: '#embedded-feed', network: '" + network + @"', feedType: 'group', feedId: '" + groupId + @"'}); </script>

]]>
</property>
</properties>
</data>
</webPart>
</webParts>";
                wpXML = wpXML.Replace("\r\n", "");

                //get the web part page
                var       list      = web.Lists.GetByTitle("Site Pages");
                CamlQuery camlQuery = new CamlQuery();
                var       items     = list.GetItems(camlQuery);
                context.Load(items, i =>
                             i.Include(item => item.DisplayName, item => item["WikiField"]).Where(item => item.DisplayName == "Home"));
                context.ExecuteQuery();

                //remove the sitefeed
                var wikiPage = items[0].File;
                LimitedWebPartManager limitedWebPartManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
                var wps = limitedWebPartManager.WebParts;
                context.Load(wps);
                context.ExecuteQuery();
                for (int i = 0; i < wps.Count; i++)
                {
                    var wp = wps[i].WebPart;
                    context.Load(wp);
                    context.ExecuteQuery();

                    if (wp.ZoneIndex == 1)
                    {
                        wps[i].DeleteWebPart();
                        context.ExecuteQuery();
                        break;
                    }
                }

                //add the yammer embed
                WebPartDefinition wpd = limitedWebPartManager.ImportWebPart(wpXML);
                var newWP             = limitedWebPartManager.AddWebPart(wpd.WebPart, "wpz", 0);
                context.Load(newWP);
                context.ExecuteQuery();

                // Create reference to WebPart in HTML
                string      wikiField = items[0]["WikiField"] as string;
                XmlDocument xd        = new XmlDocument();
                xd.PreserveWhitespace = true;
                xd.LoadXml(wikiField);
                XmlElement layoutsZoneInner = xd.SelectSingleNode("div/table/tbody/tr[2]/td/div/div") as XmlElement;

                //create wrapper
                XmlElement wpWrapper = xd.CreateElement("div");
                layoutsZoneInner.AppendChild(wpWrapper);
                XmlAttribute attribute = xd.CreateAttribute("class");
                wpWrapper.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read ms-rte-wpbox";

                //create inner elements
                XmlElement div1 = xd.CreateElement("div");
                wpWrapper.AppendChild(div1);
                div1.IsEmpty = false;
                attribute    = xd.CreateAttribute("class");
                div1.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-notify ms-rtestate-read " + newWP.Id.ToString("D");
                attribute       = xd.CreateAttribute("id");
                div1.Attributes.Append(attribute);
                attribute.Value = "div_" + newWP.Id.ToString("D");

                XmlElement div2 = xd.CreateElement("div");
                wpWrapper.AppendChild(div2);
                div2.IsEmpty = false;
                attribute    = xd.CreateAttribute("class");
                div2.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read";
                attribute       = xd.CreateAttribute("style");
                div2.Attributes.Append(attribute);
                attribute.Value = "display:none";
                attribute       = xd.CreateAttribute("id");
                div2.Attributes.Append(attribute);
                attribute.Value = "vid_" + newWP.Id.ToString("D");

                // Update
                items[0]["WikiField"] = xd.OuterXml;
                items[0].Update();
                context.ExecuteQuery();
            }
        }
Example #35
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSpecified(nameof(Batch)))
            {
                var list = List.GetList(Batch);

                var id = Identity.GetItemId();
                {
                    if (Recycle)
                    {
                        list.Items.RecycleByIdBatch(Batch.Batch, id.Value);
                    }
                    else
                    {
                        list.Items.DeleteByIdBatch(Batch.Batch, id.Value);
                    }
                }
            }
            else
            {
                List list;
                if (List != null)
                {
                    list = List.GetList(CurrentWeb);

                    if (Identity == null || (Identity.Item == null && Identity.Id == 0))
                    {
                        // Remove all list items from the list
                        if (Force || ShouldContinue($"{(Recycle ? "Recycle" : "Remove")} all items in the list?", Resources.Confirm))
                        {
                            CamlQuery query = new CamlQuery {
                                ViewXml = "<View><Query><Where></Where></Query><ViewFields><FieldRef Name='ID' /></ViewFields><RowLimit>100</RowLimit></View>"
                            };

                            bool stillItemsToProcess = true;
                            while (stillItemsToProcess)
                            {
                                var listItems = list.GetItems(query);
                                ClientContext.Load(listItems, listItem => listItem.Include(oneItem => oneItem, oneItem => oneItem["ID"]));
                                ClientContext.ExecuteQueryRetry();

                                var itemsToProcess = listItems.Count;
                                if (itemsToProcess > 0)
                                {
                                    for (var x = itemsToProcess - 1; x >= 0; x--)
                                    {
                                        if (Recycle)
                                        {
                                            listItems[x].Recycle();
                                        }
                                        else
                                        {
                                            listItems[x].DeleteObject();
                                        }
                                    }
                                    ClientContext.ExecuteQueryRetry();
                                }
                                else
                                {
                                    stillItemsToProcess = false;
                                }
                            }
                        }
                        return;
                    }
                }
                else
                {
                    if (Identity == null || Identity.Item == null)
                    {
                        throw new PSArgumentException($"No -Identity has been provided specifying the item to remove");
                    }

                    list = Identity.Item.ParentList;
                }

                var item    = Identity.GetListItem(list);
                var message = $"{(Recycle ? "Recycle" : "Remove")} list item with id {item.Id}?";
                if (Force || ShouldContinue(message, Resources.Confirm))
                {
                    if (Recycle)
                    {
                        item.Recycle();
                    }
                    else
                    {
                        item.DeleteObject();
                    }
                    ClientContext.ExecuteQueryRetry();
                }
            }
        }
Example #36
0
        // Delete Method
        private void DeletionProcess()
        {
            if (cboSiteList.SelectedItem.ToString().Contains("Archive"))
            {
                MessageBox.Show("Cannot delete items from an archive list.");
            }

            else
            {
                try
                {
                    if (IsSPOnline == true)
                    {
                        SPOnlineContext = ClaimClientContext.GetAuthenticatedContext(cboSiteURL.SelectedItem.ToString());
                        SP.List selectedList = SPOnlineContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = @"";

                        ListItemCollection oListitemCollection = selectedList.GetItems(camlQuery);
                        SPOnlineContext.Load(oListitemCollection);
                        SPOnlineContext.ExecuteQuery();

                        int listCount = oListitemCollection.Count;

                        foreach (ListItem sourceListItem in oListitemCollection)
                        {
                            SP.List destinationList = SPOnlineContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem destinationListItem = destinationList.AddItem(itemCreateInfo);

                            switch (cboSiteList.SelectedItem.ToString())
                            {
                            case "All Grant Submitssss":

                                for (int i = 0; i < listCount; i++)
                                {
                                    var item = oListitemCollection[i]; // In order to prevent changes in all places inside the [for loop]
                                    item.DeleteObject();
                                    listCount--;                       // Here, as I am removing 1 item, I am decrementing the count
                                    i--;

                                    // Executes the clientContext.ExecuteQuery() inside the loop to prevent the
                                    // 'The request uses too many resources' error.
                                    selectedList.Update();
                                    SPOnlineContext.ExecuteQuery();

                                    //MessageBox.Show("Deletion in Progress ...");
                                }

                                selectedList.Update();
                                SPOnlineContext.ExecuteQuery();
                                //int endCount = oListitemCollection.Count;

                                break;
                            }// END Switch
                        }

                        MessageBox.Show("Deletion Completed!");

                        // Populate DGV - Refresh!!
                        PopulateDGV();
                    }

                    else
                    {
                        // SP ON PREM Selections
                        SPOnPremContext = new ClientContext(cboSiteURL.SelectedItem.ToString());
                        SP.List selectedList = SPOnPremContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = @"";

                        ListItemCollection oListitemCollection = selectedList.GetItems(camlQuery);
                        SPOnPremContext.Load(oListitemCollection);
                        SPOnPremContext.ExecuteQuery();

                        int listCount = oListitemCollection.Count;

                        foreach (ListItem sourceListItem in oListitemCollection)
                        {
                            SP.List destinationList = SPOnPremContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem destinationListItem = destinationList.AddItem(itemCreateInfo);

                            switch (cboSiteList.SelectedItem.ToString())
                            {
                            case "CADD Office Leave Calendar":

                                for (int i = 0; i < listCount; i++)
                                {
                                    var item = oListitemCollection[i]; // In order to prevent changes in all places inside the [for loop]
                                    item.DeleteObject();
                                    listCount--;                       // Here, as I am removing 1 item, I am decrementing the count
                                    i--;

                                    // Executes the clientContext.ExecuteQuery() inside the loop to prevent the
                                    // 'The request uses too many resources' error.
                                    selectedList.Update();
                                    SPOnPremContext.ExecuteQuery();

                                    //MessageBox.Show("Deletion in Progress ...");
                                    //TODO: Need Progressbar here
                                }

                                selectedList.Update();
                                SPOnPremContext.ExecuteQuery();
                                //int endCount = oListitemCollection.Count;

                                break;
                            }// END Switch
                        }

                        MessageBox.Show("Deletion Completed!");

                        // Populate DGV - Refresh!!
                        PopulateDGV();
                    }
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                    MessageBox.Show("Error Encountered " + ex.Message);
                }
            }
        }
Example #37
0
        public FacturaDto getListSharepoint(string factura, string CodigoProveedor)
        {
            try
            {
                FacturaDto objFactura = new FacturaDto();
                _Context = _Conexion.ConetionSharepoint();
                if (_Context != null)
                {
                    CamlQuery QueryReferencia = new CamlQuery();

                    var obj = _Context.Web.Lists.GetByTitle("InformacionFacturas");

                    CamlQuery query = new CamlQuery();
                    query.ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='Factura'/>" +
                                    "<Value Type='text'>" + factura + "</Value></Eq>" +
                                    "<Eq><FieldRef Name='CodigoProveedor'/>" +
                                    "<Value Type='text'>" + CodigoProveedor + "</Value></Eq>" +
                                    "</And></Where></Query><RowLimit>100</RowLimit></View>";
                    ListItemCollection itemFactura = obj.GetItems(query);
                    _Context.Load(itemFactura);
                    _Context.ExecuteQuery();
                    if (itemFactura.Count > 0)
                    {
                        for (int i = 0; i < itemFactura.Count; i++)
                        {
                            var item = itemFactura[i];
                            objFactura.Factura = (string)item["Factura"];
                            //objFactura.Proveedor = (string)item["Proveedor"];
                            objFactura.Codproveedor = (string)item["CodigoProveedor"];
                            //objFactura.ResponsableSAP = (string)item["ResponsableSAP"];
                            //objFactura.Fecharadicado = (DateTime)item["FechaRadicado"];
                            //FieldLookupValue ResponsableFactura = item["ResponsableFactura"] as FieldLookupValue;
                            //objFactura.Responsablefactura = ResponsableFactura.LookupValue;
                            //objFactura.Valor = Convert.ToString((Double)item["Valor"]);
                            //objFactura.Moneda = (string)item["Moneda"];
                            //objFactura.Numeropreliminar = (string)item["NumeroPreliminar"];
                            //objFactura.Numerocontabilizado = (string)item["NumeroContabilizado"];
                            //FieldLookupValue ResponsableEstado = item["ResponsableEstado"] as FieldLookupValue;
                            //objFactura.Responsableestado = ResponsableEstado.LookupValue;
                            //objFactura.Estado = item.FieldValues["Estado"].ToString();
                            //objFactura.Limitegestion = (DateTime)item["Limite_x0020_gestion"];
                            //objFactura.CodigoRadicado = (string)item["C_x00f3_digo_x0020_radicado"];
                            //objFactura.Añoradicado = Convert.ToString((Double)item["A_x00f1_o_x0020_del_x0020_radica"]);
                            //objFactura.Nitproveedor = (string)item["Nit_x0020_proveedor"];
                            //objFactura.Motivodevolución = (string)item["Motivo_x0020_devoluci_x00f3_n"];
                            //objFactura.Descripciondevolucion = (string)item["Descripcion_x0020_devolucion"];
                            //objFactura.Tipodocumento = (string)item["Tipo_x0020_documento"];
                            //objFactura.Iddocumento = (string)item["IdDocumento"];
                            //objFactura.Fechafactura = (DateTime)item["FechaFactura"];
                            objFactura.Linkdocumento = (string)item["LinkDocumento"];
                            //objFactura.Idfactura = (Double)item["IdFactura"];
                            //objFactura.Estadointernofactura = (string)item["EstadoInternoFactura"];
                            //objFactura.Responsabletramite = (string)item["ResponsableTramite"];
                            //objFactura.Etapatramite = (string)item["EtapaTramite"];
                            //objFactura.Cajatramite = (string)item["CajaTramite"];
                            //objFactura.Serietramite = (string)item["SerieTramite"];
                            //objFactura.Archivotramite = (string)item["ArchivoTramite"];
                            //objFactura.Ubicaciontramite = (string)item["UbicacionTramite"];
                            //objFactura.Notificacionjefe = (Boolean)item["NotificacionJefe"];
                            //objFactura.Notificacionresponsable = (Boolean)item["NotificacionResponsable"];
                            //objFactura.Codigodevolución = (string)item["CodigoDevolucion"];
                            //objFactura.Responsablecomprasnoindustriales = (string)item["ResponsableCompras"];
                            //objFactura.Codigodevolución = (string)item["CodigoDevolucion"];
                            //objFactura.Solicitantecompra = (string)item["SolicitanteCompras"];
                            //objFactura.Novidad = (Boolean)item["Novidad"];
                            //objFactura.Causantedevolucion = (string)item["CausanteDevolucion"];
                            //objFactura.Usuariocontabilidad = (string)item["UsuarioContabilidad"];
                        }
                    }
                }
                return(objFactura);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        /// <summary>
        /// Retrieves or creates the folder as a ListItem
        /// </summary>
        /// <param name="onlineLibrary">The target list for the folder</param>
        /// <param name="destinationFolder">The parent folder of the folter to be created</param>
        /// <param name="folderName">The folder to be created</param>
        /// <param name="defaultStartItemId">(OPTIONAL) If the list/library is above the threshold this will be the start index of the caml queries</param>
        /// <param name="defaultLastItemId">(OPTIONAL) If the list/library is above the threshold this will be the terminating index of the caml queries</param>
        /// <returns>The listitem as a folder</returns>
        public static Folder GetOrCreateFolder(this List onlineLibrary, Folder destinationFolder, string folderName, Nullable <int> defaultStartItemId = default(int?), Nullable <int> defaultLastItemId = default(int?))
        {
            if (!onlineLibrary.IsPropertyAvailable(lctx => lctx.BaseType))
            {
                onlineLibrary.Context.Load(onlineLibrary, lctx => lctx.BaseType, lctx => lctx.BaseTemplate);
                onlineLibrary.Context.ExecuteQueryRetry();
            }

            if (!destinationFolder.IsPropertyAvailable(fctx => fctx.ServerRelativeUrl) ||
                !destinationFolder.IsObjectPropertyInstantiated(fctx => fctx.Folders))
            {
                destinationFolder.Context.Load(destinationFolder, afold => afold.ServerRelativeUrl, afold => afold.Folders);
                destinationFolder.Context.ExecuteQueryRetry();
            }


            ListItem folderItem = null;

            var folderRelativeUrl = destinationFolder.ServerRelativeUrl;
            var camlFields        = new string[] { "Title", "ID" };
            var camlViewFields    = CAML.ViewFields(camlFields.Select(s => CAML.FieldRef(s)).ToArray());

            // Remove invalid characters
            var trimmedFolder  = HelperExtensions.GetCleanDirectory(folderName, string.Empty);
            var linkFileFilter = CAML.Eq(CAML.FieldValue("Title", FieldType.Text.ToString("f"), trimmedFolder));

            if (onlineLibrary.BaseType == BaseType.DocumentLibrary)
            {
                linkFileFilter = CAML.Or(
                    linkFileFilter,
                    CAML.Eq(CAML.FieldValue("LinkFilename", FieldType.Text.ToString("f"), trimmedFolder)));
            }

            var camlClause = CAML.And(
                CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), folderRelativeUrl)),
                CAML.And(
                    CAML.Eq(CAML.FieldValue("FSObjType", FieldType.Integer.ToString("f"), 1.ToString())),
                    linkFileFilter
                    )
                );

            var camlQueries = onlineLibrary.SafeCamlClauseFromThreshold(1000, camlClause, defaultStartItemId, defaultLastItemId);

            foreach (var camlAndValue in camlQueries)
            {
                ListItemCollectionPosition itemPosition = null;
                var camlWhereClause = CAML.Where(camlAndValue);
                var camlQuery       = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(
                        ViewScope.RecursiveAll,
                        camlWhereClause,
                        string.Empty,
                        camlViewFields,
                        5)
                };
                camlQuery.ListItemCollectionPosition = itemPosition;
                var listItems = onlineLibrary.GetItems(camlQuery);
                onlineLibrary.Context.Load(listItems, lti => lti.ListItemCollectionPosition);
                onlineLibrary.Context.ExecuteQueryRetry();

                if (listItems.Count() > 0)
                {
                    folderItem = listItems.FirstOrDefault();
                    System.Diagnostics.Trace.TraceInformation("Folder {0} exists in the destination folder.  Skip folder creation .....", folderName);
                    break;
                }
            }
            ;

            if (folderItem != null)
            {
                return(folderItem.Folder);
            }

            try
            {
                var info = new ListItemCreationInformation
                {
                    UnderlyingObjectType = FileSystemObjectType.Folder,
                    LeafName             = trimmedFolder,
                    FolderUrl            = folderRelativeUrl
                };

                folderItem          = onlineLibrary.AddItem(info);
                folderItem["Title"] = trimmedFolder;
                folderItem.Update();
                onlineLibrary.Context.ExecuteQueryRetry();
                System.Diagnostics.Trace.TraceInformation("{0} folder Created", trimmedFolder);
                return(folderItem.Folder);
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Trace.TraceError("Failed to create or get folder for name {0} MSG:{1}", folderName, Ex.Message);
            }

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

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

                Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(ConfigurationManager.AppSettings.Get(SPOConstants.SPOSiteURL)
                                                                               + "/"
                                                                               + ConfigurationManager.AppSettings.Get(SPOConstants.SPOFolderPresentationThumbnailInternalName) + "/" + 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;

                    //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() : "") : "";
                    Name    = keyValuePairs.ContainsKey(SPOConstants.Name) ? (keyValuePairs[SPOConstants.Name] != null ? keyValuePairs[SPOConstants.Name].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_presentation, r_object_id, i_chronicle_id, Constants.Ir_presentation_r_folder_path, ParentFileName, FileFormatConstants.JPEG, Constants.Presentations + "/" + Name, ParentGuid, ParentGuid, guid + '@' + ParentGuid, Constants.Presentations, display_order);
                }
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                {
                }
                else
                {
                    Console.WriteLine("Error in Presentation - GetChildItem :" + ex.Message);
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in Presentation - GetChildItem :" + ex.Message);
                throw ex;
            }
        }
Example #40
0
        //Every 5 minutes
        //0 */5 * * * *
        //Once a day at 9am
        //0 00 9 * * *
        public static void Run([TimerTrigger("0 00 9 * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
            try
            {
                string siteUrl = Environment.GetEnvironmentVariable("SharePointSiteUrl");

                var task = Task.Run(async() => await CSOMHelper.GetClientContext(siteUrl));
                task.Wait();
                if (task.Result != null)
                {
                    using (var ctx = task.Result)
                    {
                        List      l        = ctx.Web.Lists.GetByTitle("AMTaskList");
                        CamlQuery newQuery = new CamlQuery
                        {
                            ViewXml = "<View><Query><Where><And>" +
                                      "<Lt><FieldRef Name=\"DueDate\"/><Value Type=\"DateTime\"><Today/></Value></Lt>" +
                                      "<Lt><FieldRef Name=\"PercentComplete\" /><Value Type=\"Number\">1.00</Value></Lt>" +
                                      "</And></Where></Query><RowLimit>100</RowLimit></View>"
                        };
                        var items = l.GetItems(newQuery);
                        ctx.Load(items);
                        ctx.ExecuteQuery();

                        if (items.Count > 0)
                        {
                            string filePath = Path.Combine(Environment.GetEnvironmentVariable("Home") ?? throw new InvalidOperationException(), "site\\wwwroot\\", "AMCard.json");
                            //string filePath = "AMCard.json";
                            string jsonAM = System.IO.File.ReadAllText(filePath);

                            if (jsonAM.Length > 0)
                            {
                                var notificationHelper = new NotificationHelper(log);
                                foreach (var item in items)
                                {
                                    var fuv  = (FieldUserValue[])item["AssignedTo"];
                                    var user = ctx.Web.EnsureUser(fuv[0].LookupValue);
                                    ctx.Load(user);
                                    ctx.ExecuteQuery();
                                    //send email
                                    string title   = item["Title"].ToString();
                                    string dueDate = ((DateTime)item["DueDate"]).ToString("yyyy-MM-dd");
                                    //string dueDate = ((DateTime) item["DueDate"]).ToString("MM/dd/YYYY");
                                    string percentComplete = (((double)item["PercentComplete"]) * 100).ToString(CultureInfo.InvariantCulture);
                                    //string percentComplete = (((double)item["PercentComplete"]) * 100) + " %";
                                    string description = item["Body"]?.ToString() ?? "";
                                    string itemUrl     = Environment.GetEnvironmentVariable("SharePointListDisplayForm") + item["ID"];
                                    var    itemEmail   = string.Format(jsonAM, title, dueDate, percentComplete, description, item["ID"], itemUrl);

                                    var result = notificationHelper.SendNotification(user.Email, itemEmail);
                                    log.Info($"SendAM (Run) notification {result} at: {DateTime.Now} - {user.Email}");
                                }
                            }
                            else
                            {
                                log.Info($"SendAM (Run) error at: {DateTime.Now} - jsonAM.Length 0");
                            }
                        }

                        else
                        {
                            log.Info($"SendAM (Run) at: {DateTime.Now} - items.Count 0");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Info($"SendAM (Run) error at: {DateTime.Now} - {ex.Message} - {ex.StackTrace}");
            }
        }
Example #41
0
        private void BuscarV2()
        {
            String reg_act_tomo     = txTomo.Text;
            String reg_act_semestre = txSemestre.Text;
            String reg_act_año      = txAnio.Text;
            String reg_act_seccion  = txSeccion.Text;
            String reg_act_serie    = txSerie.Text;
            String reg_act_partida  = txPartida.Text;
            String reg_act_libro    = txLibro.Text;


            bool   firstParameter  = true;
            bool   secondParameter = false;
            bool   nextParameter   = false;
            string query           = "";

            if (reg_act_tomo.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Number'>{0}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Number'>{0}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Number'>{0}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_semestre.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Number'>{1}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Number'>{1}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Number'>{1}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_año.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Number'>{2}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Number'>{2}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Number'>{2}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_seccion.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Number'>{3}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Number'>{3}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Number'>{3}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_serie.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_partida.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Partida' /><Value Type='Number'>{5}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Partida' /><Value Type='Number'>{5}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Partida' /><Value Type='Number'>{5}</Value></Eq></And>";
                    }
                }
            }

            if (reg_act_libro.Length > 0)
            {
                if (firstParameter)
                {
                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Number'>{6}</Value></Eq>";
                    firstParameter  = false;
                    secondParameter = true;
                }
                else
                {
                    if (secondParameter)
                    {
                        query           = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Number'>{6}</Value></Eq></And>";
                        secondParameter = false;
                        nextParameter   = true;
                    }
                    else
                    {
                        query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Number'>{6}</Value></Eq></And>";
                    }
                }
            }

            query = "<View><Query><Where>" + query + "</Where></Query></View>";

            query = string.Format(@query,
                                  reg_act_tomo,
                                  reg_act_semestre,
                                  reg_act_año,
                                  reg_act_seccion,
                                  reg_act_serie,
                                  reg_act_partida,
                                  reg_act_libro);

            try
            {
                using (ClientContext ctx = new ClientContext("http://servidors04/sitios/digitalizacion"))
                {
                    Web  web  = ctx.Web;
                    List list = web.Lists.GetById(new Guid("9c3f7319-7740-426f-87a4-bf9b8c0eb6b8"));
                    var  q    = new CamlQuery()
                    {
                        ViewXml = query
                    };

                    Microsoft.SharePoint.Client.ListItemCollection arlRows = list.GetItems(q);
                    ctx.Load(arlRows);
                    ctx.ExecuteQuery();

                    lblResultado.Text = "Se han obtenido " + arlRows.Count + " resultados de la búsqueda.";

                    foreach (var item in arlRows)
                    {
                        List <Prelacion> resultados = new List <Prelacion>();
                        Prelacion        r          = new Prelacion();


                        for (int i = 0; i <= arlRows.Count - 1; i++)
                        {
                            Microsoft.SharePoint.Client.ListItem      itemRepositorio = (Microsoft.SharePoint.Client.ListItem)arlRows[i];
                            Dictionary <string, object>               dc   = (Dictionary <string, object>)itemRepositorio.FieldValues;
                            Microsoft.SharePoint.Client.FieldUrlValue fURl = (Microsoft.SharePoint.Client.FieldUrlValue)dc["Pagina"];

                            r = new Prelacion();

                            r.RepositoryUrl   = fURl.Url;
                            r.Tramitante      = dc["No_x002e__x0020_Notaria"].ToString();
                            r.IdPrelacion     = int.Parse(dc["ID"].ToString());
                            r.Partida         = dc["Partida"].ToString();
                            r.NumeroDocumento = dc["Numero_x0020_de_x0020_Documento"].ToString();

                            resultados.Add(r);

                            //lblError.Text = lblError.Text + "\n" + fURl.Url.ToString();
                        }

                        gvResultados.DataSource = resultados;
                        gvResultados.DataBind();
                    }
                }
            }
            catch (Exception exc)
            {
                lblError.Text = exc.Message;
            }
        }
Example #42
0
        private static void SetThemeToWebImplementation(this Web web, Web rootWeb, string themeName)
        {
            if (rootWeb == null)
            {
                throw new ArgumentNullException("rootWeb");
            }

            if (string.IsNullOrEmpty(themeName))
            {
                throw new ArgumentNullException("themeName");
            }

            LoggingUtility.Internal.TraceInformation((int)EventId.SetTheme, CoreResources.BrandingExtension_SetTheme, themeName, web.Context.Url);

            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog((int)ListTemplateType.DesignCatalog);

            rootWeb.Context.Load(themeList);
            LoggingUtility.Internal.TraceVerbose("Getting theme list (catalog 124)");
            rootWeb.Context.ExecuteQuery();

            // Double checking that theme exists
            if (rootWeb.ThemeEntryExists(themeName, themeList))
            {
                // Let's update the theme name accordingly
                CamlQuery query = new CamlQuery();
                // Find the theme by themeName
                string camlString = string.Format(CAML_QUERY_FIND_BY_FILENAME, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                rootWeb.Context.Load(found);
                LoggingUtility.Internal.TraceVerbose("Getting theme: {0}", themeName);
                rootWeb.Context.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];

                    //Set the properties for applying custom theme which was just uploaded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = UrlUtility.MakeRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = UrlUtility.MakeRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = UrlUtility.MakeRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    LoggingUtility.Internal.TraceVerbose("Apply theme '{0}', '{1}', '{2}'.", spColorURL, spFontURL, backGroundImage);
                    // Set theme for demonstration
                    // TODO: Why is shareGenerated false? If deploying to root an inheriting, then maybe use shareGenerated = true.
                    web.ApplyTheme(spColorURL,
                                   spFontURL,
                                   backGroundImage,
                                   false);
                    web.Context.ExecuteQuery();
                    LoggingUtility.Internal.TraceVerbose("Theme applied");

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        var masterUrl = UrlUtility.MakeRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);

                        web.SetMasterPageForSiteByUrl(masterUrl);
                        web.SetCustomMasterPageForSiteByUrl(masterUrl);
                    }
                }
                else
                {
                    LoggingUtility.Internal.TraceError((int)EventId.ThemeMissing, CoreResources.BrandingExtension_ThemeMissing, themeName);
                }
            }
            else
            {
                LoggingUtility.Internal.TraceError((int)EventId.ThemeMissing, CoreResources.BrandingExtension_ThemeMissing, themeName);
            }
        }
        /// <summary>
        /// Determines the page layouts in the current web
        /// </summary>
        internal ListItemCollection GetAllPageLayouts()
        {
            try
            {
                var masterPageGallery = _siteCollContext.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                _siteCollContext.Load(masterPageGallery, x => x.RootFolder.ServerRelativeUrl);

                var query = new CamlQuery
                {
                    // Use query Scope='RecursiveAll' to iterate through sub folders of Master page library because we might have file in folder hierarchy
                    // Ensure that we are getting layouts with at least one published version, not hidden layouts
                    ViewXml =
                        $"<View Scope='RecursiveAll'>" +
                        $"<Query>" +
                        $"<Where>" +
                        $"<And>" +
                        $"<Contains>" +
                        $"<FieldRef Name='File_x0020_Type'/><Value Type='Text'>aspx</Value>" +
                        $"</Contains>" +
                        $"<And>" +
                        $"<And>" +
                        $"<Geq>" +
                        $"<FieldRef Name='_UIVersionString'/><Value Type='Text'>1.0</Value>" +
                        $"</Geq>" +
                        $"<BeginsWith>" +
                        $"<FieldRef Name='ContentTypeId'/><Value Type='ContentTypeId'>{Constants.PageLayoutBaseContentTypeId}</Value>" +
                        $"</BeginsWith>" +
                        $"</And>" +
                        $"<Or>" +
                        $"<Eq>" +
                        $"<FieldRef Name='PublishingHidden'/><Value Type='Boolean'>0</Value>" +
                        $"</Eq>" +
                        $"<IsNull>" +
                        $"<FieldRef Name='PublishingHidden'/>" +
                        $"</IsNull>" +
                        $"</Or>" +
                        $"</And>" +
                        $"</And>" +
                        $"</Where>" +
                        $"</Query>" +
                        $"<ViewFields>" +
                        $"<FieldRef Name='{Constants.PublishingAssociatedContentTypeField}' />" +
                        $"<FieldRef Name='PublishingHidden' />" +
                        $"<FieldRef Name='Title' />" +
                        $"</ViewFields>" +
                        $"</View>"
                };

                var galleryItems = masterPageGallery.GetItems(query);
                _siteCollContext.Load(masterPageGallery);
                _siteCollContext.Load(galleryItems);
                _siteCollContext.Load(galleryItems, i => i.Include(o => o.DisplayName),
                                      i => i.Include(o => o.File),
                                      i => i.Include(o => o.File.ServerRelativeUrl));

                _siteCollContext.ExecuteQueryRetry();

                var galleryItemsCount = galleryItems.Count;
                LogInfo(String.Format(LogStrings.AnalyserFoundItems, galleryItemsCount), LogStrings.Heading_PageLayoutAnalyser);

                return(galleryItemsCount > 0 ? galleryItems : null);
            }catch (Exception ex)
            {
                LogError(LogStrings.Error_AnalyserCouldNotFindLayouts, LogStrings.Heading_PageLayoutAnalyser, ex);
            }

            return(null);
        }
Example #44
0
        protected override void ExecuteCmdlet()
        {
            var list = List.GetList(SelectedWeb);

            if (list == null)
            {
                throw new PSArgumentException($"No list found with id, title or url '{List}'", "List");
            }

            if (HasId())
            {
                var listItem = list.GetItemById(Id);
                if (Fields != null)
                {
                    foreach (var field in Fields)
                    {
                        ClientContext.Load(listItem, l => l[field]);
                    }
                }
                else
                {
                    ClientContext.Load(listItem);
                }
                ClientContext.ExecuteQueryRetry();
                WriteObject(listItem);
            }
            else if (HasUniqueId())
            {
                CamlQuery query = new CamlQuery();
                var       viewFieldsStringBuilder = new StringBuilder();
                if (HasFields())
                {
                    viewFieldsStringBuilder.Append("<ViewFields>");
                    foreach (var field in Fields)
                    {
                        viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field);
                    }
                    viewFieldsStringBuilder.Append("</ViewFields>");
                }
                query.ViewXml = $"<View><Query><Where><Eq><FieldRef Name='UniqueId'/><Value Type='Guid'>{UniqueId.Id}</Value></Eq></Where></Query>{viewFieldsStringBuilder}</View>";
                var listItem = list.GetItems(query);
                ClientContext.Load(listItem);
                ClientContext.ExecuteQueryRetry();
                WriteObject(listItem);
            }
            else
            {
                CamlQuery query = HasCamlQuery() ? new CamlQuery {
                    ViewXml = Query
                } : CamlQuery.CreateAllItemsQuery();

                if (Fields != null)
                {
                    var queryElement = XElement.Parse(query.ViewXml);

                    var viewFields = queryElement.Descendants("ViewFields").FirstOrDefault();
                    if (viewFields != null)
                    {
                        viewFields.RemoveAll();
                    }
                    else
                    {
                        viewFields = new XElement("ViewFields");
                        queryElement.Add(viewFields);
                    }

                    foreach (var field in Fields)
                    {
                        XElement viewField = new XElement("FieldRef");
                        viewField.SetAttributeValue("Name", field);
                        viewFields.Add(viewField);
                    }
                    query.ViewXml = queryElement.ToString();
                }

                if (HasPageSize())
                {
                    var queryElement = XElement.Parse(query.ViewXml);

                    var rowLimit = queryElement.Descendants("RowLimit").FirstOrDefault();
                    if (rowLimit != null)
                    {
                        rowLimit.RemoveAll();
                    }
                    else
                    {
                        rowLimit = new XElement("RowLimit");
                        queryElement.Add(rowLimit);
                    }

                    rowLimit.SetAttributeValue("Paged", "TRUE");
                    rowLimit.SetValue(PageSize);

                    query.ViewXml = queryElement.ToString();
                }

                do
                {
                    var listItems = list.GetItems(query);
                    ClientContext.Load(listItems);
                    ClientContext.ExecuteQueryRetry();

                    WriteObject(listItems, true);

                    if (ScriptBlock != null)
                    {
                        ScriptBlock.Invoke(listItems);
                    }

                    query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                } while (query.ListItemCollectionPosition != null);
            }
        }
Example #45
0
        /***********************Uploading Data and Files in Specific List Library*******************/
        public static void UploadFilesAndData(ClientContext clientContext, System.Data.DataTable dataTable)
        {
            Application App1 = new Application();
            //if (System.IO.File.Exists(@"D:\FileUploadData.xlsx"))
            //{
            //    Console.WriteLine("Exists file");
            //}

            Workbook WorkBook1 = (Microsoft.Office.Interop.Excel.Workbook)(App1.Workbooks._Open(ApplicationConfiguration.LocalFilePath + DiskFilePath, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value));

            //int NumberOfWorkbooks = App1.Workbooks.Count;
            Microsoft.Office.Interop.Excel.Worksheet Sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)WorkBook1.Worksheets[1];
            //int NumberOfSheets = WorkBook1.Worksheets.Count;

            try
            {
                if (dataTable.Rows.Count > 0)
                {
                    Console.WriteLine("-------------------Uploading file--------------------");

                    List ExcelFile = clientContext.Web.Lists.GetByTitle("FileUpload");
                    clientContext.Load(ExcelFile);
                    clientContext.ExecuteQuery();

                    Console.WriteLine("List name " + ExcelFile.Title + " desc :" + ExcelFile.Description);

                    /**************Get All Users of Site**************/
                    UserCollection SiteUsers = clientContext.Web.SiteUsers;
                    clientContext.Load(SiteUsers);
                    clientContext.ExecuteQuery();

                    for (int Count = 0; Count < dataTable.Rows.Count; Count++)
                    {
                        try
                        {
                            if (Count > -1)
                            {
                                string LocalFilePath  = dataTable.Rows[Count]["FilePath"].ToString();
                                string StatusList     = dataTable.Rows[Count]["Status"].ToString();
                                string CreatedByEmail = dataTable.Rows[Count]["Created By"].ToString();
                                string Department     = dataTable.Rows[Count]["Dept"].ToString();
                                string UploadStatus   = dataTable.Rows[Count]["Upload Status"].ToString();
                                string Reason         = dataTable.Rows[Count]["Reason"].ToString();
                                long   SizeOfFile     = new System.IO.FileInfo(LocalFilePath.Replace(@"\\", @"\")).Length;

                                /****************Get All Users for that site*************/
                                User CreatedUserObj = SiteUsers.GetByEmail(CreatedByEmail);
                                clientContext.Load(CreatedUserObj);
                                clientContext.ExecuteQuery();

                                /****************Get All Departments from Department List and filter the data*************/
                                List DepartmentList = clientContext.Web.Lists.GetByTitle("Department");
                                clientContext.Load(DepartmentList);
                                clientContext.ExecuteQuery();

                                CamlQuery DepartmentQuery = new CamlQuery();
                                DepartmentQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Department'/><Value Type = 'Text'>" + Department.Trim() + "</Value></Eq></Where></Query><RowLimit></RowLimit></View> ";

                                //var fs = new FileStream(filepath, FileMode.Open);
                                try
                                {
                                    ListItemCollection GetDepartmentByName = DepartmentList.GetItems(DepartmentQuery);
                                    clientContext.Load(GetDepartmentByName);
                                    clientContext.ExecuteQuery();
                                    if (GetDepartmentByName != null && GetDepartmentByName.Count > 0)
                                    {
                                        if (SizeOfFile > 100 && SizeOfFile < 2097150)
                                        {
                                            FileCreationInformation FileToUpload = new FileCreationInformation();
                                            FileToUpload.Content   = System.IO.File.ReadAllBytes(LocalFilePath.Replace(@"\\", @"\"));
                                            FileToUpload.Overwrite = true;
                                            FileToUpload.Url       = Path.Combine("FileUpload/", Path.GetFileName(LocalFilePath.Replace(@"\\", @"\")));
                                            Microsoft.SharePoint.Client.File UploadFile = ExcelFile.RootFolder.Files.Add(FileToUpload);

                                            clientContext.Load(UploadFile);
                                            clientContext.ExecuteQuery();

                                            ListItem UploadItem = UploadFile.ListItemAllFields;

                                            Field Choice = ExcelFile.Fields.GetByInternalNameOrTitle("Status");
                                            clientContext.Load(Choice);
                                            clientContext.ExecuteQuery();
                                            FieldChoice StatusFieldChoice = clientContext.CastTo <FieldChoice>(Choice);
                                            clientContext.Load(StatusFieldChoice);
                                            clientContext.ExecuteQuery();
                                            string[] StatusArray            = StatusList.Split(',');
                                            string   StatusPutSelectedValue = string.Empty;
                                            for (int statusCount = 0; statusCount < StatusArray.Length; statusCount++)
                                            {
                                                if (StatusFieldChoice.Choices.Contains(StatusArray[statusCount]))
                                                {
                                                    if (statusCount == StatusArray.Length - 1)
                                                    {
                                                        StatusPutSelectedValue += StatusArray[statusCount];
                                                    }
                                                    else
                                                    {
                                                        StatusPutSelectedValue += StatusArray[statusCount] + ";";
                                                    }
                                                }
                                            }

                                            UploadItem["CreatedBy"]  = CreatedUserObj.Title;
                                            UploadItem["SizeOfFile"] = SizeOfFile;
                                            UploadItem["FileType"]   = Path.GetExtension(LocalFilePath.Replace(@"\\", @"\"));
                                            UploadItem["Status"]     = StatusPutSelectedValue;
                                            UploadItem["Dept"]       = GetDepartmentByName[0].Id.ToString();;

                                            UploadItem.Update();
                                            clientContext.ExecuteQuery();
                                            Sheet1.Cells[Count + 2, 5] = "Success";
                                            Sheet1.Cells[Count + 2, 6] = "N/A";
                                        }
                                        else
                                        {
                                            Console.WriteLine("File : " + Path.GetFileName(LocalFilePath.Replace(@"\\", @"\")) + " could not be uploaded since file size is not in range");
                                            Sheet1.Cells[Count + 2, 5] = "Error";
                                            Sheet1.Cells[Count + 2, 6] = "File Size Exceeds Specified Range";
                                            /*************Create Custom Exception Object**********/
                                            ApplicationCustomException FileSizeException = new ApplicationCustomException("File Size Exceeds Specified Range");
                                            ErrorWriteToLog.WriteToLogFile(FileSizeException);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Department Not Found in Department List");
                                        Sheet1.Cells[Count + 2, 5] = "Error";
                                        Sheet1.Cells[Count + 2, 6] = "Department Not Found in Department List";
                                        /*************Create Custom Exception Object**********/
                                        ApplicationCustomException DepartmentNotFoundException = new ApplicationCustomException("File Size Exceeds Specified Range");
                                        ErrorWriteToLog.WriteToLogFile(DepartmentNotFoundException);
                                    }
                                }
                                catch (Exception exe)
                                {
                                    Console.WriteLine("Exception : " + exe.Message);
                                    ErrorWriteToLog.WriteToLogFile(exe);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception : " + ex);
                            Sheet1.Cells[Count + 2, 5] = "Error";
                            Sheet1.Cells[Count + 2, 6] = ex.Message;
                            ErrorWriteToLog.WriteToLogFile(ex);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine("Exception :" + ee.Message);
                ErrorWriteToLog.WriteToLogFile(ee);
            }

            WorkBook1.Save();

            WorkBook1.Close(true, ApplicationConfiguration.LocalFilePath + DiskFilePath, System.Reflection.Missing.Value);
            App1.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(App1);

            Marshal.ReleaseComObject(Sheet1);
            Marshal.ReleaseComObject(WorkBook1);
            Marshal.ReleaseComObject(App1);
        }
Example #46
0
        /// <summary>
        /// Analyze the web
        /// </summary>
        /// <param name="cc">ClientContext of the web to be analyzed</param>
        /// <returns>Duration of the analysis</returns>
        public override TimeSpan Analyze(ClientContext cc)
        {
            try
            {
                base.Analyze(cc);

                Web web = cc.Web;
                cc.Web.EnsureProperties(p => p.WebTemplate, p => p.Configuration, p => p.RootFolder);

                var homePageUrl        = web.RootFolder.WelcomePage;
                var listsToScan        = web.GetListsToScan();
                var sitePagesLibraries = listsToScan.Where(p => p.BaseTemplate == (int)ListTemplateType.WebPageLibrary);
                var assetLibraries     = listsToScan.Where(p => p.IsSiteAssetsLibrary == true);

                var librariesToScan = sitePagesLibraries.Union(assetLibraries);

                if (librariesToScan.Count() > 0)
                {
                    foreach (var libraryToScan in librariesToScan)
                    {
                        CamlQuery query = new CamlQuery
                        {
                            ViewXml = CAMLQueryByExtension
                        };
                        var pages = libraryToScan.GetItems(query);
                        web.Context.Load(pages);
                        web.Context.ExecuteQueryRetry();

                        if (pages.FirstOrDefault() != null)
                        {
                            DateTime start;
                            bool     forceCheckout = libraryToScan.ForceCheckout;
                            foreach (var page in pages)
                            {
                                string pageUrl = null;
                                try
                                {
                                    if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString()))
                                    {
                                        pageUrl = page[FileRefField].ToString();
                                    }
                                    else
                                    {
                                        //skip page
                                        continue;
                                    }

                                    start = DateTime.Now;

                                    VisioWebPartScanResult visioWebPartResult = null;

                                    // Get page web parts
                                    var foundWebParts = page.WebParts();
                                    if (foundWebParts != null)
                                    {
                                        // Do we have a visio web part?
                                        var visioParts = foundWebParts.Where(p => p.Type == "Microsoft.Office.Visio.Server.WebControls.VisioWebAccess, Microsoft.Office.Visio.Server, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c").ToList();
                                        if (visioParts.Count > 0)
                                        {
                                            Console.WriteLine($"Visio web part found on page {pageUrl}");

                                            visioWebPartResult = new VisioWebPartScanResult()
                                            {
                                                SiteColUrl = this.SiteCollectionUrl,
                                                SiteURL    = this.SiteUrl,
                                                PageUrl    = pageUrl,
                                                Library    = libraryToScan.RootFolder.ServerRelativeUrl,
                                                WebParts   = foundWebParts,
                                            };

                                            // Get page change information
                                            visioWebPartResult.ModifiedAt = page.LastModifiedDateTime();
                                            visioWebPartResult.ModifiedBy = page.LastModifiedBy();

                                            // Grab this page from the search results to connect view information
                                            // Is this page the web's home page?
                                            bool isHomePage = false;
                                            if (pageUrl.EndsWith(homePageUrl, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                isHomePage = true;
                                            }

                                            string fullPageUrl = $"https://{new Uri(this.SiteCollectionUrl).DnsSafeHost}{pageUrl}";
                                            if (isHomePage)
                                            {
                                                fullPageUrl = this.SiteUrl;
                                            }

                                            var searchPage = this.pageSearchResults.Where(x => x.Values.Contains(fullPageUrl)).FirstOrDefault();
                                            if (searchPage != null)
                                            {
                                                // Recent = last 14 days
                                                visioWebPartResult.ViewsRecent              = searchPage["ViewsRecent"].ToInt32();
                                                visioWebPartResult.ViewsRecentUniqueUsers   = searchPage["ViewsRecentUniqueUsers"].ToInt32();
                                                visioWebPartResult.ViewsLifeTime            = searchPage["ViewsLifeTime"].ToInt32();
                                                visioWebPartResult.ViewsLifeTimeUniqueUsers = searchPage["ViewsLifeTimeUniqueUsers"].ToInt32();
                                            }

                                            if (!this.ScanJob.VisioWebPartScanResults.TryAdd(visioWebPartResult.PageUrl, visioWebPartResult))
                                            {
                                                ScanError error = new ScanError()
                                                {
                                                    Error      = $"Could not add page scan result for {visioWebPartResult.PageUrl}",
                                                    SiteColUrl = this.SiteCollectionUrl,
                                                    SiteURL    = this.SiteUrl,
                                                    Field1     = "PageAnalyzer",
                                                };
                                                this.ScanJob.ScanErrors.Push(error);
                                            }
                                        }
                                    }

                                    var duration = new TimeSpan((DateTime.Now.Subtract(start).Ticks));
                                    Console.WriteLine($"Scan of page {pageUrl} took {duration.Seconds} seconds");
                                }
                                catch (Exception ex)
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = ex.Message,
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "MainPageAnalyzerLoop",
                                        Field2     = ex.StackTrace,
                                        Field3     = pageUrl
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                    Console.WriteLine("Error for page {1}: {0}", ex.Message, pageUrl);
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                this.StopTime = DateTime.Now;
            }

            // return the duration of this scan
            return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks)));
        }
Example #47
0
        public static TokenParser ProcessApps(Tenant tenant, ProvisioningTenant provisioningTenant, FileConnectorBase connector, TokenParser parser, PnPMonitoredScope scope, ProvisioningTemplateApplyingInformation applyingInformation, ProvisioningMessagesDelegate messagesDelegate)
        {
            if (provisioningTenant.AppCatalog != null && provisioningTenant.AppCatalog.Packages.Count > 0)
            {
                var rootSiteUrl = tenant.GetRootSiteUrl();
                tenant.Context.ExecuteQueryRetry();
                using (var context = ((ClientContext)tenant.Context).Clone(rootSiteUrl.Value, applyingInformation.AccessTokens))
                {
                    var web = context.Web;

                    Uri appCatalogUri = null;

                    try
                    {
                        appCatalogUri = web.GetAppCatalog();
                    }
                    catch (System.Net.WebException ex)
                    {
                        if (ex.Response != null)
                        {
                            var httpResponse = ex.Response as System.Net.HttpWebResponse;
                            if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                            {
                                // Ignore any security exception and simply keep
                                // the AppCatalog URI null
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                        else
                        {
                            throw ex;
                        }
                    }

                    if (appCatalogUri != null)
                    {
                        var manager = new AppManager(context);

                        foreach (var app in provisioningTenant.AppCatalog.Packages)
                        {
                            AppMetadata appMetadata = null;

                            if (app.Action == PackageAction.Upload || app.Action == PackageAction.UploadAndPublish)
                            {
                                var appSrc   = parser.ParseString(app.Src);
                                var appBytes = ConnectorFileHelper.GetFileBytes(connector, appSrc);

                                var hash = string.Empty;
                                using (var memoryStream = new MemoryStream(appBytes))
                                {
                                    hash = CalculateHash(memoryStream);
                                }

                                var exists = false;
                                var appId  = Guid.Empty;

                                using (var appCatalogContext = ((ClientContext)tenant.Context).Clone(appCatalogUri, applyingInformation.AccessTokens))
                                {
                                    // check if the app already is present
                                    var appList   = appCatalogContext.Web.GetListByUrl("AppCatalog");
                                    var camlQuery = new CamlQuery
                                    {
                                        ViewXml = string.Format(appExistsQuery, hash)
                                    };
                                    var items = appList.GetItems(camlQuery);
                                    appCatalogContext.Load(items, i => i.IncludeWithDefaultProperties());
                                    appCatalogContext.ExecuteQueryRetry();
                                    if (items.Count > 0)
                                    {
                                        exists = true;
                                        appId  = Guid.Parse(items[0].FieldValues["UniqueId"].ToString());
                                    }
                                }
                                var appFilename = appSrc.Substring(appSrc.LastIndexOf('\\') + 1);

                                if (!exists)
                                {
                                    messagesDelegate?.Invoke($"Processing solution {app.Src}", ProvisioningMessageType.Progress);
                                    appMetadata = manager.Add(appBytes, appFilename, app.Overwrite, timeoutSeconds: 300);
                                }
                                else
                                {
                                    messagesDelegate?.Invoke($"Skipping existing solution {app.Src}", ProvisioningMessageType.Progress);
                                    appMetadata = manager.GetAvailable().FirstOrDefault(a => a.Id == appId);
                                }
                                if (appMetadata != null)
                                {
                                    parser.AddToken(new AppPackageIdToken(web, appFilename, appMetadata.Id));
                                    parser.AddToken(new AppPackageIdToken(web, appMetadata.Title, appMetadata.Id));
                                }
                            }

                            if (app.Action == PackageAction.Publish || app.Action == PackageAction.UploadAndPublish)
                            {
                                if (appMetadata == null)
                                {
                                    appMetadata = manager.GetAvailable()
                                                  .FirstOrDefault(a => a.Id == Guid.Parse(parser.ParseString(app.PackageId)));
                                }
                                if (appMetadata != null)
                                {
                                    manager.Deploy(appMetadata, app.SkipFeatureDeployment);
                                }
                                else
                                {
                                    scope.LogError("Referenced App Package {0} not available", app.PackageId);
                                    throw new Exception($"Referenced App Package {app.PackageId} not available");
                                }
                            }

                            if (app.Action == PackageAction.Remove)
                            {
                                var appId = Guid.Parse(parser.ParseString(app.PackageId));

                                // Get the apps already installed in the site
                                var appExists = manager.GetAvailable()?.Any(a => a.Id == appId);

                                if (appExists.HasValue && appExists.Value)
                                {
                                    manager.Remove(appId);
                                }
                                else
                                {
                                    messagesDelegate?.Invoke($"App Package with ID {appId} does not exist in the AppCatalog and cannot be removed!", ProvisioningMessageType.Warning);
                                }
                            }
                        }
                    }
                    else
                    {
                        messagesDelegate?.Invoke($"Tenant app catalog doesn't exist. ALM step will be skipped!", ProvisioningMessageType.Warning);
                    }
                }
            }
            return(parser);
        }
Example #48
0
        private void GetDcouments()
        {
            Utility.ForceToUseNTLM();

            DataTable  excelTable = new DataTable("LinkResults");
            DataColumn column0    = new DataColumn("File");
            DataColumn column1    = new DataColumn("Link Text");
            DataColumn column2    = new DataColumn("Link Address");

            excelTable.Columns.Add(column0);
            excelTable.Columns.Add(column1);
            excelTable.Columns.Add(column2);

            List <ListItem> itemsList = new List <ListItem>();
            int             rowLimit  = Settings.Default.RowLimit;
            int             pageIndex = 0;

            CamlQuery spQuery = new CamlQuery();

            spQuery.ViewXml = "<View Scope='Recursive'>" +
                              "<Query>" +
                              "<Where>" +
                              "<Or>" +
                              "<Or>" +
                              "<Or>" +
                              "<Eq>" +
                              "<FieldRef Name=\"DocIcon\" />" +
                              "<Value Type=\"Computed\">pptx</Value>" +
                              "</Eq>" +
                              "<Eq>" +
                              "<FieldRef Name=\"DocIcon\" />" +
                              "<Value Type=\"Computed\">docx</Value>" +
                              "</Eq>" +
                              "</Or>" +
                              "<Eq>" +
                              "<FieldRef Name=\"DocIcon\" />" +
                              "<Value Type=\"Computed\">mht</Value>" +
                              "</Eq>" +
                              "</Or>" +
                              "<Eq>" +
                              "<FieldRef Name=\"DocIcon\" />" +
                              "<Value Type=\"Computed\">aspx</Value>" +
                              "</Eq>" +
                              "</Or>" +
                              "</Where>" +
                              "</Query>" +
                              "<RowLimit>" + rowLimit + "</RowLimit>" +
                              "<ViewFields>" +
                              "<FieldRef Name='File_x0020_Type' />" +
                              "<FieldRef Name='FileLeafRef' />" +
                              "<FieldRef Name='FileDirRef' />" +
                              "<FieldRef Name='FileRef' />" +
                              "</ViewFields>" +
                              "</View>";

            do
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    txtProgress.Inlines.Add(new WinDoc.Run()
                    {
                        Text = "Fetching " + (rowLimit * pageIndex + 1) + " to " + rowLimit * (pageIndex + 1) + " documents, please wait...", Foreground = Brushes.Green
                    });
                    txtProgress.Inlines.Add(new WinDoc.LineBreak());
                    svProgress.ScrollToEnd();
                }), null);

                ListItemCollection listItems = spLibrary.GetItems(spQuery);
                spContext.Load(listItems);
                spContext.ExecuteQuery();

                itemsList.AddRange(listItems);

                spQuery.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                pageIndex++;
            } while (spQuery.ListItemCollectionPosition != null);

            int totalCount = itemsList.Count;

            this.Dispatcher.Invoke(new Action(() =>
            {
                txtProgress.Inlines.Add(new WinDoc.Run()
                {
                    Text = "Finish fetching all " + totalCount + " documents, will extract links from these documents.", Foreground = Brushes.Green
                });
                txtProgress.Inlines.Add(new WinDoc.LineBreak());
                svProgress.ScrollToEnd();
            }), null);

            int fileIndex = 1;

            string siteRootURL = string.Empty;

            if (siteURI.Port == 80)
            {
                siteRootURL = siteURI.Scheme + "://" + siteURI.Host;
            }
            else
            {
                siteRootURL = siteURI.Scheme + "://" + siteURI.Host + ":" + siteURI.Port;
            }

            ParserFacade facade = new ParserFacade();

            foreach (ListItem item in itemsList)
            {
                if (item.FileSystemObjectType == FileSystemObjectType.File)
                {
                    string fileName = item.FieldValues["FileLeafRef"].ToString();
                    string fileUri  = siteRootURL + (string)item.FieldValues["FileRef"];

                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        txtProgress.Inlines.Add(new WinDoc.Run()
                        {
                            Text = fileIndex + "/" + totalCount + " -> " + fileName
                        });
                        txtProgress.Inlines.Add(new WinDoc.LineBreak());
                        svProgress.ScrollToEnd();
                    }), null);

                    fileIndex++;

                    facade.ParseFile(fileUri);
                }
            }

            List <FileLink> results        = facade.GetParseResult();
            int             linkIndex      = 1;
            int             totalLinkCount = results.Count;

//#if DEBUG
//            string filePathAllResults = Environment.CurrentDirectory + "\\" + libriaryName + "_allResults.csv";

//            if (!System.IO.File.Exists(filePathAllResults))
//            {
//                System.IO.File.Create(filePathAllResults).Close();
//            }

//            using (System.IO.TextWriter writer = System.IO.File.CreateText(filePathAllResults))
//            {
//                for (int index = 0; index < totalLinkCount; index++)
//                {
//                    writer.WriteLine(string.Join(",", results[index].LinkAddress));
//                }
//            }
//#endif

            this.Dispatcher.Invoke(new Action(() =>
            {
                txtProgress.Inlines.Add(new WinDoc.Run()
                {
                    Text = "There are " + totalLinkCount + " links to be valided, please wait...", Foreground = Brushes.Green
                });
                txtProgress.Inlines.Add(new WinDoc.LineBreak());
                svProgress.ScrollToEnd();
            }), null);

            foreach (FileLink fileLink in results)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    txtProgress.Inlines.Add(new WinDoc.Run()
                    {
                        Text = linkIndex + "/" + totalLinkCount + " -> " + (fileLink.hasError ? "Invalid link" : fileLink.LinkAddress)
                    });
                    txtProgress.Inlines.Add(new WinDoc.LineBreak());
                    svProgress.ScrollToEnd();
                }), null);

                linkIndex++;

                if (brokenLinksFound.Contains(fileLink.LinkAddress))
                {
                    CreateExcelRow(fileLink.ParentFileUrl, fileLink.LinkText, fileLink.LinkAddress, excelTable);
                }
                else
                {
                    if (!UrlIsValid(fileLink))
                    {
                        brokenLinksFound.Add(fileLink.LinkAddress);
                        CreateExcelRow(fileLink.ParentFileUrl, fileLink.LinkText, fileLink.LinkAddress, excelTable);
                    }
                }
            }

            this.Dispatcher.Invoke(new Action(() =>
            {
                txtProgress.Inlines.Add(new WinDoc.Run()
                {
                    Text = "Finish validing links and writing results into excel, please waiting...", Foreground = Brushes.Green
                });
                txtProgress.Inlines.Add(new WinDoc.LineBreak());
                svProgress.ScrollToEnd();
            }), null);

            try
            {
                string logPath = Environment.CurrentDirectory + "\\" + libriaryName + "_Results_" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx";

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

                FileInfo logFile = new FileInfo(logPath);

                using (ExcelPackage pck = new ExcelPackage(logFile))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Broken Links");
                    ws.Cells["A1"].LoadFromDataTable(excelTable, true);
                    pck.Save();
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    txtProgress.Inlines.Add(new WinDoc.Run()
                    {
                        Text = "Finished, please open below excel report to view results.", Foreground = Brushes.Green
                    });
                    txtProgress.Inlines.Add(new WinDoc.LineBreak());
                    svProgress.ScrollToEnd();

                    logSP.Visibility      = Visibility.Visible;
                    WinDoc.Hyperlink link = new WinDoc.Hyperlink(new WinDoc.Run(logPath));
                    link.NavigateUri      = new Uri(logPath);
                    link.RequestNavigate += delegate(object sender, RequestNavigateEventArgs e)
                    {
                        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
                        e.Handled = true;
                    };
                    LogLink.Inlines.Add(link);
                }), null);
            }
            catch
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    txtProgress.Inlines.Add(new WinDoc.Run()
                    {
                        Text = "Writing results to excel file failed.", Foreground = Brushes.Red
                    });
                    txtProgress.Inlines.Add(new WinDoc.LineBreak());
                    svProgress.ScrollToEnd();
                }), null);
            }

            TimerStop();
        }
Example #49
0
        static bool loadPages(ClientContext ctx, ListCollection sitePagesList)
        {
            bool retVal = false;

            try
            {
                sitePages = sitePagesList.Where(l => l.EntityTypeName == "SitePages").Single();
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View Scope='RecursiveAll'><RowLimit>5000</RowLimit></View>";
                ListItemCollection pages = sitePages.GetItems(camlQuery);
                ctx.Load(pages, ps => ps.Include(
                             p => p.FileSystemObjectType,
                             p => p.Id,
                             p => p["UniqueId"],
                             p => p.File,
                             p => p["Title"],
                             p => p["MasterTranslationPage"],
                             p => p["LanguageVariant"],
                             p => p["FileLeafRef"],
                             p => p["FileRef"],
                             p => p["LanguageFolder"]
                             )
                         );
                ctx.ExecuteQuery();
                if (pages.Count > 0)
                {
                    log.Log("loadPages", Severity.Info, $"Site pages loaded.");
                }
                else
                {
                    log.Log("loadPages", Severity.Error, $"No Site pages were found.");
                    return(retVal);
                }

                foreach (var sitePage in pages)
                {
                    log.Log("loadPages", Severity.Info, $"Loaded {sitePage.Id.ToString()} - {sitePage["FileRef"].ToString()} - {sitePage["MasterTranslationPage"]}");
                    if (sitePage["LanguageFolder"] != null && sitePage["LanguageFolder"].ToString().ToLower() == "zh-hans")
                    {
                        log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()}changing chinese folder name to zh-cn.");
                        sitePage["LanguageFolder"] = "zh-cn";
                    }

                    if (sitePage.FileSystemObjectType == FileSystemObjectType.Folder)
                    {
                        if (sitePage["FileLeafRef"].ToString().Length <= 7 && sitePage["FileLeafRef"].ToString().Substring(2, 1) == "-")
                        {
                            folders.Add(sitePage);
                            log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()} added to folders.");
                        }
                        else
                        {
                            log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()} skipped.");
                        }
                    }
                    else if (sitePage["MasterTranslationPage"] != null)
                    {
                        //if (sitePage["MasterTranslationPage"].ToString() == sitePage.Id.ToString())
                        if (sitePage["LanguageFolder"] == null || sitePage["LanguageFolder"].ToString().ToLower() == defaultLanguage)
                        {
                            masterPages.Add(sitePage);
                            log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()} added to master pages.");
                        }
                        else
                        {
                            translationsPages.Add(sitePage);
                            log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()} added to translation pages.");
                        }
                    }
                    else
                    {
                        log.Log("loadPages", Severity.Info, $"{sitePage["FileLeafRef"].ToString()} skipped.");
                    }
                }

                retVal = true;
            }
            catch (Exception ex)
            {
                log.Log("loadPages", Severity.Exception, $"Exception {ex.Message} - {ex.StackTrace}");
            }
            return(retVal);
        }
Example #50
0
        protected virtual void InitShadowFileSystem()
        {
            // essentially, a cache over list items to avoid repeable queries
            WithSPContext(context =>
            {
                var web  = context.Web;
                var list = LoadListByUrl(context.Web, LibraryUrl);

                var camlQuery = new CamlQuery()
                {
                    ViewXml = string.Format("<View Scope='RecursiveAll'>{0}</View>", Strings.NuPkgCamlQuery)
                };

                var files = list.GetItems(camlQuery);

                context.Load(files);
                context.ExecuteQuery();

                foreach (var file in files)
                {
                    var filePath = (string)file["FileRef"];
                    var created  = (DateTime)file["Created"];
                    var version  = (string)file["PackageVersion"];
                    var id       = (string)file["PackageId"];
                    //var nuspecXml = (string)file["NuspecXml"];

                    //filePath = filePath.Replace("/" + LibraryUrl, string.Empty)
                    //                   .ToLower();
                    filePath = filePath.ToLower();

                    var existingShadowFile = _shadowFiles.FirstOrDefault(f => f.Path == filePath);

                    if (existingShadowFile == null)
                    {
                        existingShadowFile = new VirtualFile
                        {
                            Path             = filePath,
                            Created          = created,
                            PackageVersion   = version,
                            PackageId        = id,
                            PackageNuSpecXml = string.Empty,
                        };

                        _shadowFiles.Add(existingShadowFile);
                    }
                    else
                    {
                        existingShadowFile.Path    = filePath;
                        existingShadowFile.Created = created;
                    }
                }
            });

            var packageIds = _shadowFiles.GroupBy(f => f.PackageId)
                             .Where(s => !string.IsNullOrEmpty(s.Key))
                             .Select(s => s.Key)
                             .Distinct();

            var topPackages = new List <VirtualFile>();

            foreach (var packageId in packageIds)
            {
                var topPackage = _shadowFiles.Where(f => f.PackageId == packageId)
                                 .OrderByDescending(f =>
                {
                    if (!string.IsNullOrEmpty(f.PackageVersion))
                    {
                        return(new SemanticVersion(f.PackageVersion));
                    }

                    return(new SemanticVersion("0.0.0.0"));
                })
                                 .FirstOrDefault();

                if (topPackage != null)
                {
                    topPackages.Add(topPackage);
                }
            }

            topPackages = topPackages.OrderBy(p => p.PackageId)
                          .ToList();

            // trim to get only latest versions
            _shadowFiles = topPackages.ToList();
        }
Example #51
0
        // Delete Method via Criteria
        private void DeletionProcessCriteria()
        {
            if (cboSiteList.SelectedItem.ToString().Contains("Archive"))
            {
                MessageBox.Show("Cannot delete items from an archive list.");
            }

            else
            {
                try
                {
                    // ***************************** SP ONLINE LIST(S) ***********************************
                    if (IsSPOnline == true)
                    {
                        SPOnlineContext = ClaimClientContext.GetAuthenticatedContext(cboSiteURL.SelectedItem.ToString());
                        SP.List selectedList = SPOnlineContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View>" +
                                            "<Query>" +
                                            "<Where>" +
                                            "<And>" +
                                            "<Geq>" +
                                            "<FieldRef Name='From' />" +
                                            "<Value Type='DateTime'>2017-01-01</Value>" +
                                            "</Geq>" +
                                            "<Leq>" +
                                            "<FieldRef Name='From' />" +
                                            "<Value Type='DateTime'>2017-12-31</Value>" +
                                            "</Leq>" +
                                            "</And>" +
                                            "</Where>" +
                                            "</Query>" +
                                            "</View>";

                        ListItemCollection oListitemCollection = selectedList.GetItems(camlQuery);
                        SPOnlineContext.Load(oListitemCollection);
                        SPOnlineContext.ExecuteQuery();

                        int listCount = oListitemCollection.Count;

                        foreach (ListItem sourceListItem in oListitemCollection)
                        {
                            SP.List destinationList = SPOnlineContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem destinationListItem = destinationList.AddItem(itemCreateInfo);

                            switch (cboSiteList.SelectedItem.ToString())
                            {
                            case "All Grant Submitssss":

                                for (int i = 0; i < listCount; i++)
                                {
                                    var item = oListitemCollection[i]; // In order to prevent changes in all places inside the [for loop]
                                    item.DeleteObject();
                                    listCount--;                       // Here, as I am removing 1 item, I am decrementing the count
                                    i--;

                                    // Executes the clientContext.ExecuteQuery() inside the loop to prevent the
                                    // 'The request uses too many resources' error.
                                    selectedList.Update();
                                    SPOnlineContext.ExecuteQuery();

                                    //MessageBox.Show("Deletion in Progress ...");
                                }

                                selectedList.Update();
                                SPOnlineContext.ExecuteQuery();
                                //int endCount = oListitemCollection.Count;

                                break;
                            }// END Switch
                        }

                        MessageBox.Show("Deletion Completed!");
                    }

                    else
                    {
                        // ***************************** SP ON-PREM LIST(S) ***********************************
                        // SP ON PREM Selections
                        SPOnPremContext = new ClientContext(cboSiteURL.SelectedItem.ToString());
                        SP.List selectedList = SPOnPremContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                        string fromDate = metroDateTimeFrom.Value.ToString("yyyy-MM-dd");
                        string toDate   = metroDateTimeTo.Value.ToString("yyyy-MM-dd");

                        // The following example displays the Items Created less than or earlier to 20XX
                        // This CAMLQUERY is used for ClockInOutLog List
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View><Query><Where><Lt><FieldRef Name='Created'/>" +
                                            "<Value Type='DateTime'>" + fromDate + "</Value></Lt></Where></Query><RowLimit>200</RowLimit></View>";

                        ListItemCollection oListitemCollection = selectedList.GetItems(camlQuery);
                        SPOnPremContext.Load(oListitemCollection);
                        SPOnPremContext.ExecuteQuery();

                        int listCount = oListitemCollection.Count;

                        foreach (ListItem sourceListItem in oListitemCollection)
                        {
                            SP.List destinationList = SPOnPremContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());

                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem destinationListItem = destinationList.AddItem(itemCreateInfo);

                            switch (cboSiteList.SelectedItem.ToString())
                            {
                            case "ClockInOutLog":

                                for (int i = 0; i < listCount; i++)
                                {
                                    var item = oListitemCollection[i]; // In order to prevent changes in all places inside the [for loop]
                                    item.DeleteObject();
                                    listCount--;                       // Here, as I am removing 1 item, I am decrementing the count
                                    i--;

                                    // Executes the clientContext.ExecuteQuery() inside the loop to prevent the
                                    // 'The request uses too many resources' error.
                                    selectedList.Update();
                                    SPOnPremContext.ExecuteQuery();

                                    //MessageBox.Show("Deletion in Progress ...");
                                    //TODO: Need Progressbar here
                                }

                                selectedList.Update();
                                SPOnPremContext.ExecuteQuery();
                                //int endCount = oListitemCollection.Count;

                                break;

                            case "TrackEmployeeTasks":

                                for (int i = 0; i < listCount; i++)
                                {
                                    var item = oListitemCollection[i]; // In order to prevent changes in all places inside the [for loop]
                                    item.DeleteObject();
                                    listCount--;                       // Here, as I am removing 1 item, I am decrementing the count
                                    i--;

                                    // Executes the clientContext.ExecuteQuery() inside the loop to prevent the
                                    // 'The request uses too many resources' error.
                                    selectedList.Update();
                                    SPOnPremContext.ExecuteQuery();

                                    //MessageBox.Show("Deletion in Progress ...");
                                    //TODO: Need Progressbar here
                                }

                                selectedList.Update();
                                SPOnPremContext.ExecuteQuery();

                                break;
                            }// END Switch
                        }

                        MessageBox.Show("Deletion Completed!");

                        // Populate DGV - Refresh!!
                        PopulateDGV();
                    }
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                    MessageBox.Show("Error Encountered " + ex.Message);
                }
            }
        }
        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();
        }
Example #53
0
        // Populate DataGridview
        private void PopulateDGV()
        {
            try
            {
                // ******************** POPULATE DATAGRIDVIEW VIA SP ON-PREM ***************************

                if (IsSPOnline == false)
                {
                    List      list  = SPOnPremContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = "<View/>";
                    ListItemCollection items = list.GetItems(query);

                    SPOnPremContext.Load(list);
                    SPOnPremContext.Load(items);

                    SPOnPremContext.ExecuteQuery();

                    string selectedList = cboSiteList.SelectedItem.ToString();

                    switch (selectedList)
                    {
                    default:
                        DataTable table = new DataTable();
                        table.Columns.Add("Title");

                        foreach (ListItem item in items)
                        {
                            table.Rows.Add(item["Title"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource    = table;
                        lblListitemsCountAmt.Text = items.Count.ToString();

                        break;

                    case "ClockInOutLog":
                        // Show the data
                        DataTable tableCIOLog = new DataTable();
                        tableCIOLog.Columns.Add("Title");
                        tableCIOLog.Columns.Add("Status");
                        tableCIOLog.Columns.Add("Time");
                        tableCIOLog.Columns.Add("Notes");

                        foreach (ListItem item in items)
                        {
                            tableCIOLog.Rows.Add(item["Title"], item["Status"], item["Time"], item["Notes"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableCIOLog;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "Leave Requests":
                        // Show the data
                        DataTable tableLR = new DataTable();
                        tableLR.Columns.Add("Request For");
                        tableLR.Columns.Add("Title");
                        tableLR.Columns.Add("Status");
                        tableLR.Columns.Add("Leave Code");
                        tableLR.Columns.Add("From");
                        tableLR.Columns.Add("To");
                        tableLR.Columns.Add("Requested Hours");
                        tableLR.Columns.Add("Notes");

                        foreach (ListItem item in items)
                        {
                            try
                            {
                                if (((FieldUserValue)item["Request_x0020_For"]).LookupValue.ToString() != null)
                                {
                                    tableLR.Rows.Add(((FieldUserValue)item["Request_x0020_For"]).LookupValue, item["Title"], item["Status"],
                                                     ((FieldLookupValue)item["Leave_x0020_Code"]).LookupValue, item["From"], item["To"],
                                                     item["Requested_x0020_Hours"], item["Notes"]);
                                }

                                else
                                {
                                    string missingNameValue = "Missing Name";
                                    tableLR.Rows.Add(missingNameValue, item["Title"], item["Status"],
                                                     ((FieldLookupValue)item["Leave_x0020_Code"]).LookupValue, item["From"], item["To"],
                                                     item["Requested_x0020_Hours"], item["Notes"]);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableLR;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "Overtime Requests":
                        // Show the data
                        DataTable tableOR = new DataTable();
                        tableOR.Columns.Add("Request For");
                        tableOR.Columns.Add("Title");
                        tableOR.Columns.Add("Status");
                        tableOR.Columns.Add("Overtime Code");
                        tableOR.Columns.Add("From");
                        tableOR.Columns.Add("To");
                        tableOR.Columns.Add("Requested Hours");
                        tableOR.Columns.Add("Notes");

                        foreach (ListItem item in items)
                        {
                            try
                            {
                                if (((FieldUserValue)item["Request_x0020_For"]).LookupValue.ToString() != null)
                                {
                                    tableOR.Rows.Add(((FieldUserValue)item["Request_x0020_For"]).LookupValue, item["Title"], item["Status"],
                                                     ((FieldLookupValue)item["Overtime_x0020_Code"]).LookupValue, item["From"], item["To"],
                                                     item["Requested_x0020_Hours"], item["Notes"]);
                                }
                                else
                                {
                                    string missingNameValue = "Missing Name";
                                    tableOR.Rows.Add(missingNameValue, item["Title"], item["Status"],
                                                     ((FieldLookupValue)item["Overtime_x0020_Code"]).LookupValue, item["From"], item["To"],
                                                     item["Requested_x0020_Hours"], item["Notes"]);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableOR;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "CADD Office Leave Calendar":
                        // Show the data
                        DataTable tableCOLC = new DataTable();
                        tableCOLC.Columns.Add("Title");
                        tableCOLC.Columns.Add("Status");
                        tableCOLC.Columns.Add("Requested Hours");
                        tableCOLC.Columns.Add("Start Time");
                        tableCOLC.Columns.Add("End Time");

                        foreach (ListItem item in items)
                        {
                            tableCOLC.Rows.Add(item["Title"], item["Status"], item["Requested_x0020_Hours"],
                                               item["EventDate"], item["EndDate"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableCOLC;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "TrackEmployeeTasks":
                        // Show the data
                        DataTable tableTET = new DataTable();
                        tableTET.Columns.Add("Created By");
                        tableTET.Columns.Add("Start");
                        tableTET.Columns.Add("End");
                        tableTET.Columns.Add("Title");
                        tableTET.Columns.Add("Notes");
                        tableTET.Columns.Add("TotalTaskTime");
                        tableTET.Columns.Add("Created");

                        foreach (ListItem item in items)
                        {
                            tableTET.Rows.Add(((FieldUserValue)item["Author"]).LookupValue, item["Start"], item["End"],
                                              item["Title"], item["Notes"], item["TotalTaskTime"], item["Created"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableTET;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;
                    } // END ON PREM SWITCH
                }     // END IF

                // ******************** POPULATE DATAGRIDVIEW VIA SP ONLINE ***************************
                else
                {
                    MessageBox.Show("Retrieving via SharePoint Online ...");

                    SPOnlineContext = ClaimClientContext.GetAuthenticatedContext(cboSiteURL.SelectedItem.ToString());

                    //Get the site
                    Web site = SPOnlineContext.Web;
                    SPOnlineContext.Load(site);
                    //Get Lists
                    SPOnlineContext.Load(site.Lists);
                    // Execute
                    SPOnlineContext.ExecuteQuery();


                    List      _list = SPOnlineContext.Web.Lists.GetByTitle(cboSiteList.SelectedItem.ToString());
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = "<View/>";
                    ListItemCollection items = _list.GetItems(query);

                    SPOnlineContext.Load(items);
                    SPOnlineContext.ExecuteQuery();

                    string selectedList = cboSiteList.SelectedItem.ToString();

                    switch (selectedList)
                    {
                    default:
                        DataTable table = new DataTable();
                        table.Columns.Add("Title");

                        foreach (ListItem item in items)
                        {
                            table.Rows.Add(item["Title"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource    = table;
                        lblListitemsCountAmt.Text = items.Count.ToString();

                        break;

                    case "All Grant Submits":
                        // Show the data
                        DataTable tableAGS = new DataTable();
                        //table.Columns.Add("Id");
                        tableAGS.Columns.Add("Name(Grant/Municipality)");
                        tableAGS.Columns.Add("Contact Name");
                        tableAGS.Columns.Add("Email");
                        tableAGS.Columns.Add("Phone");
                        tableAGS.Columns.Add("District");
                        tableAGS.Columns.Add("Comments");

                        foreach (ListItem item in items)
                        {
                            tableAGS.Rows.Add(item["Title"], item["Contact_x0020_Name"], item["Email"], item["Phone"],
                                              ((FieldLookupValue)item["District"]).LookupValue, item["Comments"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableAGS;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "AllGrantSubmits":
                        // Show the data
                        DataTable tableAGSs = new DataTable();
                        //table.Columns.Add("Id");
                        tableAGSs.Columns.Add("Name(Grant/Municipality)");
                        tableAGSs.Columns.Add("Contact Name");
                        tableAGSs.Columns.Add("Email");
                        tableAGSs.Columns.Add("Phone");
                        tableAGSs.Columns.Add("District");
                        tableAGSs.Columns.Add("Comments");

                        foreach (ListItem item in items)
                        {
                            tableAGSs.Rows.Add(item["Title"], item["Contact_x0020_Name"], item["Email"], item["Phone"],
                                               ((FieldLookupValue)item["District"]).LookupValue, item["Comments"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableAGSs;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;

                    case "AllGrantSubmits-Archive2017":
                        // Show the data
                        DataTable tableAGSArchive17 = new DataTable();
                        //table.Columns.Add("Id");
                        tableAGSArchive17.Columns.Add("Name(Grant/Municipality)");
                        tableAGSArchive17.Columns.Add("Contact Name");
                        tableAGSArchive17.Columns.Add("Email");
                        tableAGSArchive17.Columns.Add("Phone");
                        tableAGSArchive17.Columns.Add("District");
                        tableAGSArchive17.Columns.Add("Comments");

                        foreach (ListItem item in items)
                        {
                            tableAGSArchive17.Rows.Add(item["Title"], item["Contact_x0020_Name"], item["Email"], item["Phone"],
                                                       ((FieldLookupValue)item["District"]).LookupValue, item["Comments"]);
                        }

                        // Bind data to datagridView
                        listDataDGV.DataSource = tableAGSArchive17;
                        listDataDGV.AutoResizeColumns();                                            // Resize the DataGridView columns to fit the newly loaded data.
                        listDataDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // Columns automatically adjust their widths when the data changes.
                        lblListitemsCountAmt.Text       = items.Count.ToString();

                        break;
                    } //END ON LINE SWITCH
                }     //END ELSE
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Action for this SharePoint folder
        /// </summary>
        public override void Process()
        {
            RunningManager.Logger.Debug($"FolderRunner Process() - {ActiveReceivers.Count} active receivers");
            Context.Load(Element,
                         f => f.Name,
                         f => f.ServerRelativeUrl,
                         f => f.ListItemAllFields["FileRef"],
                         f => f.ListItemAllFields.ParentList.ItemCount);
            Context.ExecuteQuery();
            RunningManager.Logger.Debug($"Folder | Name: {Element.Name} / URL: {Element.ServerRelativeUrl}");

            // OnFolderRunningStart
            RunningManager.Logger.Debug("FolderRunner OnFolderRunningStart()");
            ActiveReceivers.ForEach(r => r.OnFolderRunningStart(Element));

            // If at least one receiver run list items of deeper
            if (Manager.Receivers.Any(r => r.IsReceiverCalledOrDeeper(RunningLevel.ListItem)))
            {
                List <ListItem> items = new List <ListItem>();

                if (Element.ListItemAllFields.ParentList.ItemCount > 5000)
                {
                    // Manage large lists
                    int count     = 0;
                    int inter     = 1000;
                    int countList = Element.ListItemAllFields.ParentList.ItemCount;

                    while (count < countList)
                    {
                        CamlQuery itemsQuery = new CamlQuery()
                        {
                            FolderServerRelativeUrl = Element.ListItemAllFields["FileRef"].ToString(),
                            ViewXml = $"<View><Query><Where><And><Gt><FieldRef Name='ID'/><Value Type='Counter'>{count}</Value></Gt><Leq><FieldRef Name='ID'/><Value Type='Counter'>{count + inter}</Value></Leq></And></Where><OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy></Query></View><RowLimit>{inter}</RowLimit>"
                        };

                        ListItemCollection itemsResult = Element.ListItemAllFields.ParentList.GetItems(itemsQuery);
                        Context.Load(itemsResult);
                        Context.ExecuteQuery();
                        items.AddRange(itemsResult);

                        count += inter;
                    }
                }
                else
                {
                    CamlQuery itemsQuery = new CamlQuery()
                    {
                        FolderServerRelativeUrl = Element.ListItemAllFields["FileRef"].ToString(),
                        ViewXml = "<View><Query></Query></View>"
                    };

                    ListItemCollection itemsResult = Element.ListItemAllFields.ParentList.GetItems(itemsQuery);
                    Context.Load(itemsResult);
                    Context.ExecuteQuery();
                    items = itemsResult.ToList();
                }

                List <ListItemRunner> itemRunners = new List <ListItemRunner>();
                foreach (ListItem item in items)
                {
                    itemRunners.Add(new ListItemRunner(Manager, Context, item));
                }

                itemRunners.ForEach(r => r.Process());
            }

            // OnFolderRunningEnd
            RunningManager.Logger.Debug("FolderRunner OnFolderRunningEnd()");
            ActiveReceivers.ForEach(r => r.OnFolderRunningEnd(Element));

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

            if (Element.ListItemAllFields.ParentList.ItemCount > 5000)
            {
                // Manage large lists
                int count     = 0;
                int inter     = 1000;
                int countList = Element.ListItemAllFields.ParentList.ItemCount;

                while (count < countList)
                {
                    CamlQuery subFoldersQuery = new CamlQuery()
                    {
                        FolderServerRelativeUrl = Element.ListItemAllFields["FileRef"].ToString(),
                        ViewXml = $"<View><Query><Where><And><And><Gt><FieldRef Name='ID'/><Value Type='Counter'>{count}</Value></Gt><Leq><FieldRef Name='ID'/><Value Type='Counter'>{count + inter}</Value></Leq></And><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></And></Where><OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy></Query></View><RowLimit>{inter}</RowLimit>"
                    };

                    ListItemCollection subFoldersResult = Element.ListItemAllFields.ParentList.GetItems(subFoldersQuery);
                    Context.Load(subFoldersResult);
                    Context.ExecuteQuery();
                    subFolders.AddRange(subFoldersResult);

                    count += inter;
                }
            }
            else
            {
                CamlQuery subFoldersQuery = new CamlQuery()
                {
                    FolderServerRelativeUrl = Element.ListItemAllFields["FileRef"].ToString(),
                    ViewXml = "<View><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where></Query></View>"
                };

                // Crawl sub folders
                ListItemCollection subFoldersResult = Element.ListItemAllFields.ParentList.GetItems(subFoldersQuery);
                Context.Load(subFoldersResult,
                             coll => coll.Include(
                                 f => f.Folder));
                Context.ExecuteQuery();
                subFolders = subFoldersResult.ToList();
            }

            List <FolderRunner> folderRunners = new List <FolderRunner>();

            foreach (ListItem folder in subFolders)
            {
                folderRunners.Add(new FolderRunner(Manager, Context, folder.Folder));
            }

            folderRunners.ForEach(r => r.Process());

            // OnFolderRunningEndAfterSubFolders
            RunningManager.Logger.Debug("FolderRunner OnFolderRunningEndAfterSubFolders()");
            ActiveReceivers.ForEach(r => r.OnFolderRunningEndAfterSubFolders(Element));
        }
Example #55
0
        //Get Excel file Details
        public static void GetExcelFileDetails(ClientContext ClientContext)
        {
            List      Empoyeelist = ClientContext.Web.Lists.GetByTitle("UserDocuments");
            CamlQuery CamlQuery1  = new CamlQuery();

            CamlQuery1.ViewXml = "<View><RowLimit></RowLimit></View>";

            ListItemCollection EmpCollection = Empoyeelist.GetItems(CamlQuery1);

            ClientContext.Load(EmpCollection);
            ClientContext.ExecuteQuery();

            Microsoft.SharePoint.Client.File ExcelFile = EmpCollection[0].File;
            ClientContext.Load(ExcelFile);
            ClientContext.ExecuteQuery();
            var FilePath1 = EmpCollection[0].File.ServerRelativeUrl;
            var FileInfo1 = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ClientContext, FilePath1);

            if (ExcelFile != null)
            {
                //  DiskFilePath = LocalFilePath + EmpCollection[0].File.Name;
                try
                {
                    var fileName = Path.Combine(ApplicationConfiguration.LocalFilePath + DiskFilePath, (string)EmpCollection[0].File.Name);
                    DiskFilePath = EmpCollection[0].File.Name;
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }

                    /****************Creates File in the specified path*****************/
                    using (var FileStream1 = System.IO.File.Create(fileName))
                    {
                        FileInfo1.Stream.CopyTo(FileStream1);
                        FileInfo1.Stream.Close();
                        FileStream1.Dispose();
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Exception exc : " + exc.Message);
                    ErrorWriteToLog.WriteToLogFile(exc);
                }
            }

            string StrErrorMsg = string.Empty;

            /*************************DataSet Different Approcach***************************************/

            /*************************DataSet Different Approcach***************************************/
            try
            {
                ExcelDataTable = new System.Data.DataTable("ExcelFileDataTable");

                ClientResult <System.IO.Stream> Data = ExcelFile.OpenBinaryStream();
                ClientContext.Load(ExcelFile);
                ClientContext.ExecuteQuery();
                using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
                {
                    if (Data != null)
                    {
                        Data.Value.CopyTo(mStream);
                        using (SpreadsheetDocument Document1 = SpreadsheetDocument.Open(mStream, false))
                        {
                            IEnumerable <Sheet> Sheets1      = Document1.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>();
                            string            RelationshipId = Sheets1.First().Id.Value;
                            WorksheetPart     WorksheetPart1 = (WorksheetPart)Document1.WorkbookPart.GetPartById(RelationshipId);
                            Worksheet         WorkSheet1     = WorksheetPart1.Worksheet;
                            SheetData         SheetData1     = WorkSheet1.GetFirstChild <SheetData>();
                            IEnumerable <Row> Rows           = SheetData1.Descendants <Row>();
                            foreach (Cell Cell1 in Rows.ElementAt(0))
                            {
                                string StrCellValue = GetCellValue(ClientContext, Document1, Cell1);
                                ExcelDataTable.Columns.Add(StrCellValue);
                            }
                            foreach (Row RowLoop in Rows)
                            {
                                if (RowLoop != null)
                                {
                                    DataRow DataRow1 = ExcelDataTable.NewRow();
                                    for (int iterator = 0; iterator < RowLoop.Descendants <Cell>().Count(); iterator++)
                                    {
                                        DataRow1[iterator] = GetCellValue(ClientContext, Document1, RowLoop.Descendants <Cell>().ElementAt(iterator));
                                    }
                                    ExcelDataTable.Rows.Add(DataRow1);
                                }
                            }
                            ExcelDataTable.Rows.RemoveAt(0);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception exx " + e);
                ErrorWriteToLog.WriteToLogFile(e);
            }
        }
 public IEnumerable <TEntity> Where(CamlQuery query)
 {
     throw new NotImplementedException();
 }
Example #57
0
        ///// <summary>
        ///// Handles the ItemAdded event by modifying the Description
        ///// field of the item.
        ///// </summary>
        ///// <param name="properties"></param>
        private void UpdateDefaultValuesAdding(SPRemoteEventProperties properties, SPRemoteEventResult result)
        {
            using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
            {
                if (clientContext != null)
                {
                    var    itemProperties   = properties.ItemEventProperties;
                    var    _userLoginName   = properties.ItemEventProperties.UserLoginName;
                    var    _afterProperites = itemProperties.AfterProperties;
                    string phase            = "";

                    List list = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
                    //ListItem item = list.GetItemById(properties.ItemEventProperties.ListItemId);
                    FieldCollection fields = list.Fields;
                    //clientContext.Load(item);
                    clientContext.Load(fields);
                    clientContext.ExecuteQuery();

                    string[] folderNameSplit = itemProperties.BeforeUrl.ToString().Split('/');
                    string   folderName      = folderNameSplit[folderNameSplit.Length - 2];
                    string   code            = folderName.Split('_').First();

                    string      lookupFieldName = "Phase";
                    FieldLookup lookupField     = clientContext.CastTo <FieldLookup>(fields.GetByInternalNameOrTitle(lookupFieldName));
                    clientContext.Load(lookupField);
                    clientContext.ExecuteQuery();

                    Guid   parentWeb      = lookupField.LookupWebId;
                    string parentListGUID = lookupField.LookupList;

                    Web  lookupListWeb = clientContext.Site.OpenWebById(parentWeb);
                    List parentList    = lookupListWeb.Lists.GetById(new Guid(parentListGUID));

                    CamlQuery cq = new CamlQuery();
                    cq.ViewXml = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>";

                    ListItemCollection litems = parentList.GetItems(cq);
                    clientContext.Load(parentList);
                    clientContext.Load(litems);
                    clientContext.ExecuteQuery();

                    FieldLookupValue flv = new FieldLookupValue();
                    foreach (ListItem li in litems)
                    {
                        string phaseItemCode = li["Title"].ToString().TrimEnd(')').Split('(').Last();
                        if (phaseItemCode == code)
                        {
                            if (itemProperties.AfterProperties.ContainsKey("Phase") && !String.IsNullOrEmpty(itemProperties.AfterProperties["Phase"].ToString()))
                            {
                                string[] stringSeparators = new string[] { ";#" };
                                if (itemProperties.AfterProperties["Phase"].ToString().Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)[0] == li["ID"].ToString())
                                {
                                    break;
                                }
                            }

                            phase = li.Id + ";#" + li["Title"];
                            break;
                        }
                    }

                    result.ChangedItemProperties.Add("Phase", phase);
                    result.Status = SPRemoteEventServiceStatus.Continue;
                }
            }
        }
Example #58
0
        public void UpdateDefaultValues(ClientContext clientContext, Guid listId, int listItemId)
        {
            List            list   = clientContext.Web.Lists.GetById(listId);
            ListItem        item   = list.GetItemById(listItemId);
            FieldCollection fields = list.Fields;

            clientContext.Load(item);
            clientContext.Load(fields);
            clientContext.ExecuteQuery();

            if (item["Phase"] != null && !string.IsNullOrEmpty(item["Phase"].ToString()))
            {
                return;
            }

            string folderName = item["FileDirRef"].ToString().Split('/').Last();
            string code       = folderName.Split('_').First();

            string      lookupFieldName = "Phase";
            FieldLookup lookupField     = clientContext.CastTo <FieldLookup>(fields.GetByInternalNameOrTitle(lookupFieldName));

            clientContext.Load(lookupField);
            clientContext.ExecuteQuery();

            Guid   parentWeb      = lookupField.LookupWebId;
            string parentListGUID = lookupField.LookupList;

            Web  lookupListWeb = clientContext.Site.OpenWebById(parentWeb);
            List parentList    = lookupListWeb.Lists.GetById(new Guid(parentListGUID));

            CamlQuery cq = new CamlQuery();

            cq.ViewXml = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>";

            ListItemCollection litems = parentList.GetItems(cq);

            clientContext.Load(parentList);
            clientContext.Load(litems);
            clientContext.ExecuteQuery();

            foreach (ListItem li in litems)
            {
                string phaseItemCode = li["Title"].ToString().TrimEnd(')').Split('(').Last();
                if (phaseItemCode == code)
                {
                    string value = item.Id + ";#" + item["Title"];
                    if (item["Phase"] != null)
                    {
                        FieldLookupValue flv          = (FieldLookupValue)item["Phase"];
                        string           existingCode = flv.LookupValue.ToString().TrimEnd(')').Split('(').Last();
                        if (existingCode == code)
                        {
                            break;
                        }
                    }

                    item["Phase"] = li.Id + ";#" + li["Title"];
                    item.Update();
                    clientContext.ExecuteQuery();
                    break;
                }
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (adminPassword == null)
            {
                // This is the part where I grab the secret.
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                log.Info("Getting the secret.");
                var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                log.Info("KeyVaultSecret: " + Environment.GetEnvironmentVariable("KeyVaultSecret"));
                adminPassword = (await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("KeyVaultSecret"))).Value;
            }

            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                          .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            // Set name to query string or body data
            name = name ?? data?.name;
            string title = data?.title;

            string siteUrl   = string.Empty;
            string adminUser = Environment.GetEnvironmentVariable("spAdminUser");

            log.Info("adminUser: "******"spSite");

            log.Info("spSite: " + adminUser);
            System.Security.SecureString secureString = new System.Security.SecureString();
            foreach (char ch in adminPassword)
            {
                secureString.AppendChar(ch);
            }
            string sitesRequest = Environment.GetEnvironmentVariable("listName");

            log.Info("listName: " + sitesRequest);
            Dictionary <string, string> siteInfo = new Dictionary <string, string>();

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            string camlQuery =
                "<View>" +
                "<Query>" +
                "<Where>" +
                "<Eq>" +
                "<FieldRef Name='Status' />" +
                "<Value Type='Choice'>Approved</Value>" +
                "</Eq>" +
                "</Where>" +
                "</Query>" +
                "<RowLimit>1</RowLimit>" +
                "</View>";
            CamlQuery cq = new CamlQuery();

            cq.ViewXml = camlQuery;
            using (var context = authManager.GetSharePointOnlineAuthenticatedContextTenant(spSite, adminUser, secureString))
            {
                List list = context.Web.Lists.GetByTitle(sitesRequest);
                ListItemCollection lic = list.GetItems(cq);
                context.Load(lic);
                context.ExecuteQuery();
                foreach (ListItem item in lic)
                {
                    siteInfo.Add("Id", item["ID"].ToString());
                    siteInfo.Add("title", item["Title"].ToString());
                    siteInfo.Add("owner", item["Owner"].ToString());
                    siteInfo.Add("description", item["Description"] == null ? "" : item["Description"].ToString());
                    siteInfo.Add("type", item["SiteType"].ToString());
                    siteInfo.Add("alias", item["Alias"].ToString());
                    log.Info("Processing: " + item["Title"].ToString());
                    var siteType = siteInfo["type"];
                    switch (siteType.ToLower())
                    {
                    case "communicationsite":
                        var ctx = context.CreateSiteAsync(new CommunicationSiteCollectionCreationInformation
                        {
                            Title       = siteInfo["title"].ToString(),
                            Owner       = siteInfo["owner"].ToString(),
                            Lcid        = 1033,
                            Description = siteInfo["description"].ToString(),
                            Url         = spSite + "/sites/" + siteInfo["alias"].ToString(),
                        }).GetAwaiter().GetResult();
                        // Add OWner
                        User user = ctx.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctx.Web.Context.Load(user);
                        ctx.Web.Context.ExecuteQueryRetry();
                        ctx.Web.AssociatedOwnerGroup.Users.AddUser(user);
                        ctx.Web.AssociatedOwnerGroup.Update();
                        ctx.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teamsite":
                        var ctxTeamsite = context.CreateSiteAsync(new TeamSiteCollectionCreationInformation
                        {
                            DisplayName = siteInfo["title"].ToString(),
                            Description = siteInfo["description"].ToString(),
                            Alias       = siteInfo["alias"].ToString(),
                            IsPublic    = false,
                        }).GetAwaiter().GetResult();
                        siteUrl = ctxTeamsite.Url;
                        // Add OWner
                        User userTeamSite = ctxTeamsite.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctxTeamsite.Web.Context.Load(userTeamSite);
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        ctxTeamsite.Web.AssociatedOwnerGroup.Users.AddUser(userTeamSite);
                        ctxTeamsite.Web.AssociatedOwnerGroup.Update();
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teams":
                        string token = Graph.getToken();
                        log.Info("Access Token: " + token);
                        string userId  = string.Empty;
                        string groupId = string.Empty;
                        if (string.IsNullOrEmpty(token) == false)
                        {
                            userId = Graph.getUser(token, siteInfo["owner"].ToString());
                            log.Info("userId: " + userId);
                        }
                        if (string.IsNullOrEmpty(userId) == false)
                        {
                            string dataPost =
                                "{ 'displayName': '" + siteInfo["title"].ToString() + "', 'groupTypes': ['Unified'], 'mailEnabled': true, 'mailNickname': '" + siteInfo["alias"].ToString().Replace("\r\n", "").Replace(" ", "") + "', 'securityEnabled': false, '*****@*****.**': ['https://graph.microsoft.com/v1.0/users/" + userId + "'], 'visibility': 'Private' }";
                            groupId = Graph.createUnifiedGroup(token, dataPost);
                            log.Info("userId: " + groupId);
                            //Graph.addOwnerToUnifiedGroup(token, groupId, userId);
                            //removeOwnerToUnifiedGroup(token, groupId, userId);
                        }
                        siteUrl = siteInfo["title"].ToString();
                        log.Info("Teams ready: " + siteUrl);
                        break;
                    }
                    // When the site or Teams has been created the status of the list item will change in ready
                    if (siteUrl != string.Empty)
                    {
                        item["Status"] = "Ready";
                        item.Update();

                        context.ExecuteQuery();
                    }
                }
            }

            return(siteUrl == null
                ? req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong!")
                : req.CreateResponse(HttpStatusCode.OK, siteUrl));
        }
Example #60
0
        /// <summary>
        /// Process ListItem one by one
        /// </summary>
        /// <param name="listName">ListName</param>
        /// <param name="camlQuery">CamlQuery</param>
        /// <param name="itemProcessor">itemprocessor delegate</param>
        /// <param name="errorCallout">error delegate</param>
        public void ProcessListItem(string listName, CamlQuery camlQuery, ItemProcessor itemProcessor, ref List <PeoplePickerListOutput> lstPeoplepickeroutput, ItemProcessorErrorCallout errorCallout)
        {
            List      list  = _context.Web.Lists.GetByTitle(listName);
            CamlQuery query = camlQuery;

            //EventReceiverDefinitionCollection erCollection = list.EventReceivers;
            //foreach(EventReceiverDefinition erDefinition in erCollection)
            //{
            //    erDefinition.
            //}
            ListItemCollectionPosition position = null;

            query.ListItemCollectionPosition = position;

            while (true)
            {
                ListItemCollection listItems = list.GetItems(query);
                _context.Load(listItems, items => items.ListItemCollectionPosition);
                _context.ExecuteQueryRetry();

                for (int i = 0; i < listItems.Count; i++)
                {
                    try
                    {
                        itemProcessor(listItems[i], _context, ref lstPeoplepickeroutput);
                    }
                    catch (System.Exception ex)
                    {
                        if (errorCallout == null || errorCallout(listItems[i], ex))
                        {
                            throw;
                        }
                    }
                }

                if (listItems.ListItemCollectionPosition == null)
                {
                    return;
                }
                else
                {
                    /*if query contains lookup column filter last batch returns null
                     * by removing the lookup column in paginginfo query will return next records
                     */
                    string        pagingInfo         = listItems.ListItemCollectionPosition.PagingInfo;
                    string[]      parameters         = pagingInfo.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                    List <string> requiredParameters = new List <string>();
                    foreach (string str in parameters)
                    {
                        if (str.Contains("Paged=") || str.Contains("p_ID="))
                        {
                            requiredParameters.Add(str);
                        }
                    }

                    pagingInfo = string.Join("&", requiredParameters.ToArray());
                    listItems.ListItemCollectionPosition.PagingInfo = pagingInfo;
                    query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                }
            }
        }