Esempio n. 1
0
        public ActionResult SiteLists()
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);

            SiteInfo info = new SiteInfo();

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                try
                {
                    SP.Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    GetContentTypes(info, clientContext, web);

                    GetListsAndLibraries(info, clientContext, web);
                }
                catch (Exception ex)
                {
                    info.Messages.Add("Error");
                }
            }
            return(PartialView("SiteLists", info));
        }
Esempio n. 2
0
        /// <summary>
        /// Gets content type data
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="contentTypeNames">Content type names</param>
        /// <returns>IList object</returns>
        internal static IList <ContentType> GetContentTypeData(ClientContext clientContext, IList <string> contentTypeNames)
        {
            ContentTypeCollection contentTypeCollection         = null;
            IList <ContentType>   selectedContentTypeCollection = null;

            if (null != clientContext && null != contentTypeNames)
            {
                Microsoft.SharePoint.Client.Web web = clientContext.Web;
                contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection);
                clientContext.ExecuteQuery();
                selectedContentTypeCollection = new List <ContentType>();
                foreach (string contentTypeName in contentTypeNames)
                {
                    foreach (ContentType contentType in contentTypeCollection)
                    {
                        if (string.Equals(contentTypeName, contentType.Name))
                        {
                            selectedContentTypeCollection.Add(contentType);
                        }
                    }
                }
            }
            return(selectedContentTypeCollection);
        }
        public void MockEntryResponseProvider_Web_Test_GetPropertyBag()
        {
            MockEntryResponseProvider provider = new MockEntryResponseProvider();

            provider.ResponseEntries.Add(new MockResponseEntry()
            {
                Url          = TestSiteUrl,
                PropertyName = "AllProperties",
                ReturnValue  = new
                {
                    _ObjectType_ = "SP.PropertyValues",
                    Prop1        = "Test Property 1",
                    Prop2        = "Test Property 2",
                }
            });
            using (ClientContext context = new ClientContext(TestSiteUrl))
            {
                context.WebRequestExecutorFactory = new MockWebRequestExecutorFactory(provider);
                Microsoft.SharePoint.Client.Web currentWeb = context.Web;
                PropertyValues allProperties = currentWeb.AllProperties;
                context.Load(allProperties);
                context.ExecuteQuery();

                Assert.AreEqual("Test Property 1", allProperties["Prop1"]);
                Assert.AreEqual("Test Property 2", allProperties["Prop2"]);
            }
        }
Esempio n. 4
0
        public spClient.ListItemCollection getSharePointData(string subProjectRiskUrl, string query)
        {
            spClient.ListItemCollection collectionList = null;
            try
            {
                string[] validUrlApi = subProjectRiskUrl.Split(new string[] { "/Lists/" }, StringSplitOptions.None);
                string   newriskUrl  = subProjectRiskUrl;
                if (validUrlApi.Length != 0)
                {
                    newriskUrl = validUrlApi[0] + "/";
                }
                using (spClient.ClientContext ctx = new spClient.ClientContext(newriskUrl))
                {
                    var passWord = new SecureString();
                    foreach (var c in "intel@123")
                    {
                        passWord.AppendChar(c);
                    }
                    ctx.Credentials = new spClient.SharePointOnlineCredentials("*****@*****.**", passWord);

                    spClient.Web       myWeb   = ctx.Web;
                    spClient.List      proList = myWeb.Lists.GetByTitle("Risk List");
                    spClient.CamlQuery myQuery = new spClient.CamlQuery();
                    myQuery.ViewXml = query;
                    collectionList  = proList.GetItems(myQuery);
                    ctx.Load(collectionList);
                    ctx.ExecuteQuery();
                }
            }
            catch (Exception e)
            {
                collectionList = null;
            }
            return(collectionList);
        }
Esempio n. 5
0
        public ActionResult ScanTemplates(List <string> urls)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);
            var scanInfo  = new ScanTemplateInfo();
            var listInfo  = new List <FormInformation>();

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                foreach (var url in urls)
                {
                    try
                    {
                        SP.Web web = clientContext.Site.RootWeb;

                        var file = web.GetFileByServerRelativeUrl(url);

                        FormInformation info = InfoPathAnalytics.FormInformation(clientContext, file);
                        info.XsnUrl = file.ServerRelativeUrl;

                        listInfo.Add(info);
                    }
                    catch
                    {
                        scanInfo.AddMessage(url);
                    }
                }
            }
            scanInfo.FormInfos = listInfo;

            return(View(scanInfo));
        }
