コード例 #1
0
        public void AddUserToGroup(string url, Authentication authentication, string loginNames, int groupId)
        {
            // Group Id is invalid
            if (groupId <= 0)
            {
                return;
            }

            using (var clientContext = new SPContext(url, authentication ?? credentials.Get(url)))
            {
                var group = clientContext.Web.SiteGroups.GetById(groupId);
                foreach (var loginName in loginNames.Split(','))
                {
                    var user = clientContext.Web.EnsureUser(loginName);
                    group.Users.AddUser(user);
                }
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    //User not found
                    SPLog.RoleOperationUnavailable(ex, String.Format("A server exception occurred while adding users to the group with id '{0}'. The exception message is: {1}", groupId, ex.Message));
                }
            }
        }
コード例 #2
0
 public List <Term> Terms(string url, Guid sspId, int lcid, Guid termSetId)
 {
     using (var tax = new TaxonomyService(url, credentials.Get(url)))
     {
         return(ParseXml(tax.GetChildTermsInTermSet(sspId, lcid, termSetId)).ToList());
     }
 }
コード例 #3
0
        public SP.Folder NewFolder(string url, Guid listId, string folderName, string currentDir)
        {
            if (!IsFolderValid(url, listId, folderName, currentDir))
            {
                return(null);
            }

            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);

                // add a new folder
                SP.Folder newFolder = parentFolder.Folders.Add(folderName);
                parentFolder.Update();
                clientContext.Load(newFolder);
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.FileNotFound(ex, "Error occurred while creating a new folder with a name '{0}' for a directory '{1}'.", folderName, currentDir);
                    return(null);
                }

                CacheService.RemoveByTags(new[] { Documents.Tag(listId), Folders.Tag(listId) }, CacheScope.All);

                return(newFolder);
            }
        }
コード例 #4
0
        public SP.FileCollection Attachments(SPListItem listItem, SPList list, object value)
        {
            if (value == null || !(bool)value)
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.Web web = clientContext.Web;
                clientContext.Load(web);
                SP.List splist = clientContext.ToList(list.Id);
                clientContext.Load(splist);
                SP.ListItem splistItem = splist.GetItemById(listItem.Id);
                clientContext.Load(splistItem);
                clientContext.ExecuteQuery();

                SP.Folder listFolder = splistItem.ParentList.RootFolder;
                clientContext.Load(listFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                SP.Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(listFolder.ServerRelativeUrl + "/attachments/" + splistItem.Id.ToString());
                clientContext.Load(attachmentsFolder);
                var attachments = attachmentsFolder.Files;
                clientContext.Load(attachments);
                clientContext.ExecuteQuery();

                return(attachments);
            }
        }
コード例 #5
0
        public SPUser Get(string url, string name)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Web web = clientContext.Web;

                // find users with equal account names
                SP.ListItemCollection usersByEqualQuery = web.SiteUserInfoList.GetItems(new SP.CamlQuery
                {
                    ViewXml = ViewQueryWhere(EqualQuery("Name", name, "Text"))
                });

                IEnumerable <SP.ListItem> userItemsByEqualQuery = clientContext.LoadQuery(SP.ClientObjectQueryableExtension.Include(usersByEqualQuery, SPUser.InstanceQuery));

                // find users with the same account names
                SP.ListItemCollection usersByContainsQuery = web.SiteUserInfoList.GetItems(new SP.CamlQuery
                {
                    ViewXml = ViewQueryWhere(ContainsQuery("Name", name, "Text"))
                });
                IEnumerable <SP.ListItem> userItemsByContainsQuery = clientContext.LoadQuery(SP.ClientObjectQueryableExtension.Include(usersByContainsQuery, SPUser.InstanceQuery));

                // find users by display name
                SP.ListItemCollection usersByTitleQuery = web.SiteUserInfoList.GetItems(new SP.CamlQuery
                {
                    ViewXml = ViewQueryWhere(EqualQuery("Title", name, "Text"))
                });
                IEnumerable <SP.ListItem> userItemsByTitleQuery = clientContext.LoadQuery(SP.ClientObjectQueryableExtension.Include(usersByTitleQuery, SPUser.InstanceQuery));

                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (SP.ServerException ex)
                {
                    SPLog.RoleOperationUnavailable(ex, String.Format("A server exception occurred while getting the user with name {0}'. The exception message is: {1}", name, ex.Message));
                    return(null);
                }

                SPUser user = TryGet(userItemsByEqualQuery);
                if (user != null)
                {
                    return(user);
                }

                user = TryGet(userItemsByContainsQuery);
                if (user != null)
                {
                    return(user);
                }

                user = TryGet(userItemsByTitleQuery);
                if (user != null)
                {
                    return(user);
                }
                return(null);
            }
        }
