Beispiel #1
0
        public void DeleteItemById <T>(int id)
        {
            Type entityType = typeof(T);

            try
            {
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }
                    ListItem item = list.GetItemById(id);
                    item.DeleteObject();
                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot delete item from table of entity of type '{entityType.Name}' with id '{id}'", ex);
                throw;
            }
        }
Beispiel #2
0
        public List <string> SelectFileNamesFromItem <T>(int id)
        {
            string         listname    = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            FileCollection attachments = GetAttachments(listname, id);

            return(attachments.Select(q => q.Name).ToList());
        }
Beispiel #3
0
 private void DeleteTable(Type entityType, bool throwErrorIfMissing)
 {
     try
     {
         string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
         using (var clientContext = GetClientContext())
         {
             Web            web            = clientContext.Web;
             ListCollection listCollection = web.Lists;
             clientContext.Load(listCollection);
             clientContext.ExecuteQuery();
             List list = listCollection.FirstOrDefault(q => q.Title == listName);
             if (list == null)
             {
                 if (throwErrorIfMissing)
                 {
                     throw new ListNotFoundException();
                 }
                 return;
             }
             list.DeleteObject();
             clientContext.ExecuteQuery();
         }
     }
     catch (Exception ex)
     {
         _log.Error($"Cannot delete table from entity of type '{entityType.Name}'", ex);
         throw;
     }
 }
Beispiel #4
0
        private int CountItems <T>(CamlQuery query)
        {
            Type entityType = typeof(T);

            try
            {
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }
                    ListItemCollection items = list.GetItems(query);
                    clientContext.Load(items, q => q.Include(l => l.Id));
                    clientContext.ExecuteQuery();
                    return(items.Count);
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot select items from table of entity with type '{entityType.Name}", ex);
                throw;
            }
        }
Beispiel #5
0
        public int InsertItem <T>(T entity)
        {
            Type entityType = typeof(T);

            try
            {
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }

                    ListItem newItem = list.AddItem(new ListItemCreationInformation());
                    AssignPropertiesToListItem(entity, newItem);

                    newItem.Update();
                    clientContext.ExecuteQuery();
                    return(newItem.Id);
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot insert data from entity of type '{entityType.Name}'", ex);
                throw;
            }
        }
Beispiel #6
0
        public AweCsomeLibraryFile SelectFileFromLibrary <T>(string foldername, string filename) where T : new()
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            var    allFiles = new List <AweCsomeLibraryFile>();

            using (ClientContext context = GetClientContext())
            {
                var folder = GetFolderFromDocumentLibrary <T>(context, foldername);
                context.Load(folder.Files);
                context.Load(folder.Files, f => f.Include(q => q.ListItemAllFields));
                context.ExecuteQuery();
                var file = folder.Files?.FirstOrDefault(q => q.Name == filename);
                if (file == null)
                {
                    return(null);
                }

                var fileStream = file.OpenBinaryStream();
                context.ExecuteQuery();
                MemoryStream stream = new MemoryStream();
                fileStream.Value.CopyTo(stream);
                stream.Position = 0;
                var entity = new T();

                StoreFromListItem(entity, file.ListItemAllFields);
                return(new AweCsomeLibraryFile
                {
                    Filename = file.Name,

                    Stream = stream,
                    entity = entity
                });
            }
        }
Beispiel #7
0
        private ListCreationInformation BuildListCreationInformation(ClientContext context, Type entityType)
        {
            ListCreationInformation listCreationInfo = new ListCreationInformation
            {
                Title        = EntityHelper.GetInternalNameFromEntityType(entityType),
                TemplateType = EntityHelper.GetListTemplateType(entityType),
                Description  = EntityHelper.GetDescriptionFromEntityType(entityType),
            };
            int?documentTemplateType = GetTableDocumentTemplateType(entityType);

            if (documentTemplateType.HasValue)
            {
                listCreationInfo.DocumentTemplateType = documentTemplateType.Value;
            }

            QuickLaunchOptions?quickLaunchOption = GetQuickLaunchOption(entityType);

            if (quickLaunchOption.HasValue)
            {
                listCreationInfo.QuickLaunchOption = quickLaunchOption.Value;
            }

            string url = GetTableUrl(entityType);

            if (url != null)
            {
                listCreationInfo.Url = url;
            }

            return(listCreationInfo);
        }
Beispiel #8
0
        private Folder GetFolderFromDocumentLibrary <T>(ClientContext context, string foldername)
        {
            string listname  = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            Web    web       = context.Web;
            string folderUrl = $"{listname}\\{foldername}";
            var    folder    = web.GetFolderByServerRelativeUrl(folderUrl);

            if (folder == null)
            {
                return(null);
            }
            try
            {
                context.Load(folder, f => f.Exists);
                context.ExecuteQuery();
                if (!folder.Exists)
                {
                    return(null);
                }
            }
            catch
            {
                return(null); // There is no cleaner way to do this on CSOM sadly
            }
            return(folder);
        }