Esempio n. 6
0
        /// <summary>
        /// This method will get all content types from the specified content type group and will filter out the content types that user has selected
        /// when creating the matter
        /// </summary>
        /// <param name="clientContext">The sharepoint context object</param>
        /// <param name="contentTypesNames">Content Type Names that user selected in the create matter screen</param>
        /// <param name="client">The client object which contains information for which client the matter is getting created and the url of the client</param>
        /// <param name="matter">The matter information that is getting created</param>
        /// <returns></returns>
        public IList <ContentType> GetContentTypeData(ClientContext clientContext, IList <string> contentTypesNames, Client client, Matter matter)
        {
            ContentTypeCollection contentTypeCollection         = null;
            IList <ContentType>   selectedContentTypeCollection = new List <ContentType>();

            try
            {
                if (null != clientContext && null != contentTypesNames)
                {
                    Microsoft.SharePoint.Client.Web web = clientContext.Web;
                    string contentTypeName = contentTypesConfig.OneDriveContentTypeGroup.Trim();
                    contentTypeCollection = web.ContentTypes;
                    clientContext.Load(contentTypeCollection, contentType => contentType.Include(thisContentType => thisContentType.Name).Where(currContentType => currContentType.Group == contentTypeName));
                    clientContext.ExecuteQuery();
                    selectedContentTypeCollection = GetContentTypeList(contentTypesNames, contentTypeCollection.ToList());
                }
            }
            catch (Exception exception)
            {
                customLogger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }

            return(selectedContentTypeCollection);
        }
