private static void AddPublishingPage(ClientContext context, PublishingWeb webPub, ListItemCollection allPageLayouts, OfficeDevPnP.Core.Framework.Provisioning.Model.PublishingPage page) { ListItem layout = null; //try to get layout by Title layout = allPageLayouts.Where(x => x["Title"] != null && x["Title"].ToString().Equals(page.Layout)).FirstOrDefault(); //try to get layout by DisplayName if (layout == null) { layout = allPageLayouts.Where(x => x.DisplayName == page.Layout).FirstOrDefault(); } //we need to have a layout for a publishing page if (layout == null) { throw new ArgumentNullException(string.Format("Layout '{0}' for page {1} can not be found.", page.Layout, page.Name)); } context.Load(layout); // Create a publishing page PublishingPageInformation publishingPageInfo = new PublishingPageInformation(); publishingPageInfo.Name = page.Name; publishingPageInfo.PageLayoutListItem = layout; Microsoft.SharePoint.Client.Publishing.PublishingPage publishingPage = webPub.AddPublishingPage(publishingPageInfo); //publishingPage.ListItem.File.Approve(string.Empty); context.Load(publishingPage); context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl); context.ExecuteQuery(); }
public static IQueryable <ListItem> QueryByHeroId(this ListItemCollection collection, int id) { return(collection.Where(component => component.Id == id) .Include(component => component.Id, component => component["ComponentName"], component => component["Text"])); }
public static IQueryable <ListItem> QueryBlogPosts(this ListItemCollection pages) { return(pages.Where(page => page.ContentType.Name == "BlogPage") .Include(page => page.Id, page => page["Hero"], page => page["PublishedDate1"], page => page["Text"], page => page["PageName"])); }
public static void CreatePublishingPage(ClientContext clientContext, string pageName, string pagelayoutname, string url, string queryurl) { var publishingPageName = pageName + ".aspx"; Web web = clientContext.Web; clientContext.Load(web); List pages = web.Lists.GetByTitle("Pages"); clientContext.Load(pages.RootFolder, f => f.ServerRelativeUrl); clientContext.ExecuteQuery(); Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx"); clientContext.Load(file, f => f.Exists); clientContext.ExecuteQuery(); if (file.Exists) { file.DeleteObject(); clientContext.ExecuteQuery(); } PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web); clientContext.Load(publishingWeb); if (publishingWeb != null) { List publishingLayouts = clientContext.Site.RootWeb.Lists.GetByTitle("Master Page Gallery"); ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pagelayoutname)); clientContext.ExecuteQuery(); ListItem layout = allItems.Where(x => x.DisplayName == pagelayoutname).FirstOrDefault(); clientContext.Load(layout); PublishingPageInformation publishingpageInfo = new PublishingPageInformation() { Name = publishingPageName, PageLayoutListItem = layout, }; PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingpageInfo); publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); publishingPage.ListItem.File.Publish(string.Empty); clientContext.ExecuteQuery(); } SetSupportCaseContent(clientContext, "SupportCasesPage", url, queryurl); }
public static IQueryable <ListItem> QueryHomePages(this ListItemCollection pages) { return(pages.Where(page => page.ContentType.Name == "HomePage") .Include(page => page["PageName"], page => page["Hero"], page => page["TopContentTitle"], page => page["TopContent"], page => page["MiddleContentTitle"], page => page["MiddleContentLeft"], page => page["MiddleContentRight"], page => page["BottomContentTitle"], page => page["BottomContent"], page => page["ShowBlogPosts"], page => page["FooterContentTitle"], page => page["FooterTopContent"])); }
private static string InsertListInBD(string Uri, string User, string Password, string NameTable, string StringConnectionBD) { try { //Instancia de la Uri (ejm: https://miremingtonedu.sharepoint.com/sites/Pruebas) en este link se encuentra la lista var context = new ClientContext(Uri); //se obtiene el contexto de la paginaa Web web = context.Web; //se convierte la contraseña a un objeto SecureString SecureString password = GetPassword(Password); //se ingresan las credenciales del usuario context.Credentials = new SharePointOnlineCredentials(User, password); //se obtiene la tabla indicada List tabla = web.Lists.GetByTitle(NameTable); //-------se realiza un query sobre todos los elementos de la lista------- CamlQuery query = CamlQuery.CreateAllItemsQuery();//query para consultar ListItemCollection columnas = tabla.GetItems(query); //----------------------------------------------------------------------- //se carga la consulta y se ejecuta context.Load(columnas); context.ExecuteQuery(); //se recorren todos los items pendientes var list = columnas.Where(x => x["Estado"].ToString().Equals("Pendiente")); int Countslopes = list.Count(); if (Countslopes != 0) { foreach (ListItem item in list) { Console.WriteLine("------------"); Console.WriteLine(item["Title"].ToString() + " | " + item["Fecha_Creacion"].ToString() + " | " + item["Estado"].ToString()); Console.WriteLine("------------"); InsertTicket(StringConnectionBD, item["Title"].ToString(), item["Fecha_Creacion"].ToString(), item["Estado"].ToString()); item["Estado"] = "En Proceso"; item.Update(); context.ExecuteQuery(); } return("1|Succesfull"); } else { return("1|No hay elementos en la lista"); } } catch (Exception e) { return("0|Error no controlado: " + e.ToString()); } }
private static void childUpdate(ClientContext ctx, CamlQuery q, ListItem oitem) { #region child // CamlQuery q = new CamlQuery(); //Find all replies for topic with ID=1 q.ViewXml = @"<View Scope='Recursive'> <Query> <Where> <Eq> <FieldRef Name=""ParentFolderId"" /> <Value Type=""Integer"">" + oitem["ID"] + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"; ListItemCollection replies = oitem.ParentList.GetItems(q); ctx.Load(replies); ctx.ExecuteQuery(); Console.WriteLine(replies.Count); foreach (ListItem i in replies) { int parentItemId = Convert.ToInt16(i["ParentItemID"].ToString()); int pID = Convert.ToInt32(oitem["ID"]); // Console.WriteLine(i["Text"]); Console.WriteLine(i["ID"]); FieldUserValue author = (FieldUserValue)i["Author"]; FieldUserValue editor = (FieldUserValue)i["Editor"]; FieldUserValue parentItemEditor = (FieldUserValue)i["ParentItemEditor"]; Console.WriteLine(string.Format("Reply : Author {0} Editor {1} ParentItemEditor {2}", author.LookupValue, editor.LookupValue, parentItemEditor.LookupValue)); if (parentItemId == pID) { i["ParentItemEditor"] = resolveUser(author.LookupValue, ctx); } else { var onewItem = replies.Where(e => e["ID"].ToString() == parentItemId.ToString()); string value = ((FieldUserValue)onewItem.First()["Author"]).LookupValue; i["ParentItemEditor"] = resolveUser(value, ctx); } i.Update(); ctx.ExecuteQuery(); i["Editor"] = resolveUser(author.LookupValue, ctx); i.Update(); ctx.ExecuteQuery(); } #endregion }
public void AddPublishingPage() { string pageName = "CustomPage3.aspx"; Web webSite = context.Web; context.Load(webSite); PublishingWeb web = PublishingWeb.GetPublishingWeb(context, webSite); context.Load(web); if (web != null) { List pages = context.Site.RootWeb.Lists.GetByTitle("Pages"); ListItemCollection defaultPages = pages.GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(defaultPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageName)); context.ExecuteQuery(); if (defaultPages != null && defaultPages.Count > 0) { } else { List publishingLayouts = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery"); ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "PageLayoutTemplate")); context.ExecuteQuery(); ListItem layout = allItems.Where(x => x.DisplayName == "PageLayoutTemplate").FirstOrDefault(); context.Load(layout); PublishingPageInformation publishingPageInfo = new PublishingPageInformation(); publishingPageInfo.Name = pageName; publishingPageInfo.PageLayoutListItem = layout; PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo); publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); publishingPage.ListItem.File.Publish(string.Empty); publishingPage.ListItem.File.Approve(string.Empty); context.Load(publishingPage); context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl); context.ExecuteQuery(); } } }
public IEnumerable <string> GetSuperheroesByFilm(int filmId) { ListItemCollection filmsuperheroes = website.Lists.GetByTitle("FilmSuperheroes").GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(filmsuperheroes); clientContext.ExecuteQuery(); List <int> superheroIds = filmsuperheroes.Where(f => Convert.ToInt32(f["Title"]) == filmId) .Select(fs => Convert.ToInt32(fs["SuperheroId"])) .ToList(); ListItemCollection superheroes = website.Lists.GetByTitle("Superheroes").GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(superheroes); clientContext.ExecuteQuery(); List <string> result = superheroes.Where(f => superheroIds.Any(id => Convert.ToInt32(f.Id) == id)) .Select(fs => fs["Title"].ToString()) .ToList(); return(result); }
/// <summary> /// Check for the list item named Matter Center Briefcase already exists, if not then only create new folder /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="list">Name of the list</param> /// <param name="usersMySite">My Site URL of the user</param> internal static void CreateBriefcaseIfNotExists(ClientContext clientContext, List list, string usersMySite) { CamlQuery briefcaseQuery = new CamlQuery(); briefcaseQuery.ViewXml = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.BriefcaseFolderQuery, ServiceConstantStrings.LegalBriefcaseFolder); ListItemCollection briefcases = list.GetItems(briefcaseQuery); clientContext.Load(briefcases, listItems => listItems.Include(item => item.DisplayName)); clientContext.ExecuteQuery(); ListItem listItem = briefcases.Where(item => item.DisplayName == ServiceConstantStrings.LegalBriefcaseFolder).FirstOrDefault(); if (null == listItem) // Check for Matter Center Briefcase folder exists, if not then create { ListItemCreationInformation newItem = new ListItemCreationInformation(); newItem.FolderUrl = string.Concat(usersMySite, ServiceConstantStrings.OneDriveDocumentLibraryTitle); newItem.LeafName = ServiceConstantStrings.LegalBriefcaseFolder; newItem.UnderlyingObjectType = FileSystemObjectType.Folder; listItem = list.AddItem(newItem); listItem.Update(); clientContext.Load(listItem, field => field.DisplayName); clientContext.ExecuteQuery(); } }
public IEnumerable <string> GetFilmsBySuperhero(int superheroId) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = $@"<View> <Query> <Where> <Eq> <FieldRef Name='SuperheroId'/> <Value Type='Number'>{superheroId}</Value> </Eq> </Where> </Query> </View>"; ListItemCollection filmsuperheroes = website.Lists.GetByTitle("FilmSuperheroes").GetItems(camlQuery); clientContext.Load(filmsuperheroes); clientContext.ExecuteQuery(); List <int> filmIds = filmsuperheroes //.Where(f => Convert.ToInt32(f["SuperheroId"]) == superheroId) .Select(fs => Convert.ToInt32(fs["Title"])) .ToList(); ListItemCollection films = website.Lists.GetByTitle("Films").GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(films); clientContext.ExecuteQuery(); List <string> result = films.Where(f => filmIds.Any(id => Convert.ToInt32(f.Id) == id)) .Select(a => a["Title"].ToString()) .ToList(); return(result); }
static void Main(string[] args) { string pathArchivoCompleto = "C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\Documentos Control Documental_V1_004.xlsx"; string nombrePestana = "CM FINAL"; string usuarioSharePoint = "S004221"; string passwordSharePoint = "Julio2019"; string urlShareFolder = "\\\\10.104.175.150\\Campania\\Reporte"; string urlCompletoFolder = ""; string urlSharePointOrigen = "https://one.web.ppg.com/la/mexico/ppgmexico/CalidadTotal/Control_Documental/BckP_SJDR"; string urlSharePointDestino = "https://one.web.ppg.com/la/mexico/ppgmexico/CalidadTotal/Control_Documental/DocsPublic"; string urlCompletoOrigen = ""; string urlCompletoDestino = ""; string siteUrl = "https://one.web.ppg.com/la/mexico/ppgmexico/CalidadTotal/Control_Documental/"; string bibliotecaDocumentoSP = "Manual de Calidad"; string catalogoArea = "Area"; string catalogoDepartamento = "Department"; string catalogoDocType = "DocType"; string catalogoSBU = "SBU"; string catalogoCliente = "Clientes"; ExcelQueryFactory book = new ExcelQueryFactory(); List <Archivo> ListArchivo = new List <Archivo>(); List <Archivo> ListArchivoEncontrado = new List <Archivo>(); //string nombreArchivo = "\\\\10.104.175.150\\Campania\\Reporte\\Guid.NewGuid().ToString()" + ".xls"; string pathArchivoExcel = "\\\\10.104.175.150\\Campania\\Reporte\\Archivos_Cargados_" + Guid.NewGuid().ToString() + ".xls"; DataSet dsArchivoExcel = new DataSet(); DataTable dtArchivoExcel = new DataTable(); DataSet dsCatalogos = new DataSet(); DataTable dtArea = new DataTable(); DataTable dtDepartamento = new DataTable(); DataTable dtDocType = new DataTable(); dtArchivoExcel.Columns.Add("Area"); dtArchivoExcel.Columns.Add("Departamento"); dtArchivoExcel.Columns.Add("TipoDocumento"); dtArchivoExcel.Columns.Add("DepartamentoCodigo"); dtArchivoExcel.Columns.Add("Codigo"); dtArchivoExcel.Columns.Add("NombreDocumento"); dtArchivoExcel.Columns.Add("DescripcionDocumento"); dtArchivoExcel.Columns.Add("NumeroRevision"); dtArchivoExcel.Columns.Add("FCambioFijo"); dtArchivoExcel.Columns.Add("FCambioFrecuente"); dtArchivoExcel.Columns.Add("SBU"); dtArchivoExcel.Columns.Add("Cliente"); try { ////LECTURA DEL ARCHIVO EXCEL //book = new ExcelQueryFactory(pathArchivoCompleto); //ListArchivo = book.Worksheet(nombrePestana).AsEnumerable() // .Select(n => new Archivo // { // Area = n["Area"].Cast<string>(), // Departamento = n["Department"].Cast<string>(), // TipoDocumento = n["Document"].Cast<string>(), // DepartamentoCodigo = n["Department Code"].Cast<string>(), // Codigo = n["Archivo"].Cast<string>(), // NombreDocumento = n["Archivo"].Cast<string>(), // DescripcionDocumento = n["Name Document"].Cast<string>(), // NumeroRevision = n["Revision"].Cast<string>(), // FCambioFijo = n["Date Revision"].Cast<string>(), // FCambioFrecuente = n["Date Revision"].Cast<string>(), // SBU = n["SBU"].Cast<string>(), // Cliente = n["Cliente"].Cast<string>() // }).ToList(); ////CARGAR CLIENTE ////ListArchivo = ListArchivo.Where(n => !string.IsNullOrEmpty(n.DescripcionDocumento)).ToList(); //ListArchivo = ListArchivo.Where(n => !string.IsNullOrEmpty(n.Area) && n.Area.ToUpper() == "SATELITES").ToList(); #region CARGAR ORIGEN DESTINO /* * //CARGAR ARCHIVOS A SHARE POINT * foreach (Archivo a in ListArchivo.ToList()) * //.Where(n => !string.IsNullOrEmpty(n.Codigo) && n.Codigo.Trim() == "IT-1509").ToList()) * { * if (!string.IsNullOrEmpty(a.Codigo)) * { * //SE BUSCA EN FORMATO EXCEL * /////////////////////////// * urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim()); //+ ".xls"); * urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim()); //+ ".xls"); * urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim()); //+ ".xls"); * * try * { * using (WebClient client = new WebClient()) * { * client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * a.Codigo = a.Codigo.Trim(); //+ ".xls"; * * ListArchivoEncontrado.Add(a); * * continue; * } * * //a.Codigo = a.Codigo.Trim(); //+ ".xls"; * * //ListArchivoEncontrado.Add(a); * } * catch (Exception ex) * { * continue; * } * * ////INTENTO SIN ESPACIOS EN BLANCO * //urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim().Replace(" ", "") + ".xls"); * //urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim().Replace(" ", "") + ".xls"); * //urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim().Replace(" ", "") + ".xls"); * * //try * //{ * // using (WebClient client = new WebClient()) * // { * // client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * // client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * // client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * // a.Codigo = a.Codigo.Trim().Replace(" ", "") + ".xls"; * * // ListArchivoEncontrado.Add(a); * * // continue; * // } * //} * //catch (Exception ex) * //{ * * //} * * ////SE BUSCA EN FORMATO WORD * //////////////////////////// * //urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim() + ".doc"); * //urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim() + ".doc"); * //urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim() + ".doc"); * * //try * //{ * // using (WebClient client = new WebClient()) * // { * // client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * // client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * // client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * // a.Codigo = a.Codigo.Trim().Replace(" ", "") + ".doc"; * * // ListArchivoEncontrado.Add(a); * * // continue; * // } * //} * //catch (Exception ex) * //{ * * //} * * ////INTENTO SIN ESPACIOS EN BLANCO * //urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim().Replace(" ", "") + ".doc"); * //urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim().Replace(" ", "") + ".doc"); * //urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim().Replace(" ", "") + ".doc"); * * //try * //{ * // using (WebClient client = new WebClient()) * // { * // client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * // client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * // client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * // a.Codigo = a.Codigo.Trim().Replace(" ", "") + ".doc"; * * // ListArchivoEncontrado.Add(a); * * // continue; * // } * //} * //catch (Exception ex) * //{ * * //} * * ////SE BUSCA EN FORMATO PDF * /////////////////////////// * //urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim() + ".pdf"); * //urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim() + ".pdf"); * //urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim() + ".pdf"); * * //try * //{ * // using (WebClient client = new WebClient()) * // { * // client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * // client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * // client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * // a.Codigo = a.Codigo.Trim() + ".pdf"; * * // ListArchivoEncontrado.Add(a); * * // continue; * // } * //} * //catch (Exception ex) * //{ * * //} * * ////INTENTO SIN ESPACIOS EN BLANCO * //urlCompletoOrigen = Path.Combine(HttpUtility.HtmlEncode(urlSharePointOrigen), a.Codigo.Trim().Replace(" ", "") + ".pdf"); * //urlCompletoFolder = Path.Combine(HttpUtility.HtmlEncode(urlShareFolder), a.Codigo.Trim().Replace(" ", "") + ".pdf"); * //urlCompletoDestino = Path.Combine(HttpUtility.HtmlEncode(urlSharePointDestino), a.Codigo.Trim().Replace(" ", "") + ".pdf"); * * //try * //{ * // using (WebClient client = new WebClient()) * // { * // client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); * // client.DownloadFile(urlCompletoOrigen, urlCompletoFolder); * // client.UploadFile(urlCompletoDestino, "PUT", urlCompletoFolder); * * // a.Codigo = a.Codigo.Trim().Replace(" ", "") + ".pdf"; * * // ListArchivoEncontrado.Add(a); * * // continue; * // } * //} * //catch (Exception ex) * //{ * * //} * * } * } * */ #endregion ClientContext clientContext = new ClientContext(siteUrl); SP.Web myWeb = clientContext.Web; List myListArchivos = myWeb.Lists.GetByTitle(bibliotecaDocumentoSP); ListItemCollection listItems = myListArchivos.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listItems); clientContext.ExecuteQuery(); #region CREAR ARCHIVO EXCEL ///////////////////// //////CREAR ARCHIVO EXCEL //listItems.ToList().ForEach(item => //{ // dtArchivoExcel.Rows.Add(item["Area"] == null ? "" : ((FieldLookupValue)item["Area"]).LookupValue, // item["Department"] == null ? "" : ((FieldLookupValue)item["Department"]).LookupValue, // item["DocType"] == null ? "" : ((FieldLookupValue)item["DocType"]).LookupValue, // item["DepartmentCode"] == null ? "" : item["DepartmentCode"].ToString(), // item["FileLeafRef"] == null ? "" : item["FileLeafRef"].ToString(), // item["Title"] == null ? "" : item["Title"].ToString(), // item["Cliente"] == null ? "" : ((FieldLookupValue)item["Cliente"]).LookupValue, // item["Revision"] == null ? "" : item["Revision"].ToString(), // item["Update"] == null ? "" : item["Update"].ToString(), // item["Created"] == null ? "" : item["Created"].ToString(), // item["SBU"] == null ? "" : ((FieldLookupValue)item["SBU"]).LookupValue, // item["Modified"] == null ? "" : item["Modified"].ToString()); //}); //dsArchivoExcel.Tables.Add(dtArchivoExcel); //ExcelLibrary.DataSetHelper.CreateWorkbook(pathArchivoExcel, dsArchivoExcel); #endregion //CATALOGO AREA List myListCatalogoArea = myWeb.Lists.GetByTitle(catalogoArea); ListItemCollection listCatalogoArea = myListCatalogoArea.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listCatalogoArea); clientContext.ExecuteQuery(); //CATALOGO DEPARTAMENTE List myListCatalogoDepartamento = myWeb.Lists.GetByTitle(catalogoDepartamento); ListItemCollection listCatalogoDepartamento = myListCatalogoDepartamento.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listCatalogoDepartamento); clientContext.ExecuteQuery(); //CATALOGO DOC TYPE List myListCatalogoDocType = myWeb.Lists.GetByTitle(catalogoDocType); ListItemCollection listCatalogoDocType = myListCatalogoDocType.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listCatalogoDocType); clientContext.ExecuteQuery(); //CATALOGO SBU List myListCatalogoSBU = myWeb.Lists.GetByTitle(catalogoSBU); ListItemCollection listCatalogoSBU = myListCatalogoSBU.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listCatalogoSBU); clientContext.ExecuteQuery(); //CATALOGO CLIENTE List myListCatalogoCliente = myWeb.Lists.GetByTitle(catalogoCliente); ListItemCollection listCatalogoCliente = myListCatalogoCliente.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listCatalogoCliente); clientContext.ExecuteQuery(); #region ACTUALIZAR CODIGO ARCHIVO long maxId = listItems.Max(n => Convert.ToInt64(((ListItem)n).FieldValues["ID"])); long minId = listItems.Min(n => Convert.ToInt64(((ListItem)n).FieldValues["ID"])); var uno = listItems.Where(n => ((ListItem)n).FieldValues["DepartmentCode"] != null).ToList(); string codigoDocumento = string.Empty; listItems.ToList().ForEach(n => { var area = ((ListItem)n).FieldValues["Area"]; var departamento = ((ListItem)n).FieldValues["Department"]; var tipoDocumento = ((ListItem)n).FieldValues["DocType"]; var id = ((ListItem)n).FieldValues["ID"]; long idc = 0; idc = Convert.ToInt64(id) - 6525; n["IDC"] = idc; //n.Update(); if (area != null && departamento != null && tipoDocumento != null) { //clientContext.ExecuteQuery(); if (Convert.ToInt64(id) >= 1) { codigoDocumento = ((FieldLookupValue)area).LookupValue.ToUpper().Substring(0, 3) + "-" + ((FieldLookupValue)departamento).LookupValue.ToUpper().Substring(0, 3) + "-" + ((FieldLookupValue)tipoDocumento).LookupValue.ToUpper().Substring(0, 3) + "-" + idc.ToString("0000"); n["DepartmentCode"] = codigoDocumento; //n.Update(); } } n.Update(); if (Convert.ToInt64(id) % 100 == 0) { //n.Update(); clientContext.ExecuteQuery(); } if (listItems.Count == Convert.ToInt64(id)) { clientContext.ExecuteQuery(); } }); clientContext.ExecuteQuery(); #endregion #region ACTUALIZAR AREA //ListItem AreaTot = listCatalogoArea.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains("SATELITES")).ToList().FirstOrDefault(); //var res = listItems.Where(n => n.FieldValues["Area"] != null && ((FieldLookupValue)n.FieldValues["Area"]).LookupValue.ToUpper().Trim().Contains(AreaTot["Title"].ToString().ToUpper())); //foreach (ListItem item in res) //{ // ListItem Area = listCatalogoArea.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains("LOCALIDADES PPG")).ToList().FirstOrDefault(); // if (Area != null) // { // item["Area"] = Area; // item.Update(); // } // else // { // //Area = listCatalogoArea.ToList().FirstOrDefault(); // //item["Area"] = Area; // continue; // } //} //clientContext.ExecuteQuery(); #endregion #region ACTUALIZAR DEPARTAMENTO //string departamento = "Powder"; //string departamentoNuevo = "Pintura en Polvo"; //ListItem DepartamentoTot = listCatalogoDepartamento.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(departamento.ToUpper())).ToList().FirstOrDefault(); //var resDep = listItems.Where(n => n.FieldValues["Department"] != null && ((FieldLookupValue)n.FieldValues["Department"]).LookupValue.ToUpper().Trim().Contains(DepartamentoTot["Title"].ToString().ToUpper())); //foreach (ListItem item in resDep) //{ // ListItem Departamento = listCatalogoDepartamento.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(departamentoNuevo.ToUpper())).ToList().FirstOrDefault(); // if (Departamento != null) // { // item["Department"] = Departamento; // item.Update(); // } // else // { // //Area = listCatalogoArea.ToList().FirstOrDefault(); // //item["Area"] = Area; // continue; // } //} //clientContext.ExecuteQuery(); #endregion //CARGAR METADATOS A SHARE POINT foreach (Archivo am in ListArchivo.ToList())//.Where(n => !string.IsNullOrEmpty(n.SBU) || !string.IsNullOrEmpty(n.DescripcionDocumento))) //foreach (Archivo am in ListArchivoEncontrado.ToList()) { try { ListItem item = listItems.ToArray().Where(n => ((ListItem)n).FieldValues["FileLeafRef"] != null && ((ListItem)n).FieldValues["FileLeafRef"].ToString() == am.Codigo).ToList().FirstOrDefault(); if (item != null) { try { //item.Update(); item.File.CheckOut(); clientContext.ExecuteQuery(); } catch (Exception ex) { } ////item.File.UndoCheckOut(); //item["Title"] = am.Codigo; //item["Loop"] = "Si"; ////item["SBU"] = string.IsNullOrEmpty(am.SBU) ? "": am.SBU; ////item["DepartmentCode"] = am.DepartamentoCodigo; //////item["Cliente"] = string.IsNullOrEmpty(am.DescripcionDocumento) ? "": am.DescripcionDocumento; //item["Revision"] = am.NumeroRevision; ////item["Area"] = ""; ////item["Department"] = ""; ////item["DocType"] = ""; #region Catalogo Area if (!string.IsNullOrEmpty(am.Area)) { //ListItem Area = listCatalogoArea.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.Area.ToUpper().Trim())).ToList().FirstOrDefault(); ListItem Area = listCatalogoArea.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.Area.ToUpper().Trim())).ToList().FirstOrDefault(); if (Area != null) { item["Area"] = Area; } else { //Area = listCatalogoArea.ToList().FirstOrDefault(); //item["Area"] = Area; continue; } } else { //ListItem Area = listCatalogoArea.ToList().FirstOrDefault(); //item["Area"] = Area; continue; } #endregion //#region Catalogo Departamento //if (!string.IsNullOrEmpty(am.Departamento)) //{ // ListItem Departamento = listCatalogoDepartamento.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.Departamento.ToUpper().Trim())).ToList().FirstOrDefault(); // if (Departamento != null) // { // item["Department"] = Departamento; // } // else // { // //Departamento = listCatalogoDepartamento.ToList().FirstOrDefault(); // //item["Department"] = Departamento; // continue; // } //} //else //{ // //ListItem Departamento = listCatalogoDepartamento.ToList().FirstOrDefault(); // //item["Department"] = Departamento; // continue; //} //#endregion //#region Catalogo TipoDocumento //if (!string.IsNullOrEmpty(am.TipoDocumento)) //{ // ListItem DocType = listCatalogoDocType.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.TipoDocumento.ToUpper().Trim())).ToList().FirstOrDefault(); // if (DocType != null) // { // item["DocType"] = DocType; // } // else // { // //DocType = listCatalogoDocType.ToList().FirstOrDefault(); // //item["DocType"] = DocType; // //continue; // item["DocType"] = null; // } //} //else //{ // //ListItem DocType = listCatalogoDocType.ToList().FirstOrDefault(); // //item["DocType"] = DocType; // item["DocType"] = null; //} //#endregion //#region SBU //if (!string.IsNullOrEmpty(am.SBU)) //{ // ListItem SBU = listCatalogoSBU.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.SBU.ToUpper().Trim())).ToList().FirstOrDefault(); // if (SBU != null) // { // item["SBU"] = SBU; // } // else // { // item["SBU"] = null; // } //} //else //{ // item["SBU"] = null; //} //#endregion //#region Catalogo Cliente //if (!string.IsNullOrEmpty(am.Cliente)) //{ // ListItem Clientes = listCatalogoCliente.ToArray().Where(n => ((ListItem)n).FieldValues["Title"] != null && ((ListItem)n).FieldValues["Title"].ToString().ToUpper().Trim().Contains(am.Cliente.ToUpper().Trim())).ToList().FirstOrDefault(); // if (Clientes != null) // { // item["Cliente"] = Clientes; // } // else // { // item["Cliente"] = null; // } //} //else //{ // item["Cliente"] = null; //} //#endregion //ACTUALIZAR INFORMACION DE METADATOS //item.File.UndoCheckOut(); item.Update(); //clientContext.ExecuteQuery(); //REALIZAR CHECKOUT PARA TOMAR LOS ARCHIVOS //item.File.CheckOut(); //clientContext.ExecuteQuery(); //REALIZAR CHECKIN DE LOS ARCHIVOS item.File.CheckIn("", CheckinType.OverwriteCheckIn); clientContext.ExecuteQuery(); dtArchivoExcel.Rows.Add(string.IsNullOrEmpty(am.Area) ? " ": am.Area, string.IsNullOrEmpty(am.Departamento) ? " ": am.Departamento, string.IsNullOrEmpty(am.TipoDocumento) ? " ": am.TipoDocumento, string.IsNullOrEmpty(am.DepartamentoCodigo) ? " " : am.DepartamentoCodigo, string.IsNullOrEmpty(am.Codigo) ? " ": am.Codigo, string.IsNullOrEmpty(am.NombreDocumento) ? " ": am.NombreDocumento, string.IsNullOrEmpty(am.DescripcionDocumento) ? " " : am.DescripcionDocumento, string.IsNullOrEmpty(am.NumeroRevision) ? " ": am.NumeroRevision, string.IsNullOrEmpty(am.FCambioFijo) ? " ": am.FCambioFijo, string.IsNullOrEmpty(am.FCambioFrecuente) ? " ": am.FCambioFrecuente, string.IsNullOrEmpty(am.SBU) ? " " : am.SBU, string.IsNullOrEmpty(am.Cliente) ? " " : am.Cliente); //if(dtArchivoExcel.Rows.Count % 200 == 0) //{ //clientContext.ExecuteQuery(); //} } } catch (Exception ex) { } } //clientContext.ExecuteQuery(); //CREAR ARCHIVO EXCEL dsArchivoExcel.Tables.Add(dtArchivoExcel); ExcelLibrary.DataSetHelper.CreateWorkbook(pathArchivoExcel, dsArchivoExcel); ////EXPORTAR CATALOGOS ////AREA //dtArea.Columns.Add("Title"); //dtArea.Columns.Add("Code"); //foreach(ListItem item in listCatalogoArea) //{ // dtArea.Rows.Add(item["Title"], item["Code"]); //} ////DEPARTAMENTO //dtDepartamento.Columns.Add("Title"); //dtDepartamento.Columns.Add("Area"); //dtDepartamento.Columns.Add("Code"); //foreach (ListItem item in listCatalogoDepartamento) //{ // dtDepartamento.Rows.Add(item["Title"], ((FieldLookupValue)item["Area"]).LookupValue, item["b8ph"]); //} ////DOC TYPE //dtDocType.Columns.Add("Title"); //foreach (ListItem item in listCatalogoDocType) //{ // dtDocType.Rows.Add(item["Title"]); //} //dsCatalogos.Tables.Add(dtArea); //dsCatalogos.Tables.Add(dtDepartamento); //dsCatalogos.Tables.Add(dtDocType); //ExcelLibrary.DataSetHelper.CreateWorkbook(pathArchivoExcel, dsCatalogos); } catch (Exception ex) { Console.WriteLine("Mensaje: " + ex.Message + ", Source: " + ex.Source + ", StackTrace: " + ex.StackTrace); } }
private static void CreatePublishingPage2013(ClientContext ctx, Web web, XElement xPage) { Web webSite = web; ctx.Load(webSite); PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(ctx, webSite); ctx.Load(pubWeb); string pageName = xPage.Attribute("Name").Value; string layoutPageName = xPage.Attribute("LayoutPageName").Value; string pageLibrary = xPage.Attribute("PageLibrary").Value; if (pubWeb != null) { // Get library to hold new page List targetLibrary = webSite.Lists.GetByTitle(pageLibrary); ListItemCollection existingPages = targetLibrary.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageName)); ctx.ExecuteQuery(); if (existingPages != null && existingPages.Count > 0) { // Page already exists } else { // Get publishing page layouts List publishingLayouts = ctx.Web.Lists.GetByTitle("Master Page Gallery"); ListItemCollection layoutPages = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(layoutPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == layoutPageName)); ctx.ExecuteQuery(); ListItem layoutPage = layoutPages.Where(x => x.DisplayName == layoutPageName).FirstOrDefault(); ctx.Load(layoutPage); // Create a publishing page PublishingPageInformation newPublishingPageInfo = new PublishingPageInformation(); newPublishingPageInfo.Name = pageName; newPublishingPageInfo.PageLayoutListItem = layoutPage; PublishingPage newPublishingPage = pubWeb.AddPublishingPage(newPublishingPageInfo); newPublishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); newPublishingPage.ListItem.File.Publish(string.Empty); newPublishingPage.ListItem.File.Approve(string.Empty); ctx.Load(newPublishingPage); ctx.Load(newPublishingPage.ListItem.File, obj => obj.ServerRelativeUrl); ctx.ExecuteQuery(); } } }
static void Main(string[] args) { Console.WriteLine("Please Enter Site Address: "); string siteUrl = Console.ReadLine(); bool siteOnline = false; string siteUser = ""; string sitePassword = ""; string siteDomain = ""; if (siteUrl.Contains(".sharepoint.com")) { Console.WriteLine("This site is SharePoint Online Right ? (Y/N): "); string OnlineAnswer = Console.ReadLine(); if (OnlineAnswer.ToUpper() == "Y") { siteOnline = true; } } if (siteOnline) { Console.WriteLine("Please Enter Site Login User Email Address: "); siteUser = Console.ReadLine(); Console.WriteLine("Please Enter Site Login User Password: "******"Please Enter Site Login User Domain Name: "); siteDomain = Console.ReadLine(); Console.WriteLine("Please Enter Site Login User Name: "); siteUser = Console.ReadLine(); Console.WriteLine("Please Enter Site Login User Password: "******"Please Enter Master Page Gallery Name: "); string siteMasterPageGallery = Console.ReadLine(); Console.WriteLine("Please Enter Create Publishing Page Content Type Display Name: "); string pageContentType = Console.ReadLine(); Console.WriteLine("Please Enter Create Publishing Page Name: "); string pageName = Console.ReadLine(); Console.WriteLine("Do You Have Add Page Field Value (Y/N): "); string addPageValuAnswer = Console.ReadLine(); bool addPageValue = false; string addPageValueString = ""; if (addPageValuAnswer.ToUpper() == "Y") { addPageValue = true; Console.WriteLine("Please Enter Page Field Data ( ':' Separator Using For Field Name And Value, ';' Separator Using For Each Field Data ): "); Console.WriteLine("For Example ---> Title:TestPage;Comments:TestPage Comments "); Console.WriteLine(""); addPageValueString = Console.ReadLine(); } Console.WriteLine("Please Wait Start Create Process...."); ClientContext clientContext = null; PublishingPage publishingPage = null; Web web = null; try { clientContext = new ClientContext(siteUrl); if (siteOnline) { clientContext.AuthenticationMode = ClientAuthenticationMode.Default; string password = sitePassword; System.Security.SecureString passwordChar = new System.Security.SecureString(); foreach (char ch in password) { passwordChar.AppendChar(ch); } clientContext.Credentials = new SharePointOnlineCredentials(siteUser, passwordChar); } else { clientContext.Credentials = new NetworkCredential(siteUser, sitePassword, siteDomain); } web = clientContext.Web; clientContext.Load(web); clientContext.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine("This Site Connect Error Please Check Your Information And Try Again"); Console.WriteLine("Error Message: " + ex.Message); Console.ReadLine(); Environment.Exit(0); } try { Console.WriteLine("This Site Connection Success...."); Console.WriteLine("Please Wait Create Publishing Page....."); List publishingLayouts = clientContext.Site.RootWeb.Lists.GetByTitle(siteMasterPageGallery); ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageContentType)); clientContext.ExecuteQuery(); ListItem layout = allItems.Where(x => x.DisplayName == pageContentType).FirstOrDefault(); clientContext.Load(layout); PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web); clientContext.Load(publishingWeb); PublishingPageInformation publishingPageInfo = new PublishingPageInformation(); publishingPageInfo.Name = pageName.Contains(".aspx") ? pageName : pageName + ".aspx"; publishingPageInfo.PageLayoutListItem = layout; publishingPage = publishingWeb.AddPublishingPage(publishingPageInfo); clientContext.Load(publishingPage); clientContext.Load(publishingPage.ListItem.File); clientContext.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine("This During Publishing Page Error Please Check Your Information And Try Again"); Console.WriteLine("Error Message: " + ex.Message); Console.ReadLine(); Environment.Exit(0); } Console.WriteLine("this Publishing Page Create Success...."); if (addPageValue) { try { Console.WriteLine("Please Wait Add Field Data Publishing Page...."); ListItem listItem = publishingPage.ListItem; string[] dataArray = addPageValueString.Split(';'); foreach (string data in dataArray) { listItem[data.Split(':')[0]] = data.Split(':')[1]; } listItem.Update(); publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); publishingPage.ListItem.File.Publish(string.Empty); clientContext.Load(publishingPage); clientContext.ExecuteQuery(); Console.WriteLine("Tihs Publishing Page Add Field Data Success...."); } catch (Exception ex) { Console.WriteLine("This During Publishing Page Add Field Data Error Please Check Your Information And Try Again"); Console.WriteLine("Error Message: " + ex.Message); Console.ReadLine(); Environment.Exit(0); } } Console.WriteLine("All Process Complete Success..."); Console.ReadLine(); Environment.Exit(0); }
public static IQueryable <ListItem> QueryByFlexibleListItemId(this ListItemCollection collection, int id) { return(collection.Where(component => component.Id == id) .IncludeWithDefaultProperties(component => component.ContentType)); }
static public void ChangeInvoiceStatusToInvoiced(string baseUrl, string subWebsite, string user, string password, string listName, string barcode) { try { string[] parts = user.Split('\\'); using (ClientContext clientContext = new ClientContext(baseUrl + subWebsite)) { clientContext.Credentials = new NetworkCredential(parts[1], password, parts[0]); Web site = clientContext.Web; List list = site.Lists.GetByTitle(listName); CamlQuery query = new CamlQuery() { ViewXml = "<View Scope=\"RecursiveAll\">" + "<Query>" + "<Where>" + "<And>" + "<Eq>" + "<FieldRef Name=\"IFUInvoiceStatus\"/>" + "<Value Type=\"Text\">" + "Frei zur Zahlung" + "</Value>" + "</Eq>" + "<Eq>" + "<FieldRef Name=\"IFUInvoiceBarcode\"/>" + "<Value Type=\"Text\">" + barcode + "</Value>" + "</Eq>" + "</And>" + "</Where>" + "</Query>" + "</View>" }; ListItemCollection itemColl = list.GetItems(query); clientContext.Load(itemColl); clientContext.ExecuteQuery(); ListItem item = itemColl.Where(li => (li.FieldValues["IFUInvoiceBarcode"].ToString()) == barcode).First(); /* foreach (ListItem li in itemColl) { * clientContext.Load(li); * clientContext.ExecuteQuery(); * if (li.FieldValues["IFUInvoiceBarcode"] != null) { * if (li.FieldValues["IFUInvoiceBarcode"].ToString() == barcode) { * item = li; * break; * } * } * }*/ if (item != null) { clientContext.Load(item); clientContext.ExecuteQuery(); item["IFUInvoiceStatus"] = "Fakturiert"; item.Update(); clientContext.ExecuteQuery(); } else { logger.Error("Invoice was not found: " + barcode); } } } catch (Exception ex) { logger.Error(ex.Message); logger.Debug(ex.StackTrace); } }