Beispiel #9
0
        public string AttachFileToLibrary <T>(string foldername, string filename, Stream fileStream, T entity)
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            var    newFile  = new FileCreationInformation
            {
                ContentStream = fileStream,
                Url           = filename
            };

            using (ClientContext context = GetClientContext())
            {
                Web  web             = context.Web;
                List documentLibrary = web.GetListByTitle(listname);
                var  targetFolder    = documentLibrary.RootFolder;
                if (foldername != null)
                {
                    targetFolder = web.GetFolderByServerRelativeUrl($"{listname}\\{foldername}");
                }
                context.Load(targetFolder);
                context.ExecuteQuery();

                File uploadFile = targetFolder.Files.Add(newFile);

                uploadFile.ListItemAllFields.Update();
                context.ExecuteQuery();
                AssignPropertiesToListItem(entity, uploadFile.ListItemAllFields);
                uploadFile.ListItemAllFields.Update();
                context.ExecuteQuery();

                string targetFilename = $"{targetFolder.ServerRelativeUrl}/{filename}";
                _log.DebugFormat($"File '{filename}' uploaded to {targetFilename}");
                return(targetFilename);
            }
        }
Beispiel #10
0
        public List <AweCsomeLibraryFile> SelectFilesFromLibrary <T>(string foldername) where T : new()
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            var    allFiles = new List <AweCsomeLibraryFile>();

            using (ClientContext context = GetClientContext())
            {
                Web    web       = context.Web;
                string folderUrl = $"{listname}\\{foldername}";
                var    folder    = web.GetFolderByServerRelativeUrl(folderUrl);

                if (folder == null)
                {
                    return(null);
                }
                try
                {
                    context.Load(folder, f => f.Exists);
                    context.ExecuteQuery();
                    if (!folder.Exists)
                    {
                        return(null);
                    }
                }
                catch
                {
                    return(null); // There is no cleaner way to do this on CSOM
                }
                context.Load(folder.Files);
                context.Load(folder.Files, f => f.Include(q => q.ListItemAllFields));
                context.ExecuteQuery();
                if (folder.Files == null)
                {
                    return(null);
                }
                foreach (var file in folder.Files)
                {
                    var fileStream = file.OpenBinaryStream();
                    context.ExecuteQuery();
                    MemoryStream stream = new MemoryStream();
                    fileStream.Value.CopyTo(stream);
                    stream.Position = 0;
                    var entity = new T();

                    StoreFromListItem(entity, file.ListItemAllFields);
                    allFiles.Add(new AweCsomeLibraryFile
                    {
                        Filename = file.Name,

                        Stream = stream,
                        entity = entity
                    });
                }
                return(allFiles);
            }
        }
Beispiel #11
0
        public void UpdateItem <T>(T entity)
        {
            Type entityType = typeof(T);

            try
            {
                PropertyInfo idProperty = entityType.GetProperty(AweCsomeField.SuffixId);
                if (idProperty == null)
                {
                    throw new FieldMissingException("Field 'Id' is required for Update-Operations on Lists", AweCsomeField.SuffixId);
                }
                int?idValue = idProperty.GetValue(entity) as int?;
                if (!idValue.HasValue)
                {
                    throw new FieldMissingException("Field 'Id' is has no value. Update failed", AweCsomeField.SuffixId);
                }
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }
                    ListItem existingItem = list.GetItemById(idValue.Value);
                    foreach (var property in entityType.GetProperties())
                    {
                        if (!property.CanRead)
                        {
                            continue;
                        }
                        if (property.GetCustomAttribute <IgnoreOnUpdateAttribute>() != null)
                        {
                            continue;
                        }
                        existingItem[EntityHelper.GetInternalNameFromProperty(property)] = EntityHelper.GetItemValueFromProperty(property, entity);
                    }
                    existingItem.Update();
                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot update data from entity of type '{entityType.Name}'", ex);
                throw;
            }
        }
Beispiel #12
0
        public void Unlike <T>(int id, int userId)
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));

            ListItem item      = GetListItemById(listname, id);
            var      likeArray = ((FieldUserValue[])item.FieldValues.First(fn => fn.Key == "LikedBy").Value).ToList();
            var      userLike  = likeArray.FirstOrDefault(q => q.LookupId == userId);

            if (userLike != null)
            {
                likeArray.Remove(userLike);
                UpdateLikes(item, likeArray);
            }
        }
Beispiel #13
0
        public T SelectItemById <T>(int id) where T : new()
        {
            Type entityType = typeof(T);
            var  entity     = new T();

            try
            {
                string listname = EntityHelper.GetInternalNameFromEntityType(entityType);
                var    item     = GetListItemById(listname, id);
                StoreFromListItem(entity, item);
                return(entity);
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot select item by id for '{entityType.Name}' with id '{id}'", ex);
                throw;
            }
        }
