public void Remove(string url, Guid listId, AttachmentsRemoveQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                var attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId);
                clientContext.Load(attachmentsFolder.Files);
                clientContext.ExecuteQuery();

                foreach (var file in attachmentsFolder.Files.ToList())
                {
                    if (options.FileNames.Contains(file.Name))
                    {
                        file.DeleteObject();
                    }
                }
                attachmentsFolder.Update();
                clientContext.ExecuteQuery();
            }
        }
Exemple #2
0
        public MemoryStream DownloadFileById(ref string hayError, string idItem, string siteUrl, string listName)
        {
            hayError = string.Empty;
            MemoryStream memorySt  = null;
            string       lsRetorno = string.Empty;

            try
            {
                using (ClientContext context = new ClientContext(siteUrl))
                {
                    context.Credentials = credentialsSHP;
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = string.Format(@"
                    <View Scope='Recursive'>
                        <Query>
                            <Where>
                                <Eq><FieldRef Name='ID'/><Value Type='Number'>" + idItem + @"</Value></Eq>
                            </Where>
                            <RowLimit>1</RowLimit>
                        </Query>                                                                    
                    </View>", idItem);

                    List list = context.Web.Lists.GetByTitle(listName);
                    ListItemCollection listItems = list.GetItems(query);
                    context.Load(listItems);
                    context.ExecuteQuery();

                    if (listItems.Count == 1)
                    {
                        ListItem item = listItems.First();
                        Microsoft.SharePoint.Client.File file = item.File;
                        ClientResult <Stream>            data = file.OpenBinaryStream();
                        ////Load the Stream data for the file
                        context.Load(file);
                        context.ExecuteQuery();
                        if (data != null)
                        {
                            using (memorySt = new MemoryStream())
                            {
                                data.Value.CopyTo(memorySt);
                            }
                        }
                    }
                    else
                    {
                        memorySt = null;
                    }
                }
            }
            catch (Exception ex)
            {
                hayError = ex.Message;
            }
            return(memorySt);
        }
        public void Add(string url, Guid listId, AttachmentsAddQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                Microsoft.SharePoint.Client.Folder attachmentsFolder;
                try
                {
                    attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
                    clientContext.Load(attachmentsFolder);
                    clientContext.ExecuteQuery();
                }
                catch
                {
                    attachmentsFolder = null;
                }

                // add
                var useService = (attachmentsFolder == null);
                if (useService)
                {
                    //There is no way to create attachments folder using client object model.
                    using (var service = new ListService(url, credentials.Get(url)))
                    {
                        service.AddAttachment(listId.ToString(), listItemId.ToString(CultureInfo.InvariantCulture), options.FileName, options.FileData);
                    }
                }
                else
                {
                    var fileUrl = string.Format("{0}/{1}", listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), options.FileName);
                    if (options.FileData != null)
                    {
                        using (var stream = new MemoryStream(options.FileData))
                        {
                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, stream, true);
                        }
                        clientContext.ExecuteQuery();
                    }
                }
            }
        }
        public List <SPAttachment> List(string url, Guid listId, AttachmentsGetQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                var site = clientContext.Site;
                clientContext.Load(site, s => s.Url);

                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                try
                {
                    int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                    var attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
                    clientContext.Load(attachmentsFolder);
                    clientContext.Load(attachmentsFolder.Files,
                                       files => files.Include(
                                           f => f.ServerRelativeUrl,
                                           f => f.Name,
                                           f => f.Title,
                                           f => f.TimeCreated,
                                           f => f.Author,
                                           f => f.TimeLastModified,
                                           f => f.ModifiedBy));
                    clientContext.ExecuteQuery();
                    return(attachmentsFolder.Files.ToList().Select(attachment => new SPAttachment(attachment.Name, new Uri(site.Url + attachment.ServerRelativeUrl))
                    {
                        Created = attachment.TimeCreated,
                        Modified = attachment.TimeLastModified,
                        CreatedBy = new SPUserPrincipal(attachment.Author),
                        ModifiedBy = new SPUserPrincipal(attachment.ModifiedBy)
                    }).ToList());
                }
                catch
                {
                    return(new List <SPAttachment>());
                }
            }
        }
        public static bool DeleteScannedDocument(string url, string user, string password, string listName, Guid guid)
        {
            string[] parts = user.Split('\\');
            try
            {
                using (ClientContext clientContext = new ClientContext(url))
                {
                    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>" +
                                  "<Eq>" +
                                  "<FieldRef Name=\"GUID\"/>" +
                                  "<Value Type=\"GUID\">" + guid + "</Value>" +
                                  "</Eq>" +
                                  "</Where>" +
                                  "</Query>" +
                                  "</View>"
                    };

                    ListItemCollection itemColl = list.GetItems(query);
                    clientContext.Load(itemColl);
                    clientContext.ExecuteQuery();

                    ListItem item = itemColl.First();
                    item.DeleteObject();

                    clientContext.ExecuteQuery();

                    return(true);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Debug(ex.StackTrace);
                return(false);
            }
        }
        public SFile Convert(ListItem listItem, SharepointClient sp)
        {
            var firmwareFileType  = "4dadfd09-f883-4f42-9178-ded2fe88016b";
            var firmwareFileType2 = "e3de2072-1eb2-4b6d-a7e2-3319bf89836d";

            var fileType = _fileTypeTerms.FirstOrDefault(t => t.Id == new Guid(firmwareFileType));

            var docType = listItem.Get <TaxonomyFieldValue>(SharepointFields.DocType);

            if (docType.TermGuid == firmwareFileType2)
            {
                fileType = _fileTypeTerms.FirstOrDefault(t => t.Id == new Guid(firmwareFileType2));
            }


            string folder        = listItem.Get <String>(SharepointFields.FileDir);
            string parent_folder = folder.Substring(0, folder.LastIndexOf('/'));

            var name       = listItem.Get <String>(SharepointFields.FileLeaf);
            var title      = listItem.Get <String>(SharepointFields.Title);
            var devices    = _firmwarefolders.First(fldr => parent_folder == fldr.Get <String>(SharepointFields.FileRef)).Get <TaxonomyFieldValueCollection>(SharepointFields.Devices).ToSPTermList(_names);
            var createDate = listItem.Get <DateTime>(SharepointFields.Created);
            var url        = UrlBuilder.GetFirmwaresUrl(name).ToString();



            var firmwareFile = new SFile
            {
                Id        = listItem.Id,
                Name      = name,
                Title     = title,
                Devices   = devices,
                File_type = fileType,
                Created   = createDate,
                Url       = url
            };

            var fileRef = listItem.Get <String>(SharepointFields.FileRef);

            sp.DownloadFileToLocal(fileRef, UrlBuilder.LocalPath_firmwares, name);


            return(firmwareFile);
        }
        public static List <FeeAttachment> GetFeeAttachment(string url, string user, string password, string listName, Guid guid)
        {
            List <FeeAttachment> feeAttachments = new List <FeeAttachment>();

            string[] parts = user.Split('\\');

            using (ClientContext clientContext = new ClientContext(url))
            {
                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>" +
                              "<Eq>" +
                              "<FieldRef Name=\"GUID\"/>" +
                              "<Value Type=\"GUID\">" + guid + "</Value>" +
                              "</Eq>" +
                              "</Where>" +
                              "</Query>" +
                              "</View>"
                };

                ListItemCollection itemColl = list.GetItems(query);
                clientContext.Load(itemColl);
                clientContext.ExecuteQuery();

                ListItem             item        = itemColl.First();
                AttachmentCollection attachments = item.AttachmentFiles;
                clientContext.Load(attachments);
                clientContext.ExecuteQuery();
                foreach (Attachment a in attachments)
                {
                    feeAttachments.Add(new FeeAttachment(url.Substring(0, url.Length - 1) + a.ServerRelativeUrl));
                }
            }

            return(feeAttachments);
        }