コード例 #6
0
        public SPView Get(
            [Documentation(Name = "List", Type = typeof(SPList)),
             Documentation(Name = "ById", Type = typeof(string)),
             Documentation(Name = "ByTitle", Type = typeof(string))]
            IDictionary options)
        {
            SPList list = null;

            if (options != null && options["List"] != null)
            {
                list = (SPList)options["List"];
            }
            else
            {
                return(null);
            }

            var byId    = (options["ById"] != null) ? options["ById"].ToString() : string.Empty;
            var byTitle = (options["ByTitle"] != null) ? options["ByTitle"].ToString() : string.Empty;

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.List splist      = clientContext.ToList(list.Id);
                var     fieldsQuery = clientContext.LoadQuery(splist.Fields.Include(
                                                                  field => field.Title,
                                                                  field => field.InternalName));

                SP.View spview = null;

                if (!string.IsNullOrEmpty(byId))
                {
                    string viewId = options["ById"].ToString();
                    spview = splist.GetView(new Guid(viewId));
                    clientContext.Load(spview);
                    clientContext.Load(spview, SPView.InstanceQuery);
                    clientContext.ExecuteQuery();
                }

                if (spview == null && !string.IsNullOrEmpty(byTitle))
                {
                    string viewTitle = options["ByTitle"].ToString();
                    var    viewQuery = clientContext.LoadQuery(splist.Views
                                                               .Where(view => view.Title == viewTitle)
                                                               .IncludeWithDefaultProperties(SPView.InstanceQuery));
                    clientContext.ExecuteQuery();
                    spview = viewQuery.FirstOrDefault();
                }

                if (spview != null)
                {
                    return(new SPView(spview, fieldsQuery.ToDictionary(item => item.InternalName, item => item.Title)));
                }
            }

            return(null);
        }
コード例 #7
0
        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();
                    }
                }
            }
        }
        private void Init(SP.Field Field, string baseurl)
        {
            var xml = Field.SchemaXml;
            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
            XmlReader      xmlReader     = XmlReader.Create(new StringReader(xml), readerSettings);
            var            xpathDocument = new XPathDocument(xmlReader);
            XPathNavigator nav           = xpathDocument.CreateNavigator();

            var allowMultipleValuesNode = nav.SelectSingleNode(@"/Field");

            bool.TryParse(allowMultipleValuesNode.GetAttribute("Mult", ""), out allowMultipleValues);

            var sspIdPropertyNode = nav.SelectSingleNode(@"/Field/Customization/ArrayOfProperty/Property[Name='SspId']");

            sspId = sspIdPropertyNode.SelectSingleNode(@"Value").Value;

            var termSetIdPropertyNode = nav.SelectSingleNode(@"/Field/Customization/ArrayOfProperty/Property[Name='TermSetId']");

            termSetId = termSetIdPropertyNode.SelectSingleNode(@"Value").Value;

            using (var tax = new TaxonomyClientService.Taxonomywebservice())
            {
                tax.Url         = baseurl.TrimEnd('/') + "/_vti_bin/TaxonomyClientService.asmx";
                tax.Credentials = credentials.Get(baseurl).Credentials();
                string termsXml = tax.GetChildTermsInTermSet(new Guid(sspId), CultureInfo.CurrentCulture.LCID, new Guid(termSetId));
                Terms = ParseResult(termsXml);
            }
        }