Esempio n. 7
0
        /// <summary>
        /// Retrieves the server-relative URL of a folder from its absolute URL.
        /// </summary>
        /// <param name="webUrl">Web URL to establish context.</param>
        /// <param name="folderUrl">folder URL</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>The server-relative folder URL if found. Null otherwise.</returns>
        private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password)
        {
            string methodName = "SharePointManager2003.GetFolderUrlDirect";

            try
            {
                SP.ClientContext context = new SP.ClientContext(webUrl);
                context.Credentials = new NetworkCredential(username, password);

                // load the web data
                SP.Web web = context.Web;
                context.Load(web);

                // load the folder data
                Uri       uri    = new Uri(folderUrl);
                SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath);
                context.Load(folder);

                context.ExecuteQuery();

                // check if the URL belongs to a folder
                if (folder != null)
                {
                    return(folder.ServerRelativeUrl);
                }

                return(null);
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e);
                return(null);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Creates the type of the content.
        /// </summary>
        /// <param name="clientContext">The client context.</param>
        /// <param name="web">Object of site</param>
        /// <param name="siteColumns">The site columns.</param>
        /// <param name="contentTypeName">Name of Content Type</param>
        internal static bool CreateContentType(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, List <string> siteColumns, string contentTypeName, string contentTypegroup)
        {
            bool        status            = true;
            ContentType parentContentType = null;

            try
            {
                ContentTypeCollection contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection);
                clientContext.Load(web.Fields);
                clientContext.ExecuteQuery();
                parentContentType = (from ct in contentTypeCollection
                                     where ct.Name == ServiceConstantStrings.OneDriveParentContentType
                                     select ct).FirstOrDefault();
                ContentTypeCreationInformation contentType = new ContentTypeCreationInformation();
                contentType.Name  = contentTypeName;
                contentType.Group = contentTypegroup;
                ///// contentType.Id = "0x010100B1ED198475FB3A4AABC59AAAD89B7EAD";
                if (parentContentType != null)
                {
                    contentType.ParentContentType = parentContentType;
                }
                ContentType finalObj = web.ContentTypes.Add(contentType);
                AddColumnsToContentType(web, siteColumns, finalObj);
                web.Update();
                clientContext.ExecuteQuery();
            }
            catch (Exception exception)
            {
                status = false;
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(status);
        }
        public static string GetSettingsUrl(this SPClient.ContentType ct, TreeNode selectedNode)
        {
            // Link: <sitecollection|web>/_layouts/ManageContentType.aspx?ctype=0x0101009148F5A04DDD49CBA7127AADA5FB792B006973ACD696DC4858A76371B2FB2F439A
            // Link: <sitecollection|web>/_layouts/ManageContentType.aspx?List=%7BF798C4D9%2DEF29%2D4F8D%2DA1F1%2D4C70CFBAECE4%7D&ctype=0x010100A204AFB24228A94AB2D6195EB1705291

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?ctype={1}", site.RootWeb.GetUrl(), ct.Id));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
            {
                // <sitecollection>/<web>/_layouts/15/ManageContentType.aspx?ctype=0x00A7470EADF4194E2E9ED1031B61DA088403000BE6CEFFF1ACA6429D14B2B7E0A03FE2
                // <sitecollection>/<web>/_layouts/15/start.aspx#/_layouts/15/ManageContentType.aspx?ctype=0x00A7470EADF4194E2E9ED1031B61DA088403000BE6CEFFF1ACA6429D14B2B7E0A03FE2&Source=https%3A%2F%2Fbramdejager%2Esharepoint%2Ecom%2Fsub%2F%5Flayouts%2F15%2Fmngctype%2Easpx

                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?ctype={1}", web.GetUrl(), ct.Id));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.List)
            {
                SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?list={1}&ctype={2}", list.ParentWeb.GetUrl(), list.Id, ct.Id));
            }
            else
            {
                return(string.Empty);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Determines whether the content type exists in the content type group under the specified client context.
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="web">Object of site</param>
        /// <param name="receivedContentType">Type of the received content</param>
        /// <param name="contentTypeGroup">The content type group</param>
        /// <param name="siteColumns">List of site columns</param>
        internal static bool IsContentTypePresentCheck(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, string receivedContentType, string contentTypeGroup, List <string> siteColumns)
        {
            bool status = true;

            try
            {
                ContentTypeCollection contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection, contentTypes => contentTypes.Include(contentTypeProperties => contentTypeProperties.Group, contentTypeProperties => contentTypeProperties.Name).Where(contentTypeValues => (contentTypeValues.Group == ServiceConstantStrings.OneDriveContentTypeGroup) && (contentTypeValues.Name == ServiceConstantStrings.OneDriveContentTypeName)));
                clientContext.ExecuteQuery();

                if (0 < contentTypeCollection.Count)
                {
                    FieldCollection fields = contentTypeCollection[0].Fields;
                    clientContext.Load(fields, field => field.Include(fieldType => fieldType.Title).Where(column => column.Title == ServiceConstantStrings.OneDriveSiteColumn));
                    clientContext.ExecuteQuery();
                    if (0 == fields.Count)
                    {
                        BriefcaseContentTypeHelperFunctions.AddColumnsToContentType(web, siteColumns, contentTypeCollection[0]);
                        web.Update();
                        clientContext.ExecuteQuery();
                    }
                }
                else
                {
                    status = BriefcaseContentTypeHelperFunctions.CreateContentType(clientContext, web, siteColumns, receivedContentType, contentTypeGroup);
                }
            }
            catch (Exception exception)
            {
                status = false;
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(status);
        }
Esempio n. 11
0
        /// <summary>
        /// Returns the WebDav URL for the current web.
        /// </summary>
        /// <param name="web"></param>
        /// <remarks>A webdav URL looks like: \\webapplicationurl@SSL\DavWWWRoot\sites\sitecollection</remarks>
        /// <returns></returns>
        public static string GetSiteWebDavUrl(this SPClient.Web web)
        {
            Uri    webUri    = new Uri(web.GetUrl());
            string webDavUrl = string.Format("\\\\{0}@SSL\\DavWWWRoot{1}", webUri.DnsSafeHost, webUri.AbsolutePath.Replace('/', '\\'));

            return(webDavUrl);
        }
        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);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Breaks permission for user
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="matterName">Matter name</param>
        /// <param name="copyPermissionsFromParent">Copy permissions from parent</param>
        /// <param name="calendarName">Calendar name</param>
        /// <returns>Boolean value</returns>
        internal static bool BreakPermission(ClientContext clientContext, string matterName, bool copyPermissionsFromParent, string calendarName = null)
        {
            bool flag = false;

            try
            {
                Microsoft.SharePoint.Client.Web web = clientContext.Web;
                string matterOrCalendar             = !string.IsNullOrWhiteSpace(calendarName) ? calendarName : matterName;
                List   list = web.Lists.GetByTitle(matterOrCalendar);
                clientContext.Load(list, l => l.HasUniqueRoleAssignments);
                clientContext.ExecuteQuery();
                if (!list.HasUniqueRoleAssignments)
                {
                    list.BreakRoleInheritance(copyPermissionsFromParent, true);
                    list.Update();
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();
                    flag = true;
                }
            }
            catch (Exception exception)
            {
                Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + "Matter name: " + exception.Message + matterName + "\nStacktrace: " + exception.StackTrace);
                throw;
            }
            return(flag);
        }
Esempio n. 14
0
        /// <summary>
        /// Function to check user full permission on document library
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="matter"></param>
        /// <returns></returns>
        public bool CheckUserFullPermission(ClientContext clientContext, Matter matter)
        {
            bool result = false;

            try
            {
                if (null != matter)
                {
                    Microsoft.SharePoint.Client.Web web = clientContext.Web;
                    List           list          = web.Lists.GetByTitle(matter.Name);
                    Users          userDetails   = GetLoggedInUserDetails(clientContext);
                    Principal      userPrincipal = web.EnsureUser(userDetails.Name);
                    RoleAssignment userRole      = list.RoleAssignments.GetByPrincipal(userPrincipal);
                    clientContext.Load(userRole, userRoleProperties => userRoleProperties.Member,
                                       userRoleProperties => userRoleProperties.RoleDefinitionBindings.Include(userRoleDefinition => userRoleDefinition.Name).Where(userRoleDefinitionName => userRoleDefinitionName.Name ==
                                                                                                                                                                    matterSettings.EditMatterAllowedPermissionLevel));
                    clientContext.ExecuteQuery();
                    if (0 < userRole.RoleDefinitionBindings.Count)
                    {
                        result = true;
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
        }
Esempio n. 15
0
        public static string GetSettingsUrl(this SPClient.Field field, TreeNode selectedNode)
        {
            // <sitecollection|web>/_layouts/FldEditEx.aspx?field=Instructie
            // <sitecollection|web>/_layouts/FldEdit.aspx?List=%7BCEBB8CB0%2DC088%2D4BEE%2DBF17%2DE6A8CD5F6C9F%7D&Field=Title

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                // <sitecollection>/_layouts/15/fldedit.aspx?field=%5FEndDate&Source=%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", site.RootWeb.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
            {
                // <sitecollection>/<web>/_layouts/15/fldedit.aspx?field=Sub%5Fx0020%5FSite%5Fx0020%5FColumn&Source=%2Fsub%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", web.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.List)
            {
                // <sitecollection>/<web>/_layouts/15/FldEditEx.aspx?List=%7B051E4502%2D504E%2D49C8%2DA815%2DF46BFD61911D%7D&Field=Modified

                SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
                return(string.Format("{0}/_layouts/FldEditEx.aspx?list={1}&field={2}", list.ParentWeb.GetUrl(), list.Id, field.InternalName));
            }
            else
            {
                return(string.Empty);
            }
        }
        public void DeleteItemByQuery(string ListName, ICamlQuery Query)
        {
            try
            {
                SP.Web       web   = context.Web;
                SP.List      list  = web.Lists.GetByTitle(ListName);
                SP.CamlQuery query = (SP.CamlQuery)Query.ExecuteQuery();

                SP.ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                if (items != null)
                {
                    foreach (SP.ListItem item in items)
                    {
                        item.DeleteObject();
                        context.Load(item);
                    }
                    context.ExecuteQuery();
                }
                else
                {
                    throw new Exception("Item does not exist");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating SharePoint list data: " + ex.Message);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Assigns content type
        /// </summary>
        /// <param name="clientcontext">SP client context</param>
        /// <param name="matterMetadata">Object containing metadata for Matter</param>
        internal static void AssignContentType(ClientContext clientcontext, MatterMetadata matterMetadata)
        {
            // For each value in the list of Content Type Names
            // Add that content Type to the Library
            string defaultContentType = matterMetadata.ContentTypes[0];

            try
            {
                // Returns the selected Content types from the Site Content Types
                IList <ContentType> contentTypeCollection = GetContentTypeData(clientcontext, matterMetadata.ContentTypes);
                if (null != contentTypeCollection)
                {
                    Microsoft.SharePoint.Client.Web web = clientcontext.Web;
                    List            matterList          = web.Lists.GetByTitle(matterMetadata.Matter.MatterName);
                    FieldCollection fields = GetContentType(clientcontext, contentTypeCollection, matterList);
                    matterMetadata = GetWSSId(clientcontext, matterMetadata, fields);
                    MatterProvisionHelper.SetFieldValues(matterMetadata, fields);
                    clientcontext.ExecuteQuery();
                    SetDefaultContentType(clientcontext, matterList, defaultContentType);
                    MatterProvisionHelper.CreateView(clientcontext, matterList);
                }
            }
            // SharePoint Specific Exception
            catch (Exception exception)
            {
                Utility.DisplayAndLogError(Utility.ErrorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "assigning ContentType"));
                Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "Matter name: " + matterMetadata.Matter.MatterName + "\nStacktrace: " + exception.StackTrace);
                throw;
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Creates site column.
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="web">Object of site</param>
        /// <param name="siteColumns">List of site columns</param>
        /// <returns>Success or Failure</returns>
        internal static bool CreateSiteColumn(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, List <string> siteColumns)
        {
            bool result = false;

            try
            {
                FieldCollection fieldCol = web.Fields;
                clientContext.Load(fieldCol);
                clientContext.ExecuteQuery();
                List <Field> existingFields = fieldCol.ToList <Field>();
                foreach (string columns in siteColumns)
                {
                    Field field = (from fld in existingFields
                                   where fld.Title == columns && fld.TypeAsString == ServiceConstantStrings.OneDriveSiteColumnType
                                   select fld).FirstOrDefault();
                    if (null == field)
                    {
                        web.Fields.AddFieldAsXml(string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.OneDriveSiteColumnSchema, ServiceConstantStrings.OneDriveSiteColumn, ServiceConstantStrings.OneDriveContentTypeGroup), true, AddFieldOptions.DefaultValue);
                        web.Update();
                        clientContext.ExecuteQuery();
                    }
                }
                result = true;
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = false;
            }
            return(result);
        }
Esempio n. 19
0
        public Web CreateSubSite(Microsoft.SharePoint.Client.ClientContext ctx, Web hostWeb, string txtUrl,
                                 string template, string title, string description)
        {
            // Create web creation configuration
            WebCreationInformation information = new WebCreationInformation();

            information.WebTemplate = template;
            information.Description = description;
            information.Title       = title;
            information.Url         = txtUrl;
            // Currently all english, could be extended to be configurable based on language pack usage
            information.Language = 1033;

            Microsoft.SharePoint.Client.Web newWeb = null;
            newWeb = hostWeb.Webs.Add(information);
            ctx.ExecuteQuery();

            ctx.Load(newWeb);
            ctx.ExecuteQuery();

            // Add sub site link override
            new LabHelper().AddJsLink(ctx, newWeb, this.Request);

            // Set oob theme to the just created site
            new LabHelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "Orange");

            // All done, let's return the newly created site
            return(newWeb);
        }
Esempio n. 20
0
    private void GetDocIDURL(ref StringBuilder permaurl)
    {
        string ctxurl = permaurl.ToString(0, 24);
        string relurl = permaurl.Replace("https://sp.contoso.com", "").ToString();

        // Starting with ClientContext, the constructor requires a URL to the
        // server running SharePoint.
        SP.ClientContext context = new SP.ClientContext(ctxurl);
        // The SharePoint web at the URL.
        SP.Web web = context.Web;
        // Load
        context.Load(web);
        // Execute query.
        context.ExecuteQuery();
        //
        SP.File     ObjFile = web.GetFileByServerRelativeUrl(relurl);
        SP.ListItem item    = ObjFile.ListItemAllFields;
        //
        context.Load(ObjFile);
        context.Load(item);
        context.ExecuteQuery();
        //
        //string fileName = item.FieldValues["FileLeafRef"].ToString();
        //string fileType = System.IO.Path.GetExtension(fileName);
        //Guid uniqueId = new Guid(item.FieldValues["UniqueId"].ToString());
        var furl = item.FieldValues["_dlc_DocIdUrl"] as SP.FieldUrlValue;

        permaurl.Clear();
        permaurl.Append(furl.Url);
    }
Esempio n. 21
0
        /// <summary>
        /// Sets the upload item properties.
        /// </summary>
        /// <param name="clientContext">The client context.</param>
        /// <param name="web">The web.</param>
        /// <param name="documentLibraryName">Name of the document library.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="folderPath">Path of the folder.</param>
        /// <param name="mailProperties">The mail properties.</param>
        public static void SetUploadItemProperties(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, string documentLibraryName, string fileName, string folderPath, Dictionary <string, string> mailProperties)
        {
            ListItemCollection items    = null;
            ListItem           listItem = null;

            if (null != clientContext && null != web && !string.IsNullOrEmpty(documentLibraryName) && !string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(folderPath) && null != mailProperties)
            {
                ListCollection lists              = web.Lists;
                CamlQuery      query              = new CamlQuery();
                List           selectedList       = lists.GetByTitle(documentLibraryName);
                string         serverRelativePath = folderPath + ConstantStrings.ForwardSlash + fileName;
                query.ViewXml = string.Format(CultureInfo.InvariantCulture, ConstantStrings.GetAllFilesInFolderQuery, serverRelativePath);
                items         = selectedList.GetItems(query);
                if (null != items)
                {
                    clientContext.Load(items, item => item.Include(currentItem => currentItem.DisplayName, currentItem => currentItem.File.Name).Where(currentItem => currentItem.File.Name == fileName));
                    clientContext.ExecuteQuery();
                    if (0 < items.Count)
                    {
                        listItem = items[0];
                        if (null != mailProperties)
                        {
                            listItem[ConstantStrings.SearchEmailFrom] = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailSenderKey]) ? mailProperties[ConstantStrings.MailSenderKey].Trim() : string.Empty;
                            if (!string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailReceivedDateKey]))
                            {
                                listItem[ConstantStrings.SearchEmailReceivedDate] = Convert.ToDateTime(mailProperties[ConstantStrings.MailReceivedDateKey].Trim(), CultureInfo.InvariantCulture).ToUniversalTime();
                            }
                            else
                            {
                                listItem[ConstantStrings.SearchEmailReceivedDate] = null;
                            }
                            listItem[ConstantStrings.SearchEmailCC]                = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailCCAddressKey]) ? mailProperties[ConstantStrings.MailCCAddressKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailAttachments]       = (string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailHasAttachmentsKey]) || mailProperties[ConstantStrings.MailHasAttachmentsKey].Equals(ConstantStrings.TRUE, StringComparison.OrdinalIgnoreCase)) ? mailProperties[ConstantStrings.MailAttachmentKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailFromMailbox]       = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailSearchEmailFromMailboxKey]) ? mailProperties[ConstantStrings.MailSearchEmailFromMailboxKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailSubject]           = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailSearchEmailSubject]) ? mailProperties[ConstantStrings.MailSearchEmailSubject].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailTo]                = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailReceiverKey]) ? mailProperties[ConstantStrings.MailReceiverKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailImportance]        = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailImportanceKey]) ? mailProperties[ConstantStrings.MailImportanceKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailSensitivity]       = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailSensitivityKey]) ? mailProperties[ConstantStrings.MailSensitivityKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailHasAttachments]    = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailHasAttachmentsKey]) ? mailProperties[ConstantStrings.MailHasAttachmentsKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailConversationId]    = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailConversationIdKey]) ? mailProperties[ConstantStrings.MailConversationIdKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailConversationTopic] = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailConversationTopicKey]) ? mailProperties[ConstantStrings.MailConversationTopicKey].Trim() : string.Empty;
                            listItem[ConstantStrings.SearchEmailCategories]        = GetCategories(mailProperties[ConstantStrings.MailCategoriesKey].Trim());
                            if (!string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailSentDateKey]))
                            {
                                listItem[ConstantStrings.SearchEmailSentDate] = Convert.ToDateTime(mailProperties[ConstantStrings.MailSentDateKey].Trim(), CultureInfo.InvariantCulture).ToUniversalTime();
                            }
                            else
                            {
                                listItem[ConstantStrings.SearchEmailSentDate] = null;
                            }
                            listItem[ConstantStrings.SearchEmailOriginalName] = !string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailOriginalName]) ? mailProperties[ConstantStrings.MailOriginalName] : string.Empty;
                            listItem.Update();
                            clientContext.ExecuteQuery();
                            listItem.RefreshLoad();
                        }
                    }
                }
            }
        }
        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);
            }
        }
 public void Dispose()
 {
     if (_context != null)
     {
         _context.Dispose();
     }
     _context = null;
     _web     = null;
 }