Exemple #8
0
        private int GetMaxId(List list)
        {
            var caml = Camlex.Query()
                       .OrderBy(i => i["ID"] as Camlex.Desc)
                       .Take(1)
                       .ToCamlQuery();
            ListItemCollection items = list.GetItems(caml);

            _clientContext.Load(items, li => li.Include(i => i["ID"]));
            ExecuteQueryWithCustomErrorMessage($"Error while retrieving max id from the list");

            if (items.Count == 0)
            {
                return(0);
            }
            var maxId = (int)items.First().FieldValues["ID"];

            return(maxId);
        }
        public static void SetFileUrlFee(string url, string user, string password, string listName, Guid guid, string serverFilePath)
        {
            string[] parts = user.Split('\\');

            using (ClientContext clientContext = new ClientContext(url))
            {
                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>" +
                              "<Eq>" +
                              "<FieldRef Name=\"GUID\"/>" +
                              "<Value Type=\"GUID\">" + guid + "</Value>" +
                              "</Eq>" +
                              "</Where>" +
                              "</Query>" +
                              "</View>"
                };

                ListItemCollection itemColl = list.GetItems(query);
                clientContext.Load(itemColl);
                clientContext.ExecuteQuery();
                FieldUrlValue urlValue = new FieldUrlValue();
                urlValue.Url         = serverFilePath;
                urlValue.Description = "Quittung öffnen";
                ListItem item = itemColl.First();

                item["Receipt"] = urlValue;
                item.ParseAndSetFieldValue("ApprovalState", "PDF Quittung übergeben");
                item.Update();
                clientContext.ExecuteQuery();
            }
        }
        public int GetListItem(SPOList spoList, string documentPath)
        {
            List spList = context.Web.Lists.GetById(spoList.Id);

            context.Load(spList.RootFolder);
            context.ExecuteQuery();
            string path = spList.RootFolder.ServerRelativeUrl + "/" + documentPath;

            CamlQuery query = new CamlQuery()
            {
                ViewXml = "<View Scope='RecursiveAll'>"
                          + "<Query>"
                          + $"<Where><Eq><FieldRef Name='FileRef'/><Value Type='File'>{path}</Value></Eq></Where>"
                          + "</Query>"
                          + "</View>"
            };
            // execute the query
            ListItemCollection listItems = spList.GetItems(query);

            context.Load(listItems);
            context.ExecuteQuery();
            return(listItems.First().Id);
        }
        public static void DeclineFee(string url, string user, string password, string listName, Guid guid)
        {
            string[] parts = user.Split('\\');

            using (ClientContext clientContext = new ClientContext(url))
            {
                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>" +
                              "<Eq>" +
                              "<FieldRef Name=\"GUID\"/>" +
                              "<Value Type=\"GUID\">" + guid + "</Value>" +
                              "</Eq>" +
                              "</Where>" +
                              "</Query>" +
                              "</View>"
                };

                ListItemCollection itemColl = list.GetItems(query);
                clientContext.Load(itemColl);
                clientContext.ExecuteQuery();

                ListItem item = itemColl.First();
                item.ParseAndSetFieldValue("ApprovalState", "abgelehnt");
                item.Update();

                clientContext.ExecuteQuery();
            }
        }
        /// <summary>
        /// Checks if hierarchy is created for the variation label.
        /// Get the "Hierarchy_x0020_Is_x0020_Created" list item value
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="variationLabel">Variation label</param>
        /// <returns>True, if hierarchy is created for the variation label</returns>
        private static bool CheckForHierarchyCreation(this ClientContext context, VariationLabelEntity variationLabel)
        {
            bool hierarchyIsCreated = false;

            // Get current web
            Web web = context.Web;

            context.Load(web, w => w.ServerRelativeUrl);
            context.ExecuteQueryRetry();

            // Try to get _VarLabelsListId property from web property bag
            string variationLabelsListId = web.GetPropertyBagValueString(VARIATIONLABELSLISTID, string.Empty);

            if (!string.IsNullOrEmpty(variationLabelsListId))
            {
                // Load the lists
                var lists = web.Lists;
                context.Load(lists);
                context.ExecuteQueryRetry();

                // Get the "Variation Labels" List by id
                Guid varRelationshipsListId = new Guid(variationLabelsListId);
                var  variationLabelsList    = lists.GetById(varRelationshipsListId);

                // Get the variationLabelsList list items
                ListItemCollection collListItems = variationLabelsList.GetItems(CamlQuery.CreateAllItemsQuery());
                context.Load(collListItems);
                context.ExecuteQueryRetry();

                // Check hierarchy is created
                ListItem varLabel = collListItems.First(x => x["Language"].ToString() == variationLabel.Language);
                variationLabel.IsCreated = hierarchyIsCreated = (bool)varLabel["Hierarchy_x0020_Is_x0020_Created"];
            }

            return(hierarchyIsCreated);
        }