Beispiel #14
0
        public string AddFolderToLibrary <T>(string folder)
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));

            using (ClientContext context = GetClientContext())
            {
                Web  web             = context.Web;
                List documentLibrary = web.GetListByTitle(listname);
                var  targetFolder    = documentLibrary.RootFolder;
                context.Load(targetFolder);
                context.ExecuteQuery();
                string[] folderParts = folder.Split('/');
                foreach (string part in folderParts)
                {
                    targetFolder = targetFolder.EnsureFolder(part);
                }
                context.ExecuteQuery();
                return(targetFolder.ServerRelativeUrl);
            }
        }
Beispiel #15
0
        public void DeleteFileFromItem <T>(int id, string filename)
        {
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));

            using (ClientContext context = GetClientContext())
            {
                Web      web         = context.Web;
                List     currentList = web.GetListByTitle(listname);
                ListItem item        = currentList.GetItemById(id);
                var      allFiles    = item.AttachmentFiles;
                context.Load(allFiles);
                context.ExecuteQuery();
                var oldFile = allFiles.FirstOrDefault(af => af.FileName == filename);
                if (oldFile == null)
                {
                    throw new FileNotFoundException($"File '{filename}' not found on {listname}/{id}");
                }
                oldFile.DeleteObject();
                context.ExecuteQuery();
                _log.DebugFormat($"File '{filename}' deleted from {listname}/{id}");
            }
        }
Beispiel #16
0
        public void AttachFileToItem <T>(int id, string filename, Stream filestream)
        {
            long   fileSize = filestream.Length;
            string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T));

            using (ClientContext context = GetClientContext())
            {
                Web      web            = context.Web;
                List     currentList    = web.GetListByTitle(listname);
                ListItem item           = currentList.GetItemById(id);
                var      attachmentInfo = new AttachmentCreationInformation
                {
                    FileName      = filename,
                    ContentStream = filestream
                };
                Attachment attachment = item.AttachmentFiles.Add(attachmentInfo);

                context.Load(attachment);
                context.ExecuteQuery();
                _log.DebugFormat($"Uploaded '{filename}' to {listname}({id}). Size:{fileSize} Bytes");
            }
        }
Beispiel #17
0
        private List <T> SelectItems <T>(CamlQuery query) where T : new()
        {
            Type entityType = typeof(T);
            var  entities   = new List <T>();

            try
            {
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }
                    ListItemCollection items = list.GetItems(query);
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();
                    foreach (var item in items)
                    {
                        var entity = new T();
                        StoreFromListItem(entity, item);
                        entities.Add(entity);
                    }
                }
                return(entities);
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot select items from table of entity with type '{entityType.Name}", ex);
                throw;
            }
        }
Beispiel #18
0
        public void CreateTable <T>()
        {
            Type   entityType = typeof(T);
            string listName   = EntityHelper.GetInternalNameFromEntityType(entityType);

            using (var clientContext = GetClientContext())
            {
                try
                {
                    ValidateBeforeListCreation(clientContext, listName);
                    Dictionary <string, Guid> lookupTableIds = GetLookupTableIds(clientContext, entityType);

                    ListCreationInformation listCreationInfo = BuildListCreationInformation(clientContext, entityType);

                    var newList = clientContext.Web.Lists.Add(listCreationInfo);
                    SetRating <T>(newList);
                    SetVersioning <T>(newList);
                    AddFieldsToTable(clientContext, newList, entityType.GetProperties(), lookupTableIds);
                    foreach (var property in entityType.GetProperties().Where(q => q.GetCustomAttribute <IgnoreOnCreationAttribute>() != null && q.GetCustomAttribute <DisplayNameAttribute>() != null))
                    {
                        // internal fields with custom displayname
                        _awecsomeField.ChangeDisplaynameFromField(newList, property);
                    }
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    var outerException = new Exception("error creating list", ex);
                    outerException.Data.Add("List", listName);

                    _log.Error($"Failed creating list {listName}", ex);
                    throw outerException;
                }
            }
            _log.Debug($"List '{listName}' created.");
        }
Beispiel #19
0
        public Dictionary <string, Stream> SelectFilesFromItem <T>(int id)
        {
            long           totalSize   = 0;
            string         listname    = EntityHelper.GetInternalNameFromEntityType(typeof(T));
            FileCollection attachments = GetAttachments(listname, id);

            var attachmentStreams = new Dictionary <string, Stream>();

            using (var clientContext = GetClientContext())
            {
                foreach (var attachment in attachments)
                {
                    MemoryStream targetStream = new MemoryStream();
                    var          stream       = attachment.OpenBinaryStream();
                    clientContext.ExecuteQuery();
                    stream.Value.CopyTo(targetStream);
                    attachmentStreams.Add(attachment.Name, targetStream);
                    totalSize += targetStream.Length;
                }
            }

            _log.DebugFormat($"Retrieved '{attachments.Count}' attachments from {listname}({id}). Size:{totalSize} Bytes");
            return(attachmentStreams);
        }
Beispiel #20
0
 public string GetListName <T>()
 {
     return(EntityHelper.GetInternalNameFromEntityType(typeof(T)));
 }