コード例 #9
0
        public int GetWSSId(string url, string label)
        {
            using (var context = new SPContext(url, credentials.Get(url)))
            {
                try
                {
                    var taxonomyList = context.Web.Lists.GetByTitle("TaxonomyHiddenList");
                    var taxItems     = taxonomyList.GetItems(CAMLQueryBuilder.GetItemByTitle(label, new[] { "Title", "ID" }));
                    context.Load(taxItems);

                    context.ExecuteQuery();

                    if (taxItems.Any())
                    {
                        return(taxItems[0].Id);
                    }
                }
                catch (Exception ex)
                {
                    SPLog.UnKnownError(ex, ex.Message);
                }
            }

            return(-1);
        }
コード例 #10
0
        public void CheckIn(string url, Guid libraryId, int itemId, FileCheckInOptions options)
        {
            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfile = clientContext.Web.Lists.GetById(libraryId).GetItemById(itemId).File;
                    var type   = !string.IsNullOrEmpty(options.CheckinType) ? (CheckinType)Enum.Parse(typeof(CheckinType), options.CheckinType) : CheckinType.MajorCheckIn;

                    spfile.CheckIn(options.Comment, type);

                    if (options.KeepCheckOut)
                    {
                        spfile.CheckOut();
                    }

                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.CheckIn() method for URL: {1}, LibraryId: {2}, ItemId: {3}. The exception message is: {4}", ex.GetType(), url, libraryId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message);
            }
        }