Exemple #13
0
        /// <summary>
        /// Retorna el arreglo de bytes del documento SharePoint
        /// </summary>
        /// <param name="hayError">Cadena para ver si hay errores al retornar el documento.</param>
        /// <param name="idItem">Código del Archivo en el SharePoint</param>
        /// <param name="siteUrl">URL del Site SharePoint</param>
        /// <param name="listName">Lista de biblioteca.</param>
        /// <returns>Indicador con el resultado de la operación</returns>
        public ProcessResult <Object> DescargaArchivoPorId(ref string hayError, long idItem, string listName)
        {
            ProcessResult <Object> resultado = new ProcessResult <Object>();

            hayError = string.Empty;
            MemoryStream memorySt = null;
            string       siteUrl  = string.Empty;

            siteUrl = RetornaSiteUrlSharePoint();
            try
            {
                using (ClientContext context = new ClientContext(siteUrl))
                {
                    context.Credentials = RetornaCredencialesServer();
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = string.Format(@"
                    <View Scope='Recursive'>
                        <Query>
                            <Where>
                                <Eq><FieldRef Name='ID'/><Value Type='Number'>" + idItem + @"</Value></Eq>
                            </Where>
                            <RowLimit>1</RowLimit>
                        </Query>                                                                    
                    </View>", idItem);

                    List list = context.Web.Lists.GetByTitle(listName);
                    ListItemCollection listItems = list.GetItems(query);
                    context.Load(listItems);
                    context.ExecuteQuery();

                    if (listItems.Count == 1)
                    {
                        ListItem item = listItems.First();
                        Microsoft.SharePoint.Client.File file = item.File;
                        ClientResult <Stream>            data = file.OpenBinaryStream();
                        ////Load the Stream data for the file
                        context.Load(file);
                        context.ExecuteQuery();
                        if (data != null)
                        {
                            using (memorySt = new MemoryStream())
                            {
                                data.Value.CopyTo(memorySt);
                            }
                        }

                        resultado.Result = memorySt.ToArray();
                    }
                    else
                    {
                        memorySt = null;
                    }
                }
            }
            catch (Exception ex)
            {
                hayError = ex.Message;
                LogBL.grabarLogError(ex);//GRC16062015
                resultado.Result    = null;
                resultado.IsSuccess = false;
                resultado.Exception = new ApplicationLayerException <SharePointService>(ex);
            }
            return(resultado);
        }
        static public void UpdateBrochureOrder(string baseUrl, string subWebsite, string user, string password, string listName, BrochureOrder brochureOrder)
        {
            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>" +
                                  "<Eq>" +
                                  "<FieldRef Name=\"GUID\"/>" +
                                  "<Value Type=\"GUID\">" + brochureOrder.GetGuid() + "</Value>" +
                                  "</Eq>" +
                                  "</Where>" +
                                  "</Query>" +
                                  "</View>"
                    };

                    string status = "";

                    switch (brochureOrder.GetStatus())
                    {
                    case 0:
                        status = "Neu";
                        break;

                    case 1:
                        status = "Verarbeitet";
                        break;

                    case 2:
                        status = "Zurückgestellt";
                        break;
                    }


                    ListItemCollection itemColl = list.GetItems(query);
                    clientContext.Load(itemColl);
                    clientContext.ExecuteQuery();
                    FieldUrlValue urlValue = new FieldUrlValue();

                    ListItem item = itemColl.First();
                    item.ParseAndSetFieldValue("IFUKuAnmldgStatus", status);
                    item.ParseAndSetFieldValue("IFUKuAnmldgContactNumber", brochureOrder.GetContactNo());
                    item.ParseAndSetFieldValue("IFUEventnumber", brochureOrder.GetEventNo());
                    item.ParseAndSetFieldValue("IFUEventTemplateNumber", brochureOrder.GetEventTemplateNo());
                    item.ParseAndSetFieldValue("IFUCourseNumber", brochureOrder.GetCourseNo());
                    item.ParseAndSetFieldValue("IFUArticleNumber", brochureOrder.GetArticleNo());
                    item.Update();
                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Debug(ex.StackTrace);
            }
        }