Esempio n. 24
0
        public static string GetWebUrl(this SPClient.Web web)
        {
            if (!web.IsPropertyAvailable("Title"))
            {
                web.Context.Load(web);
                web.Context.ExecuteQuery();
            }

            return(string.Format("{0}/{1}", web.Context.Url, web.ServerRelativeUrl.ToLower().Replace(new Uri(web.Context.Url.ToLower()).AbsolutePath, "")));
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the URL for the current web.
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static string GetUrl(this SPClient.Web web)
        {
            if (!web.IsPropertyAvailable("Url"))
            {
                web.Context.Load(web);
                web.Context.ExecuteQuery();
            }

            return(web.Url);
        }
        public static string GetAppRedirectUrl(this SPClient.AppInstance appInstance, TreeNode selectedNode)
        {
            // How do I use the appredirect page in the URL? You can use the app redirect page by URL-encoding, as follows:
            // https://sitecollection/web/_layouts/15/appredirect.aspx?instance_id=<AppClientId>&redirect_uri=<redirectURL>

            SPClient.Web web = (SPClient.Web)selectedNode.Parent.Parent.Tag;

            return(string.Format("{0}/_layouts/15/appredirect.aspx?instance_id={1}",
                                 web.GetUrl(),
                                 appInstance.Id));
        }
Esempio n. 27
0
 public void ConnectSharePointOnline()
 {
     using (SP.ClientContext context = new SP.ClientContext(siteUrl))
     {
         context.Credentials = new SP.SharePointOnlineCredentials(userName, securePass);
         SP.Web web = context.Web;
         context.Load(web);
         context.ExecuteQuery();
         Console.WriteLine("Web Title is " + web.Title);
     }
 }
Esempio n. 28
0
 private List<web> GetSubWebsInternal(web subweb)
 {
     var subwebs = new List<web>();
     var webs = subweb.Context.LoadQuery(subweb.Webs);
     subweb.Context.ExecuteQueryRetry();
     subwebs.AddRange(webs);
     foreach (var sw in webs)
     {
         subwebs.AddRange(GetSubWebsInternal(sw));
     }
     return subwebs;
 }
Esempio n. 29
0
        public ActionResult Documents(string libId)
        {
            var  info = new DocumentInfo();
            Guid libraryId;

            if (!Guid.TryParse(libId, out libraryId))
            {
                info.AddMessage("Cannot get documents invalid library id.");
                return(View(info));
            }

            var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                try
                {
                    SP.Web web = clientContext.Web;

                    var library = web.Lists.GetById(libraryId);
                    clientContext.Load(library);
                    clientContext.ExecuteQuery();

                    if (!DocumentTypeBaseId.Any(id => id == library.BaseTemplate))
                    {
                        info.AddMessage("Cannot get documents invalid library.");
                        return(View(info));
                    }

                    var camlQuery = new CamlQuery
                    {
                        ViewXml = "<View><Query><Where><Contains><FieldRef Name='FileLeafRef'/>" +
                                  "<Value Type='String'>.xsn</Value>" +
                                  "</Contains></Where></Query></View>"
                    };

                    var listItems = library.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();

                    foreach (var item in listItems)
                    {
                        info.ItemInfo.Add(new ListItemInfo(item));
                    }
                    return(View(info));
                }
                catch
                {
                    info.AddMessage("There was an error while getting documents.");
                    return(View(info));
                }
            }
        }
Esempio n. 30
0
 protected override void ExecuteCmdlet()
 {
     if (ParameterSetName == "List")
     {
         var list = this.SelectedWeb.GetList(List);
         WriteObject(list.AddRemoteEventReceiver(Name, Url, EventReceiverType, Synchronization, Force));
     }
     else
     {
         Microsoft.SharePoint.Client.Web web = SelectedWeb;
         WriteObject(this.SelectedWeb.AddRemoteEventReceiver(Name, Url, EventReceiverType, Synchronization, Force));
     }
 }
Esempio n. 31
0
        private List <web> GetSubWebsInternal(web subweb)
        {
            var subwebs = new List <web>();
            var webs    = subweb.Context.LoadQuery(subweb.Webs);

            subweb.Context.ExecuteQueryRetry();
            subwebs.AddRange(webs);
            foreach (var sw in webs)
            {
                subwebs.AddRange(GetSubWebsInternal(sw));
            }
            return(subwebs);
        }