コード例 #11
0
        public List <SPPermissionsLevel> Levels(string webUrl)
        {
            var levels = new List <SPPermissionsLevel>();

            try
            {
                using (var clientContext = new SPContext(webUrl, credentials.Get(webUrl)))
                {
                    var web = clientContext.Web;
                    clientContext.Load(web,
                                       w => w.RoleDefinitions.Include(
                                           rd => rd.Id,
                                           rd => rd.Name,
                                           rd => rd.Description));
                    clientContext.ExecuteQuery();

                    foreach (var rd in web.RoleDefinitions)
                    {
                        levels.Add(new SPPermissionsLevel(rd.Id, rd.Name)
                        {
                            Description = rd.Description
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the SPPermissionsService.Levels() method for SPWebUrl: {1}. The exception message is: {2}", ex.GetType(), webUrl, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(levels);
        }
コード例 #12
0
 public Microsoft.SharePoint.Client.Field Get(string url, Guid listId, Guid fieldId)
 {
     using (var spcontext = new SPContext(url, credentials.Get(url)))
     {
         var list  = spcontext.Web.Lists.GetById(listId);
         var field = list.Fields.GetById(fieldId);
         spcontext.Load(field);
         spcontext.ExecuteQuery();
         return(field);
     }
 }
コード例 #13
0
        public bool IsCheckedOut(SPList list, SPListItem listItem)
        {
            var cacheId      = string.Format("SharePointFile:{0}_{1}", list.Id, listItem.Id);
            var isCheckedOut = (bool?)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process);

            if (isCheckedOut == null)
            {
                using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
                {
                    var spfile = clientContext.ToFile(list.Id, listItem.Id);
                    clientContext.Load(spfile, item => item.CheckedOutByUser);
                    clientContext.ExecuteQuery();
                    isCheckedOut = !(spfile.CheckedOutByUser.ServerObjectIsNull ?? true);
                    cacheService.Put(cacheId, isCheckedOut, CacheScope.Context | CacheScope.Process, new string[0], CacheTimeOut);
                }
            }
            return(isCheckedOut.Value);
        }
コード例 #14
0
        public Dictionary <int, string> UserCollection(SPList currentList)
        {
            var _userCollection = new Dictionary <int, string>();

            using (var clientContext = new SPContext(currentList.SPWebUrl, credentials.Get(currentList.SPWebUrl)))
            {
                SP.Web web       = clientContext.Web;
                var    usersList = web.SiteUserInfoList.GetItems(SP.CamlQuery.CreateAllItemsQuery());
                clientContext.Load(usersList, _users => _users
                                   .Include(_user => _user["Name"], _user => _user.Id));
                clientContext.ExecuteQuery();
                for (int i = 0, len = usersList.Count; i < len; i++)
                {
                    _userCollection.Add(usersList[i].Id, usersList[i]["Name"].ToString());
                }
                return(_userCollection);
            }
        }
コード例 #15
0
 public SPUser Get(string url, int lookupId)
 {
     using (var clientContext = new SPContext(url, credentials.Get(url)))
     {
         try
         {
             var userProfile = clientContext.Web.SiteUserInfoList.GetItemById(lookupId);
             clientContext.Load(userProfile, SPUser.InstanceQuery);
             clientContext.ExecuteQuery();
             return(new SPUser(userProfile));
         }
         catch (Exception ex)
         {
             string message = string.Format("An exception of type {0} occurred in the InternalApi.UserProfileService.Get() method URL: {1}, LookupId: {2}. The exception message is: {4}", ex.GetType(), url, lookupId, ex.Message);
             SPLog.RoleOperationUnavailable(ex, message);
         }
     }
     return(null);
 }
コード例 #16
0
        public Dictionary <string, string> GetValues(SPList currentList, object splistItem, SP.Field field, bool removeSelected)
        {
            SPListItem listItem = splistItem as SPListItem;

            SP.FieldLookup lookupField = field as SP.FieldLookup;
            if (lookupField == null)
            {
                return(new Dictionary <string, string>());
            }
            using (var clientContext = new SPContext(currentList.SPWebUrl, credentials.Get(currentList.SPWebUrl)))
            {
                SP.Web lookupWeb = clientContext.Site.OpenWebById(lookupField.LookupWebId);
                clientContext.Load(lookupWeb);
                SP.List list = lookupWeb.Lists.GetById(new Guid(lookupField.LookupList));
                clientContext.Load(list);
                SP.ListItemCollection items = list.GetItems(SP.CamlQuery.CreateAllItemsQuery());
                clientContext.Load(items);
                clientContext.ExecuteQuery();
                SP.FieldLookupValue[] selectedValues = null;
                if (removeSelected)
                {
                    selectedValues = GetSelectedValues(listItem, field);
                }
                Dictionary <string, string> values = new Dictionary <string, string>();
                foreach (SP.ListItem item in items)
                {
                    if (removeSelected && selectedValues.Any(v => v.LookupId == item.Id))
                    {
                        continue;
                    }
                    object lookupVal = item[lookupField.LookupField];
                    if (lookupVal != null)
                    {
                        values.Add(item.Id.ToString(), (string)lookupVal);
                    }
                }
                return(values);
            }
        }
コード例 #17
0
        public SPListItem Get(SPList list, string listItemId,
                              [Documentation(Name = "ViewFields", Type = typeof(List <string>))]
                              IDictionary options)
        {
            int id;

            if (!int.TryParse(listItemId, out id))
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                var splist = clientContext.ToList(list.Id);
                IEnumerable <ListItem> itemQuery;
                if (options != null && options["ViewFields"] != null)
                {
                    var viewFields = (List <string>)options["ViewFields"];
                    itemQuery = clientContext.LoadQuery(splist.GetItems(CamlQuery.CreateAllItemsQuery())
                                                        .Where(item => item.Id == id)
                                                        .Include(CreateListItemLoadExpressions(viewFields)));
                }
                else
                {
                    itemQuery = clientContext.LoadQuery(splist.GetItems(CamlQuery.CreateAllItemsQuery())
                                                        .Where(item => item.Id == id)
                                                        .IncludeWithDefaultProperties(SPItemService.InstanceQuery));
                }
                var fieldsQuery = clientContext.LoadQuery(splist.Fields.Where(field => !field.Hidden && field.Group != "_Hidden"));
                clientContext.ExecuteQuery();
                var listItem = itemQuery.FirstOrDefault();
                if (listItem != null)
                {
                    return(new SPListItem(listItem, fieldsQuery.ToList()));
                }
                return(null);
            }
        }
コード例 #18
0
        public Folder Create(string url, Guid libraryId, FolderCreateQuery folderCreateQuery)
        {
            Folder folder;

            try
            {
                SP.ListItem folderListItem;

                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var splist       = clientContext.Web.Lists.GetById(libraryId);
                    var parentFolder = !String.IsNullOrEmpty(folderCreateQuery.Path) ? clientContext.Web.GetFolderByServerRelativeUrl(folderCreateQuery.Path) : splist.RootFolder;

                    clientContext.Load(parentFolder);

                    // check that new folder name is unique
                    var folderName = folderCreateQuery.Name;
                    var subfolderWithTheSameName = clientContext.LoadQuery(parentFolder.Folders.Where(f => f.Name == folderName));
                    try
                    {
                        clientContext.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Create() method for SharePoint ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'. The exception message is: {3}", ex.GetType(), folderCreateQuery.Path, url, ex.Message);
                        SPLog.FileNotFound(ex, message);

                        throw new SPInternalException(message, ex);
                    }

                    if (subfolderWithTheSameName != null && subfolderWithTheSameName.Any())
                    {
                        throw new InvalidOperationException(string.Format("The folder with '{0}' name already exists at ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'.", folderName, folderCreateQuery.Path, url));
                    }

                    var newFolder = parentFolder.Folders.Add(folderCreateQuery.Name);
                    clientContext.Load(newFolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);

                    parentFolder.Update();
                    clientContext.ExecuteQuery();

                    var query           = GetFolderByServerRelativeUrl(newFolder.ServerRelativeUrl);
                    var folderListItems = clientContext.LoadQuery(splist.GetItems(query));
                    clientContext.ExecuteQuery();

                    folder         = new Folder(newFolder.Name, newFolder.ServerRelativeUrl, newFolder.ItemCount, libraryId);
                    folderListItem = folderListItems.First();
                }

                listItemDataService.AddUpdate(new ItemBase(libraryId,
                                                           Guid.Parse(folderListItem["UniqueId"].ToString()),
                                                           folderListItem.Id,
                                                           Convert.ToDateTime(folderListItem["Modified"]))
                {
                    IsIndexable = false
                });
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (SPInternalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Create() method while creating a new folder with the Name: '{1}' ServerRelativeUrl: '{2}' in SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), folderCreateQuery.Name, folderCreateQuery.Path, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }

            return(folder);
        }
コード例 #19
0
        public SPCalendar Get(string url, string listId,
                              [Documentation(Name = "DateRange", Type = typeof(string), Description = "Today, Month, Year"),
                               Documentation(Name = "CalendarDate", Type = typeof(DateTime), Description = "Date in UTC format (Now is a default value)"),
                               Documentation(Name = "ViewFields", Type = typeof(ArrayList), Description = "An array of field names"),
                               Documentation(Name = "DateInUtc", Type = typeof(bool), Description = "False by default"),
                               Documentation(Name = "PageSize", Type = typeof(int))]
                              IDictionary options)
        {
            var spcalendar = new SPCalendar();
            var auth       = credentials.Get(url);

            string webId;

            using (SPContext spcontext = new SPContext(url, auth))
            {
                SP.Web web = spcontext.Web;
                spcontext.Load(web, w => w.Id);
                spcontext.ExecuteQuery();
                webId = web.Id.ToString();
            }

            using (var listService = new ListService(url, auth))
            {
                DateRangesOverlap dateRange = DateRangesOverlap.Month;
                if (options != null && options["DateRange"] != null && Enum.TryParse(options["DateRange"].ToString(), out dateRange))
                {
                }

                var queryDocument = new XmlDocument();

                // CAML Query
                var queryXml = queryDocument.CreateElement("Query");
                queryXml.InnerXml = String.Format(@"
                    <Where>
                        <DateRangesOverlap>
                            <FieldRef Name='EventDate' />
                            <FieldRef Name='EndDate' />
                            <FieldRef Name='RecurrenceID' />
                            <Value Type='DateTime'>
                                <{0}/>
                            </Value>
                        </DateRangesOverlap>
                    </Where>
                    <OrderBy>
                        <FieldRef Name='ID' />
                    </OrderBy>", Enum.GetName(dateRange.GetType(), dateRange));

                // CAML Query options
                bool dateInUtc = false;
                if (options != null && options["DateInUtc"] is bool)
                {
                    dateInUtc = (bool)options["DateInUtc"];
                }

                DateTime calendarDate = dateInUtc ? DateTime.Now : DateTime.UtcNow;
                if (options != null && options["CalendarDate"] is DateTime)
                {
                    calendarDate = (DateTime)options["CalendarDate"];
                }

                var queryOptionsXml = queryDocument.CreateElement("QueryOptions");
                queryOptionsXml.InnerXml = String.Format(@"
                    <IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>
                    <DateInUtc>{0}</DateInUtc>
                    <ViewAttributes Scope='Recursive' />
                    <RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>
                    <ExpandRecurrence>True</ExpandRecurrence>
                    <CalendarDate>{1}Z</CalendarDate>
                    <RecurrenceOrderBy>TRUE</RecurrenceOrderBy>
                    <ViewAttributes Scope='RecursiveAll'/>
                    <ExpandRecurrence>TRUE</ExpandRecurrence>",
                                                         dateInUtc.ToString().ToUpper(), calendarDate.ToString("s"));

                // CAML Query View Fields
                var viewFieldsInnerXml = new StringBuilder();
                if (options != null && options["ViewFields"] is ArrayList)
                {
                    var fields = (ArrayList)options["ViewFields"];
                    if (fields != null && fields.Count > 0)
                    {
                        foreach (string fieldName in fields)
                        {
                            viewFieldsInnerXml.AppendFormat("<FieldRef Name='{0}' />", fieldName);
                        }
                    }
                }

                var viewFieldsXml = queryDocument.CreateElement("ViewFields");
                viewFieldsXml.InnerXml = viewFieldsInnerXml.ToString();

                const int defaultPageSize = 10000;
                int       pageSize        = defaultPageSize;
                if (options != null && options["PageSize"] != null && !String.IsNullOrEmpty(options["PageSize"].ToString()))
                {
                    pageSize = int.Parse(options["PageSize"].ToString());
                }

                var recurrenceEvents = listService.GetListItems(listId, String.Empty, queryXml, viewFieldsXml, pageSize.ToString(), queryOptionsXml, webId);

                var recurrenceEventsDoc = recurrenceEvents.OwnerDocument ?? (XmlDocument)recurrenceEvents;
                var nsmanager           = new XmlNamespaceManager(recurrenceEventsDoc.NameTable);
                nsmanager.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/soap/");
                nsmanager.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
                nsmanager.AddNamespace("z", "#RowsetSchema");

                const string fieldNamePrefix = "ows_";
                foreach (XmlNode itemXml in recurrenceEvents.SelectNodes("//rs:data/z:row", nsmanager))
                {
                    if (itemXml.Attributes[fieldNamePrefix + "UniqueId"] != null)
                    {
                        string[] parsedIds = itemXml.Attributes[fieldNamePrefix + "UniqueId"].Value.Split(new[] { ';' });
                        Guid     uniqueId;
                        int      counterId;
                        if (parsedIds.Length == 2 && int.TryParse(parsedIds[0], out counterId) && Guid.TryParseExact(parsedIds[1].Replace("#", String.Empty), "B", out uniqueId))
                        {
                            string title   = itemXml.Attributes[fieldNamePrefix + "Title"] != null ? itemXml.Attributes[fieldNamePrefix + "Title"].Value : String.Empty;
                            var    spevent = new SPEvent(counterId.ToString(), uniqueId.ToString(), title);
                            foreach (XmlAttribute attribute in itemXml.Attributes)
                            {
                                spevent[attribute.Name.Replace(fieldNamePrefix, string.Empty)] = attribute.Value;
                            }
                            spcalendar.Add(spevent);
                        }
                    }
                }

                if (dateRange == DateRangesOverlap.Today)
                {
                    spcalendar.RemoveAll(item =>
                                         !item.StartDate.HasValue ||
                                         item.StartDate.Value.Day != calendarDate.Day);
                }
            }
            return(spcalendar);
        }
コード例 #20
0
        public static string GetText(string webUrl, string fileName, string filePath, ICredentialsManager credentialsManager, int maxFileSizeInBytes, int bufferSizeKB = 16)
        {
            var remoteFileText = String.Empty;

            using (var remoteFile = Microsoft.SharePoint.Client.File.OpenBinaryDirect(new SPContext(webUrl, credentialsManager.Get(webUrl)), filePath))
                using (var dataStream = remoteFile.Stream)
                    using (var memoryDataStream = new MemoryStream())
                    {
                        if (dataStream.CanRead)
                        {
                            byte[] buffer          = new byte[bufferSizeKB * 1024];
                            int    readBytes       = 0;
                            int    memoryDataBytes = 0;
                            while ((readBytes = dataStream.Read(buffer, 0, buffer.Length)) > 0 &&
                                   memoryDataBytes < maxFileSizeInBytes)
                            {
                                memoryDataStream.Write(buffer, 0, readBytes);
                                memoryDataBytes += readBytes;
                            }
                            if (memoryDataBytes < maxFileSizeInBytes)
                            {
                                memoryDataStream.Seek(0, SeekOrigin.Begin);
                                remoteFileText = SearchIndexingFormatter.GetText(new RemoteAttachment(fileName, memoryDataStream)
                                {
                                    Length = memoryDataStream.Length
                                });
                            }
                        }
                    }
            return(remoteFileText);
        }
コード例 #21
0
        public void Update(ListUpdateQuery options)
        {
            if (options.Id == Guid.Empty)
            {
                return;
            }

            ListBase listBase = null;
            string   spwebUrl = options.SPWebUrl;

            if (string.IsNullOrEmpty(spwebUrl))
            {
                listBase = listDataService.Get(options.Id);
                if (listBase == null)
                {
                    return;
                }

                Validate(listBase);
                spwebUrl = listBase.SPWebUrl;
            }

            try
            {
                var hasSharePointUpdates = options.Title != null || options.Description != null;
                if (hasSharePointUpdates)
                {
                    using (var clientContext = new SPContext(spwebUrl, credentials.Get(spwebUrl)))
                    {
                        var splist = clientContext.Web.Lists.GetById(options.Id);
                        if (!string.IsNullOrEmpty(options.Title))
                        {
                            splist.Title = options.Title;
                        }
                        if (options.Description != null)
                        {
                            splist.Description = options.Description;
                        }
                        splist.Update();
                        clientContext.ExecuteQuery();

                        if (listBase != null)
                        {
                            listBase.ApplicationKey = splist.Title;
                        }
                    }
                }
                if (listBase != null)
                {
                    listBase.ViewId = options.DefaultViewId ?? Guid.Empty;
                    listDataService.AddUpdate(listBase);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPListService.Update() method. The exception message is: {1}", ex.GetType(), ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }