private static void ApplyProvisioningTemplateToSite(ClientContext context, String siteUrl, String folder, String fileName, Dictionary<String, String> parameters = null, Handlers handlers = Handlers.All)
        {
            // Configure the XML file system provider
            XMLTemplateProvider provider =
                new XMLSharePointTemplateProvider(context, siteUrl,
                    PnPPartnerPackConstants.PnPProvisioningTemplates +
                    (!String.IsNullOrEmpty(folder) ? "/" + folder : String.Empty));

            // Load the template from the XML stored copy
            ProvisioningTemplate template = provider.GetTemplate(fileName);
            template.Connector = provider.Connector;

            ProvisioningTemplateApplyingInformation ptai = 
                new ProvisioningTemplateApplyingInformation();

            // We exclude Term Groups because they are not supported in AppOnly
            ptai.HandlersToProcess = handlers;
            ptai.HandlersToProcess ^= Handlers.TermGroups;

            // Handle any custom parameter
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    template.Parameters.Add(parameter.Key, parameter.Value);
                }
            }

            // Apply the template to the target site
            context.Site.RootWeb.ApplyProvisioningTemplate(template, ptai);
        }
        public void Execute(ClientContext ctx, string library, Uri url, string description)
        {
            Logger.Verbose($"Started executing {nameof(AddLinkToLinkList)} for url '{url}' on library '{library}'");

            var web = ctx.Web;
            var links = web.Lists.GetByTitle(library);
            var result = links.GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(result);
            ctx.ExecuteQuery();

            var existingLink =
                result
                    .ToList()
                    .Any(l =>
                    {
                        var u = (FieldUrlValue)l.FieldValues["URL"];
                        return u.Url == url.ToString() && u.Description == description;
                    });

            if (existingLink)
            {
                Logger.Warning($"Link '{url}' with description '{description}' already exists");
                return;
            }

            var newLink = links.AddItem(new ListItemCreationInformation());
            newLink["URL"] = new FieldUrlValue { Url = url.ToString(), Description = description };
            newLink.Update();
            ctx.ExecuteQuery();
        }
        public void Execute(ClientContext ctx, string listTitle, XElement schema, Action<Field> setAdditionalProperties = null)
        {
            var displayName = schema.Attribute("DisplayName").Value;
            Logger.Verbose($"Started executing {nameof(CreateColumnOnList)} for column '{displayName}' on list '{listTitle}'");

            var list = ctx.Web.Lists.GetByTitle(listTitle);
            var fields = list.Fields;
            ctx.Load(fields);
            ctx.ExecuteQuery();

            // if using internal names in code, remember to encode those before querying, e.g., 
            // space character becomes "_x0020_" as described here:
            // http://www.n8d.at/blog/encode-and-decode-field-names-from-display-name-to-internal-name/
            // We don't use the internal name here because it's limited to 32 chacters. This means
            // "Secondary site abcde" is the longest possible internal name when taken into account
            // the "_x0020_" character. Using a longer name will truncate the internal name to 32
            // characters. Thus querying on the complete, not truncated name, will always return no
            // results which causes the field get created repetedly.
            var field = fields.SingleOrDefault(f => f.Title == displayName);
            if (field != null)
            {
                Logger.Warning($"Column '{displayName}' already on list {listTitle}");
                return;
            }

            var newField = list.Fields.AddFieldAsXml(schema.ToString(), true, AddFieldOptions.DefaultValue);
            ctx.Load(newField);
            ctx.ExecuteQuery();

            if (setAdditionalProperties != null)
            {
                setAdditionalProperties(newField);
                newField.Update();
            }
        }
        /// <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)
                {                   

                    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;
        }
Beispiel #5
0
        private static void SetDocumentAsTemplate(ClientContext cc, Web web)
        {
            ContentType ct = web.ContentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB3");
            cc.Load(ct); 
            cc.ExecuteQuery();

            // Get instance to the _cts folder created for the each of the content types
            string ctFolderServerRelativeURL = "_cts/" + ct.Name;
            Folder ctFolder = web.GetFolderByServerRelativeUrl(ctFolderServerRelativeURL);
            cc.Load(ctFolder);
            cc.ExecuteQuery();

            // Load the local template document
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "template.docx");
            string fileName = System.IO.Path.GetFileName(path);
            byte[] filecontent = System.IO.File.ReadAllBytes(path);

            // Uplaod file to the Office365
            using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open))
            {
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = filecontent;
                newFile.Url = ctFolderServerRelativeURL + "/" + fileName;

                Microsoft.SharePoint.Client.File uploadedFile = ctFolder.Files.Add(newFile);
                cc.Load(uploadedFile);
                cc.ExecuteQuery();
            }


            ct.DocumentTemplate = fileName;
            ct.Update(true);
            cc.ExecuteQuery();
            Console.WriteLine("Document template uploaded and set to the content type.");
        }
Beispiel #6
0
 public void SetProperties(ClientContext context, Web webToConfigure, Dictionary<string, string> properties)
 {
     foreach (KeyValuePair<string, string> property in properties)
     {
         SetProperty(context, webToConfigure, property);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Assumption
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string siteUrl = GetSite();

            /* Prompt for Credentials */
            Console.WriteLine("Enter Credentials for {0}", siteUrl);

            string userName = GetUserName();
            SecureString pwd = GetPassword();

            /* End Program if no Credentials */
            if (string.IsNullOrEmpty(userName) || (pwd == null))
                return;

            // Open connection to Office365 tenant
            ClientContext cc = new ClientContext(siteUrl);
            cc.AuthenticationMode = ClientAuthenticationMode.Default;
            cc.Credentials = new SharePointOnlineCredentials(userName, pwd);

            // Load reference to content type collection
            Web web = cc.Web;
            CreateContentTypeIfDoesNotExist(cc, web);
            SetDocumentAsTemplate(cc, web);

            // Just to pause
            Console.WriteLine("Modification completed successfully, press enter to continue");
            Console.ReadLine();
        }
Beispiel #8
0
        private static void CreateContentTypeIfDoesNotExist(ClientContext cc, Web web)
        {
            ContentTypeCollection contentTypes = web.ContentTypes;
            cc.Load(contentTypes);
            cc.ExecuteQuery();

            foreach (var item in contentTypes)
            {
                if (item.StringId == "0x0101009189AB5D3D2647B580F011DA2F356FB3")
                    return;
            }

            // Create a Content Type Information object
            ContentTypeCreationInformation newCt = new ContentTypeCreationInformation();
            // Set the name for the content type
            newCt.Name = "Contoso Sample Document";
            //Inherit from oob document - 0x0101 and assign 
            newCt.Id = "0x0101009189AB5D3D2647B580F011DA2F356FB3";
            // Set content type to be avaialble from specific group
            newCt.Group = "Contoso Content Types";
            // Create the content type
            ContentType myContentType = contentTypes.Add(newCt);
            cc.ExecuteQuery();

            Console.WriteLine("Content type created.");
        }
Beispiel #9
0
 public SiteModelHost(ClientContext clientContext)
 {
     HostClientContext = clientContext;
     
     HostSite = clientContext.Site;
     HostWeb = clientContext.Web;
 }
        /// <summary>
        /// This method will return a ClientContext object with the authentication cookie set.
        /// The ClientContext should be disposed of as any other IDisposable
        /// </summary>
        /// <param name="targetSiteUrl"></param>
        /// <returns></returns>
        public static ClientContext GetAuthenticatedContext(string targetSiteUrl, int popUpWidth, int popUpHeight)
        {
            CookieCollection cookies = null;
            cookies = GetAuthenticatedCookies(targetSiteUrl, popUpWidth, popUpHeight);
            if (cookies == null) return null;

            ClientContext context = new ClientContext(targetSiteUrl);
            try
            {
                context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
                {
                    e.WebRequestExecutor.WebRequest.CookieContainer = new CookieContainer();
                    foreach (Cookie cookie in cookies)
                    {
                        e.WebRequestExecutor.WebRequest.CookieContainer.Add(cookie);
                    }
                };
            }
            catch
            {
                if (context != null) context.Dispose();
                throw;
            }

            return context;
        }
Beispiel #11
0
        public static void UploadDocument(string siteURL, string documentListName, string documentListURL, string DocuSetFolder, string documentName, FileStream documentStream, string status, string version, string contentID, string newFileName)
        {
            using (ClientContext clientContext = new ClientContext(siteURL))
            {

                //Get Document List
                Microsoft.SharePoint.Client.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

                var fileCreationInformation = new FileCreationInformation();
                fileCreationInformation.ContentStream = documentStream;
                //Allow owerwrite of document

                fileCreationInformation.Overwrite = true;
                //Upload URL

                fileCreationInformation.Url = siteURL + documentListURL + DocuSetFolder + newFileName;

                Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
                    fileCreationInformation);

                //Update the metadata for a field

                uploadFile.ListItemAllFields["ContentTypeId"] = contentID;
                uploadFile.ListItemAllFields["Mechanical_x0020_Status"] = status;
                uploadFile.ListItemAllFields["Mechanical_x0020_Version"] = version;
                uploadFile.ListItemAllFields["Comments"] = "Autogenerated upload";

                uploadFile.ListItemAllFields.Update();
                clientContext.ExecuteQuery();

            }
        }
        /// <summary>
        /// Adds a list to a site
        /// </summary>
        /// <param name="properties">Site to operate on</param>
        /// <param name="listType">Type of the list</param>
        /// <param name="featureID">Feature guid that brings this list type</param>
        /// <param name="listName">Name of the list</param>
        /// <param name="enableVersioning">Enable versioning on the list</param>
        public static List AddList(ClientContext ctx, Web web, ListTemplateType listType, string listName)
        {
            ListCollection listCollection = web.Lists;
            ctx.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName));
            ctx.ExecuteQuery();

            if (listCollection.Count == 0)
            {
                ListCollection listCol = web.Lists;
                ListCreationInformation lci = new ListCreationInformation();
                lci.Title = listName;
                lci.TemplateType = (int)listType;
                List newList = listCol.Add(lci);
                newList.Description = "Demo list for remote event receiver lab";
                newList.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' />",true,AddFieldOptions.DefaultValue);
                newList.Fields.AddFieldAsXml("<Field DisplayName='AssignedTo' Type='Text' />",true,AddFieldOptions.DefaultValue);
                newList.Update();
                return newList;
                //ctx.Load(listCol);
                //ctx.ExecuteQuery();                
            }
            else
            {
                return listCollection[0];
            }
        }
Beispiel #13
0
        private static void ProvisionLists(ClientContext ctx)
        {
            Console.WriteLine("Provisioning lists:");
            Console.WriteLine("Events");
            List eventsList = ctx.Web.CreateList(ListTemplateType.Events, "Events", false, false, "Lists/Events", false);
            eventsList.CreateField(@"<Field Type=""Boolean"" DisplayName=""Registration Allowed"" ID=""{d395011d-07c9-40a5-99c2-cb4d4f209d13}"" Name=""OfficeDevPnPRegistrationAllowed""><Default>1</Default></Field>", false);
            ctx.Load(eventsList);
            ctx.ExecuteQueryRetry();

            Console.WriteLine("Event Registration");
            List regList = ctx.Web.CreateList(ListTemplateType.GenericList, "Event Registration", false, false, "Lists/Event Registration", false);
            Field field = regList.CreateField(@"<Field Type=""Lookup"" DisplayName=""Event"" ID=""{39e09239-3da4-455f-9f03-add53034de0a}"" Name=""OfficeDevPnPEventLookup"" />", false);
            ctx.Load(regList);
            ctx.Load(field);
            ctx.ExecuteQueryRetry();

            // configure event lookup field
            FieldLookup eventField = ctx.CastTo<FieldLookup>(field);
            eventField.LookupList = eventsList.Id.ToString();
            eventField.LookupField = "Title";
            eventField.Indexed = true;
            eventField.IsRelationship = true;
            eventField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Cascade;
            eventField.Update();
            ctx.ExecuteQueryRetry();
            // configure author field
            Field authorField = regList.Fields.GetFieldByName<Field>("Author");
            authorField.Indexed = true;
            authorField.Update();
            ctx.ExecuteQueryRetry();

            Console.WriteLine("");
        }
Beispiel #14
0
        private static void ProvisionAssets(ClientContext ctx)
        {
            Console.WriteLine("Provisioning assets:");

            string[] fileNames = {
                                     "jquery-1.11.2.min.js",
                                     "knockout-3.3.0.js",
                                     "event-registration-form.js",
                                     "event-registration-form-template.js"};
            
            List styleLibrary = ctx.Web.Lists.GetByTitle("Style Library");
            ctx.Load(styleLibrary, l => l.RootFolder);
            Folder pnpFolder = styleLibrary.RootFolder.EnsureFolder("OfficeDevPnP");
            foreach (string fileName in fileNames)
            {
                Console.WriteLine(fileName);

                File assetFile = pnpFolder.GetFile(fileName);
                if (assetFile != null)
                    assetFile.CheckOut();

                string localFilePath = "Assets/" + fileName;
                string newLocalFilePath = Utilities.ReplaceTokensInAssetFile(ctx, localFilePath);

                assetFile = pnpFolder.UploadFile(fileName, newLocalFilePath, true);
                assetFile.CheckIn("Uploaded by provisioning engine.", CheckinType.MajorCheckIn);
                ctx.ExecuteQuery();
                System.IO.File.Delete(newLocalFilePath);
            }
            Console.WriteLine("");
        }
Beispiel #15
0
        public SPService(string username, string password, string url)
        {
            using (ClientContext ctx = new ClientContext(url))
            {
                var securePassword = new SecureString();
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }

                var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
                
                ctx.Credentials = onlineCredentials;
                web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                //ctx.GetFormDigestDirect().DigestValue
                var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url));
                //var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray());
                
                webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() };
                
                context = ctx;
            }
        }
        /// <summary>
        /// Creates the OneNote.
        /// </summary>
        /// <param name="clientContext">The client context.</param>
        /// <param name="clientUrl">The client URL.</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <returns>Returns the URL of the OneNote</returns>
        internal static string CreateOneNote(ClientContext clientContext, Uri clientUrl, Matter matter)
        {
            string returnValue = string.Empty;
            try
            {
                byte[] oneNoteFile = System.IO.File.ReadAllBytes("./Open Notebook.onetoc2");

                Microsoft.SharePoint.Client.Web web = clientContext.Web;
                Microsoft.SharePoint.Client.File file = web.GetFolderByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", clientUrl.AbsolutePath, Constants.Backslash, matter.MatterGuid + ConfigurationManager.AppSettings["OneNoteLibrarySuffix"], Constants.Backslash, matter.MatterGuid)).Files.Add(new FileCreationInformation()
                {
                    Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, ConfigurationManager.AppSettings["ExtensionOneNoteTableOfContent"]),
                    Overwrite = true,
                    ContentStream = new MemoryStream(oneNoteFile)
                });
                web.Update();
                clientContext.Load(file);
                clientContext.ExecuteQuery();
                ListItem oneNote = file.ListItemAllFields;
                oneNote["Title"] = matter.MatterName;
                oneNote.Update();
                returnValue = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}", clientUrl.Scheme, Constants.COLON, Constants.Backslash, Constants.Backslash, clientUrl.Authority, file.ServerRelativeUrl, "?Web=1");
            }
            catch (Exception exception)
            {
                Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + "Matter name: " + matter.MatterName + "\n" + exception.Message + "\nStacktrace: " + exception.StackTrace);
                throw;
            }

            return returnValue;
        }
        public static void CloseAllWebParts(ClientContext ctx, string relativePageUrl)
        {
            var webPartPage = ctx.Web.GetFileByServerRelativeUrl(relativePageUrl);
            ctx.Load(webPartPage);
            ctx.ExecuteQuery();

            if (webPartPage == null)
            {
                return;
            }

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
            ctx.ExecuteQueryRetry();

            if (limitedWebPartManager.WebParts.Count >= 0)
            {
                for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++)
                {
                    limitedWebPartManager.WebParts[i].CloseWebPart();
                    limitedWebPartManager.WebParts[i].SaveWebPartChanges();
                }
                ctx.ExecuteQuery();
            }
        }
        public static bool IsWebPartOnPage(ClientContext ctx, string relativePageUrl, string title)
        {
            var webPartPage = ctx.Web.GetFileByServerRelativeUrl(relativePageUrl);
            ctx.Load(webPartPage);
            ctx.ExecuteQuery();

            if (webPartPage == null)
            {
                return false;
            }

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
            ctx.ExecuteQueryRetry();

            if (limitedWebPartManager.WebParts.Count >= 0)
            {
                for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++)
                {
                    WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart;
                    if (oWebPart.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    static void Main() {

      Console.WriteLine("Adding Team Site Content");
      Console.WriteLine();

      clientContext = new ClientContext(siteUrl);

      site = clientContext.Web;
      clientContext.Load(site);      
      clientContext.ExecuteQuery();


      WingtipContentGenerator.CreateProductCategoriesTermset();
      WingtipContentGenerator.CreateProductsLists();

      Console.WriteLine();
      Console.WriteLine("The program has finsihed. Press ENTER to close this window");
      Console.WriteLine();
      Console.ReadLine();






      clientContext.ExecuteQuery();

    }
Beispiel #20
0
        public void CreateNewSiteCollection(string title, string name, string owner)
        {
            var url = string.Format("https://{0}-admin.sharepoint.com", _generatorDefinition.TenantName);
            using (ClientContext context = new ClientContext(url))
            {
                context.Credentials = new SharePointOnlineCredentials(_generatorDefinition.Username, Utilities.Common.StringToSecureString(_generatorDefinition.Password));
                var officeTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context);
                var newSiteProperties = new SiteCreationProperties()
                {
                    Url = string.Format("https://{0}.sharepoint.com/sites/{1}", _generatorDefinition.TenantName, name),
                    Owner = _generatorDefinition.SiteCollOwnerLogin,
                    Template = "STS#0",

                };
                var spo= officeTenant.CreateSite(newSiteProperties);
                context.Load(spo, i => i.IsComplete);
                context.ExecuteQuery();

                while (!spo.IsComplete)
                {
                    System.Threading.Thread.Sleep(10000);
                    spo.RefreshLoad();
                    context.ExecuteQuery();
                }
            }
        }
Beispiel #21
0
        static void Main()
        {
            // get client context
              ClientContext clientContext = new ClientContext("http://intranet.wingtip.com");

              // create variables for CSOM objects
              Site siteCollection = clientContext.Site;
              Web site = clientContext.Web;
              ListCollection lists = site.Lists;

              // give CSOM instructions to populate objects
              clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(lists);

              // make round-trip to SharePoint host to carry out instructions
              clientContext.ExecuteQuery();

              // CSOM object are now initialized
              Console.WriteLine(siteCollection.Id);
              Console.WriteLine(site.Title);
              Console.WriteLine(lists.Count);

              // retrieve another CSOM object
              List list = lists.GetByTitle("Documents");
              clientContext.Load(list);

              // make a second round-trip to SharePoint host
              clientContext.ExecuteQuery();

              Console.WriteLine(list.Title);

              Console.ReadLine();
        }
Beispiel #22
0
        public ActionResult Index()
        {
            User spUser = null;

            var url = "https://website/";
            var accountName = "accountName";
            var password = "******";

            var securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(accountName, securePassword);

            using (var clientContext = new ClientContext(url))
            {
                if (clientContext != null)
                {
                    clientContext.Credentials = onlineCredentials;
                    spUser = clientContext.Web.CurrentUser;
                    clientContext.Load(spUser, user => user.Title);
                    clientContext.ExecuteQuery();
                    ViewBag.UserName = spUser.Title;
                }
            }

            return View();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SPOEmulationContext"/> class.
        /// </summary>
        /// <param name="isolationLevel">The level.</param>
        /// <param name="connectionInformation">The connection informations for the target web.</param>
        public SPOEmulationContext(IsolationLevel isolationLevel, ConnectionInformation connectionInformation)
        {
            this._isolationLevel = isolationLevel;

            switch (isolationLevel)
            {
                case IsolationLevel.Fake:
                    // create shim context
                    _shimsContext = ShimsContext.Create();

                    // initialize all simulated types
                    _clientContext = InitializeSimulatedAPI(connectionInformation.Url);
                    break;
                case IsolationLevel.Integration:
                    // create shim context
                    _shimsContext = ShimsContext.Create();
                    Connect(connectionInformation);
                    break;
                case IsolationLevel.None:
                    Connect(connectionInformation);
                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
        public ActionResult About()
        {
            Global.globalError1 += "Only World No Hello, ";
            using (ClientContext clientContext = new ClientContext("https://stebra.sharepoint.com/sites/sd1"))
            {

                if (clientContext != null)
                {

                    string userName = "******";

                    SecureString passWord = new SecureString();
                    string passStr = "Simoon123";
                    foreach (char c in passStr.ToCharArray()) passWord.AppendChar(c);

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
                    new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
                }
            }

            //        var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{ new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); }

            ViewBag.RemoteEvent = " Hello globalError: " + Global.globalError + " \n globalError1: " + Global.globalError1;
            return View();
        }
Beispiel #25
0
        public string ProcessSiteCreationRequest(ClientContext ctx, SiteCollectionRequest siteRequest)
        {
            // Resolve full URL 
            var webFullUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", siteRequest.TenantName, siteRequest.ManagedPath, siteRequest.Url);

            // Resolve the actual SP template to use
            string siteTemplate = SolveActualTemplate(siteRequest);

            Tenant tenant = new Tenant(ctx);
            if (tenant.SiteExists(webFullUrl))
            {
                // Abort... can't proceed, URL taken.
                throw new InvalidDataException(string.Format("site already existed with same URL as {0}. Process aborted.", webFullUrl));
            }
            else
            {
                // Create new site collection with storage limits and settings from the form
                tenant.CreateSiteCollection(webFullUrl,
                                            siteRequest.Title,
                                            siteRequest.Owner,
                                            siteTemplate,
                                            (int)siteRequest.StorageMaximumLevel,
                                            (int)(siteRequest.StorageMaximumLevel * 0.75),
                                            siteRequest.TimeZoneId,
                                            0,
                                            0,
                                            siteRequest.Lcid);

                return webFullUrl;
            }
        }
        public void RemoveEventReceiversFromHostWeb(ClientContext clientContext)
        {
            List myList = clientContext.Web.Lists.GetByTitle(LIST_TITLE);
            clientContext.Load(myList, p => p.EventReceivers);
            clientContext.ExecuteQuery();

            var rer = myList.EventReceivers.Where(e => e.ReceiverName == RECEIVER_NAME_ADDED).FirstOrDefault();

            try
            {
                System.Diagnostics.Trace.WriteLine("Removing receiver at "
                        + rer.ReceiverUrl);

                var rerList = myList.EventReceivers.Where(e => e.ReceiverUrl == rer.ReceiverUrl).ToList<EventReceiverDefinition>();

                foreach (var rerFromUrl in rerList)
                {
                    //This will fail when deploying via F5, but works
                    //when deployed to production
                    rerFromUrl.DeleteObject();
                }
                clientContext.ExecuteQuery();
            }
            catch (Exception oops)
            {
                System.Diagnostics.Trace.WriteLine(oops.Message);
            }

            clientContext.ExecuteQuery();
        }
Beispiel #27
0
        /// <summary>
        /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class.
        /// </summary>
        /// <param name="policyFactory">An instance of IDeliveryPolicyFactory. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
        /// <param name="maConfig">Mobile Analytics Manager configuration. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/></param>
        /// <param name="clientContext">An instance of ClientContext. <see cref="Amazon.Runtime.Internal.ClientContext"/></param>
        /// <param name="credentials">An instance of Credentials. <see cref="Amazon.Runtime.AWSCredentials"/></param>
        /// <param name="regionEndPoint">Region endpoint. <see cref="Amazon.RegionEndpoint"/></param>
        public DeliveryClient(IDeliveryPolicyFactory policyFactory, MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint)
        {
            _policyFactory = policyFactory;
            _deliveryPolicies = new List<IDeliveryPolicy>();
            _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());

            _clientContext = clientContext;
            _appID = clientContext.AppID;
            _maConfig = maConfig;
            _eventStore = new SQLiteEventStore(maConfig);

#if PCL
            _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
#elif BCL
            if (null == credentials && null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient();
            }
            else if (null == credentials)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(regionEndPoint);
            }
            else if (null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials);
            }
            else
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
            }
#endif
        }
Beispiel #28
0
        internal static void CreateSearchNavigationNodes(ClientContext clientContext, Web web, Dictionary<string, string> searchNavigationNodes)
        {
            if (searchNavigationNodes == null || searchNavigationNodes.Count == 0) return;

            var searchNavigation = web.Navigation.GetNodeById(1040);
            NavigationNodeCollection nodeCollection = searchNavigation.Children;

            clientContext.Load(searchNavigation);
            clientContext.Load(nodeCollection);
            clientContext.ExecuteQuery();

            for (int i = nodeCollection.Count - 1; i >= 0; i--)
            {
                nodeCollection[i].DeleteObject();
            }

            foreach (KeyValuePair<string, string> newNode in searchNavigationNodes.Reverse<KeyValuePair<string, string>>())
            {
                nodeCollection.Add(new NavigationNodeCreationInformation
                {
                    Title = newNode.Key,
                    Url = newNode.Value
                });
            }

            clientContext.ExecuteQuery();
        }
Beispiel #29
0
 public void UploadFilesInFolder(ClientContext context, Web web, List<ShContentFolder> contentFolders)
 {
     foreach (ShContentFolder folder in contentFolders)
     {
         UploadFilesInFolder(context, web, folder);
     }
 }
Beispiel #30
0
        public Steps(ServiceContext serviceContext, ClientContext clientContext)
        {
            _serviceContext = serviceContext;
            _clientContext = clientContext;

            _messages = new ReplaySubject<Tuple<string, IMessage>>();
        }
Beispiel #31
0
        /// <summary>
        /// Analyze the web
        /// </summary>
        /// <param name="cc">ClientContext of the web to be analyzed</param>
        /// <returns>Duration of the analysis</returns>
        public override TimeSpan Analyze(ClientContext cc)
        {
            try
            {
                base.Analyze(cc);

                var baseUri   = new Uri(this.SiteUrl);
                var webAppUrl = baseUri.Scheme + "://" + baseUri.Host;

                var lists = cc.Web.GetListsToScan();

                foreach (var list in lists)
                {
                    try
                    {
                        this.ScanJob.IncreaseScannedLists();

                        ListScanResult listScanData;
                        if (list.DefaultViewUrl.ToLower().Contains(".aspx"))
                        {
                            File file = cc.Web.GetFileByServerRelativeUrl(list.DefaultViewUrl);
                            listScanData = file.ModernCompatability(list, ref this.ScanJob.ScanErrors);
                        }
                        else
                        {
                            listScanData = new ListScanResult()
                            {
                                BlockedByNotBeingAbleToLoadPage = true
                            };
                        }

                        if (listScanData != null && !listScanData.WorksInModern)
                        {
                            if (this.ScanJob.ExcludeListsOnlyBlockedByOobReasons && listScanData.OnlyBlockedByOOBReasons)
                            {
                                continue;
                            }

                            listScanData.SiteURL    = this.SiteUrl;
                            listScanData.ListUrl    = $"{webAppUrl}{list.DefaultViewUrl}";
                            listScanData.SiteColUrl = this.SiteCollectionUrl;
                            listScanData.ListTitle  = list.Title;

                            if (!this.ScanJob.ListScanResults.TryAdd($"{Guid.NewGuid().ToString()}{webAppUrl}{list.DefaultViewUrl}", listScanData))
                            {
                                ScanError error = new ScanError()
                                {
                                    Error      = $"Could not add list scan result for {webAppUrl}{list.DefaultViewUrl} from web scan of {this.SiteUrl}",
                                    SiteColUrl = this.SiteCollectionUrl,
                                    SiteURL    = this.SiteUrl,
                                    Field1     = "ListAnalyzer",
                                    Field2     = $"{webAppUrl}{list.DefaultViewUrl}"
                                };
                                this.ScanJob.ScanErrors.Push(error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ScanError error = new ScanError()
                        {
                            Error      = ex.Message,
                            SiteColUrl = this.SiteCollectionUrl,
                            SiteURL    = this.SiteUrl,
                            Field1     = "MainListAnalyzerLoop",
                            Field2     = ex.StackTrace,
                            Field3     = $"{webAppUrl}{list.DefaultViewUrl}"
                        };

                        // Send error to telemetry to make scanner better
                        if (this.ScanJob.ScannerTelemetry != null)
                        {
                            this.ScanJob.ScannerTelemetry.LogScanError(ex, error);
                        }

                        this.ScanJob.ScanErrors.Push(error);
                        Console.WriteLine("Error for page {1}: {0}", ex.Message, $"{webAppUrl}{list.DefaultViewUrl}");
                    }
                }
            }
            finally
            {
                this.StopTime = DateTime.Now;
            }

            // return the duration of this scan
            return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks)));
        }
Beispiel #32
0
 public PermissionManager(ClientContext context) : base(context)
 {
 }
 internal SpproBaseRepository(string listName, ClientContext clientContext)
 {
     this.ListName      = listName;
     this.ClientContext = clientContext;
 }
Beispiel #34
0
 public SkateStatsHandler(ClientContext clientContext, IBlazeNotificationHandler notificationHandler)
 {
     _clientContext       = clientContext;
     _notificationHandler = notificationHandler;
 }
 private void DeleteLists(ClientContext cc)
 {
     DeleteListsImplementation(cc);
 }
Beispiel #36
0
 public ClientHostDisconnectionOperation(ClientContext context, ILogger logger, int timeout_ms) : base(context)
 {
     this.logger     = logger;
     this.timeout_ms = timeout_ms;
 }
Beispiel #37
0
 public PermissionManager(SqlTransaction transaction, ClientContext context) : base(transaction, context)
 {
 }
 /// <summary>
 /// Triggers the steps needed once we're processing the first site collection
 /// </summary>
 /// <param name="ccWeb">ClientContext of the rootweb of the first site collection</param>
 public void SetFirstSiteCollectionDone(ClientContext ccWeb)
 {
     SetFirstSiteCollectionDone(ccWeb, "ScanningFramework");
 }
 public SharedClientContext(ClientContext context, CancellationToken cancellationToken)
     : base(context)
 {
     _context          = context;
     CancellationToken = cancellationToken;
 }
 public TheFacade(Client client)
 {
     _Context = new ClientContext(client);
 }
Beispiel #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TenantContainer"/> class.
 /// </summary>
 /// <param name="clientContext"></param>
 internal TenantContainer(ClientContext clientContext)
     : base(clientContext)
 {
 }
Beispiel #42
0
        protected override void ExecuteCmdlet()
        {
            var list = List.GetList(CurrentWeb, l => l.InformationRightsManagementSettings, l => l.IrmEnabled, l => l.IrmExpire, l => l.IrmReject);

            if (list == null)
            {
                throw new PSArgumentException($"No list found with id, title or url '{List}'", "List");
            }

            if (list.IrmEnabled == false && !Enable.HasValue)
            {
                WriteWarning("Information Rights Management is currently disabled for this list. Enable with Set-PnPListInformationRightsManagement -Enable $true");
            }
            else
            {
                var isDirty = false;

                if (Enable.HasValue)
                {
                    list.IrmEnabled = Enable.Value;
                    isDirty         = true;
                }
                if (EnableExpiration.HasValue)
                {
                    list.IrmExpire = EnableExpiration.Value;
                    isDirty        = true;
                }
                if (EnableRejection.HasValue)
                {
                    list.IrmReject = EnableRejection.Value;
                    isDirty        = true;
                }
                if (isDirty)
                {
                    list.Update();
                    ClientContext.Load(list, l => l.InformationRightsManagementSettings, l => l.IrmEnabled, l => l.IrmExpire, l => l.IrmReject);
                    ClientContext.ExecuteQueryRetry();
                }

                if (list.IrmEnabled)
                {
                    // Enablers
                    isDirty = false;
                    if (EnableDocumentAccessExpire.HasValue)
                    {
                        list.InformationRightsManagementSettings.EnableDocumentAccessExpire = EnableDocumentAccessExpire.Value;
                        isDirty = true;
                    }

                    if (EnableDocumentBrowserPublishingView.HasValue)
                    {
                        list.InformationRightsManagementSettings.EnableDocumentBrowserPublishingView = EnableDocumentBrowserPublishingView.Value;
                        isDirty = true;
                    }

                    if (EnableGroupProtection.HasValue)
                    {
                        list.InformationRightsManagementSettings.EnableGroupProtection = EnableGroupProtection.Value;
                        isDirty = true;
                    }

                    if (EnableLicenseCacheExpire.HasValue)
                    {
                        list.InformationRightsManagementSettings.EnableLicenseCacheExpire = EnableLicenseCacheExpire.Value;
                        isDirty = true;
                    }

                    if (DisableDocumentBrowserView.HasValue)
                    {
                        list.InformationRightsManagementSettings.DisableDocumentBrowserView = DisableDocumentBrowserView.Value;
                        isDirty = true;
                    }

                    if (isDirty)
                    {
                        list.Update();
                        ClientContext.ExecuteQueryRetry();
                    }

                    // Properties
                    isDirty = false;
                    if (AllowPrint.HasValue)
                    {
                        list.InformationRightsManagementSettings.AllowPrint = AllowPrint.Value;
                        isDirty = true;
                    }

                    if (AllowScript.HasValue)
                    {
                        list.InformationRightsManagementSettings.AllowScript = AllowScript.Value;
                        isDirty = true;
                    }

                    if (AllowWriteCopy.HasValue)
                    {
                        list.InformationRightsManagementSettings.AllowWriteCopy = AllowWriteCopy.Value;
                        isDirty = true;
                    }

                    if (DocumentAccessExpireDays.HasValue)
                    {
                        if (list.InformationRightsManagementSettings.EnableDocumentAccessExpire)
                        {
                            list.InformationRightsManagementSettings.DocumentAccessExpireDays = DocumentAccessExpireDays.Value;
                            isDirty = true;
                        }
                        else
                        {
                            WriteWarning("Document Access expiration is not enabled. Enable with -EnableDocumentAccessExpire $true");
                        }
                    }

                    if (LicenseCacheExpireDays.HasValue)
                    {
                        if (list.InformationRightsManagementSettings.EnableLicenseCacheExpire)
                        {
                            list.InformationRightsManagementSettings.LicenseCacheExpireDays = LicenseCacheExpireDays.Value;
                            isDirty = true;
                        }
                        else
                        {
                            WriteWarning("License Cache expiration is not enabled. Enable with -EnableLicenseCacheExpire $true");
                        }
                    }

                    if (DocumentLibraryProtectionExpireDate.HasValue)
                    {
                        if (list.IrmExpire)
                        {
                            list.InformationRightsManagementSettings.DocumentLibraryProtectionExpireDate = DocumentLibraryProtectionExpireDate.Value;
                            isDirty = true;
                        }
                        else
                        {
                            WriteWarning("Information Rights Management (IRM) expiration is not enabled. Enable with -EnableExpiration");
                        }
                    }

                    if (GroupName != null)
                    {
                        list.InformationRightsManagementSettings.GroupName = GroupName;
                        isDirty = true;
                    }

                    if (PolicyDescription != null)
                    {
                        list.InformationRightsManagementSettings.PolicyDescription = PolicyDescription;
                        isDirty = true;
                    }

                    if (PolicyTitle != null)
                    {
                        list.InformationRightsManagementSettings.PolicyTitle = PolicyTitle;
                        isDirty = true;
                    }

                    if (TemplateId != null)
                    {
                        list.InformationRightsManagementSettings.TemplateId = TemplateId;
                        isDirty = true;
                    }

                    if (isDirty)
                    {
                        //list.InformationRightsManagementSettings.Update();
                        list.Update();
                        ClientContext.Load(list.InformationRightsManagementSettings);
                        ClientContext.ExecuteQueryRetry();
                    }

                    var irm = new
                    {
                        InformationRightsManagementEnabled = list.IrmEnabled,
                        InformationRightsManagementExpire  = list.IrmExpire,
                        InformationRightsManagementReject  = list.IrmReject,
                        list.InformationRightsManagementSettings.AllowPrint,
                        list.InformationRightsManagementSettings.AllowScript,
                        list.InformationRightsManagementSettings.AllowWriteCopy,
                        list.InformationRightsManagementSettings.DisableDocumentBrowserView,
                        list.InformationRightsManagementSettings.DocumentAccessExpireDays,
                        list.InformationRightsManagementSettings.DocumentLibraryProtectionExpireDate,
                        list.InformationRightsManagementSettings.EnableDocumentAccessExpire,
                        list.InformationRightsManagementSettings.EnableDocumentBrowserPublishingView,
                        list.InformationRightsManagementSettings.EnableGroupProtection,
                        list.InformationRightsManagementSettings.EnableLicenseCacheExpire,
                        list.InformationRightsManagementSettings.GroupName,
                        list.InformationRightsManagementSettings.LicenseCacheExpireDays,
                        list.InformationRightsManagementSettings.PolicyDescription,
                        list.InformationRightsManagementSettings.PolicyTitle,
                        list.InformationRightsManagementSettings.TemplateId
                    };
                    WriteObject(irm);
                }
            }
        }
        /// <summary>
        /// Creates a new Communication Site Collection
        /// </summary>
        /// <param name="clientContext">ClientContext object of a regular site</param>
        /// <param name="siteCollectionCreationInformation">information about the site to create</param>
        /// <returns>ClientContext object for the created site collection</returns>
        public static async Task <ClientContext> CreateAsync(ClientContext clientContext, CommunicationSiteCollectionCreationInformation siteCollectionCreationInformation)
        {
            await new SynchronizationContextRemover();

            ClientContext responseContext = null;

            var accessToken = clientContext.GetAccessToken();

            using (var handler = new HttpClientHandler())
            {
                clientContext.Web.EnsureProperty(w => w.Url);
                // we're not in app-only or user + app context, so let's fall back to cookie based auth
                if (String.IsNullOrEmpty(accessToken))
                {
                    handler.SetAuthenticationCookies(clientContext);
                }

                using (var httpClient = new PnPHttpProvider(handler))
                {
                    string requestUrl = $"{clientContext.Web.Url}/_api/SPSiteManager/Create";
                    //    string requestUrl = String.Format("{0}/_api/sitepages/communicationsite/create", clientContext.Web.Url);

                    var siteDesignId = GetSiteDesignId(siteCollectionCreationInformation);

                    Dictionary <string, object> payload = new Dictionary <string, object>();
                    //payload.Add("__metadata", new { type = "Microsoft.SharePoint.Portal.SPSiteCreationRequest" });
                    payload.Add("Title", siteCollectionCreationInformation.Title);
                    payload.Add("Lcid", siteCollectionCreationInformation.Lcid);
                    payload.Add("ShareByEmailEnabled", siteCollectionCreationInformation.ShareByEmailEnabled);
                    payload.Add("Url", siteCollectionCreationInformation.Url);
                    // Deprecated
                    // payload.Add("AllowFileSharingForGuestUsers", siteCollectionCreationInformation.AllowFileSharingForGuestUsers);
                    if (siteDesignId != Guid.Empty)
                    {
                        payload.Add("SiteDesignId", siteDesignId);
                    }
                    payload.Add("Classification", siteCollectionCreationInformation.Classification ?? "");
                    payload.Add("Description", siteCollectionCreationInformation.Description ?? "");
                    payload.Add("WebTemplate", "SITEPAGEPUBLISHING#0");
                    payload.Add("WebTemplateExtensionId", Guid.Empty);
                    payload.Add("HubSiteId", siteCollectionCreationInformation.HubSiteId);
                    payload.Add("Owner", siteCollectionCreationInformation.Owner);

                    var body = new { request = payload };

                    // Serialize request object to JSON
                    var jsonBody    = JsonConvert.SerializeObject(body);
                    var requestBody = new StringContent(jsonBody);

                    // Build Http request
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    request.Content = requestBody;
                    request.Headers.Add("accept", "application/json;odata.metadata=none");
                    request.Headers.Add("odata-version", "4.0");
                    MediaTypeHeaderValue sharePointJsonMediaType = null;
                    MediaTypeHeaderValue.TryParse("application/json;odata.metadata=none;charset=utf-8", out sharePointJsonMediaType);
                    requestBody.Headers.ContentType = sharePointJsonMediaType;

                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    }

                    requestBody.Headers.Add("X-RequestDigest", await clientContext.GetRequestDigest());

                    // Perform actual post operation
                    HttpResponseMessage response = await httpClient.SendAsync(request, new System.Threading.CancellationToken());

                    if (response.IsSuccessStatusCode)
                    {
                        // If value empty, URL is taken
                        var responseString = await response.Content.ReadAsStringAsync();

                        if (responseString != null)
                        {
                            try
                            {
                                var responseJson = JObject.Parse(responseString);
#if !NETSTANDARD2_0
                                if (Convert.ToInt32(responseJson["SiteStatus"]) == 2)
#else
                                if (responseJson["SiteStatus"].Value <int>() == 2)
#endif
                                {
                                    responseContext = clientContext.Clone(responseJson["SiteUrl"].ToString());
                                }
                                else
                                {
                                    throw new Exception(responseString);
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        // Something went wrong...
                        throw new Exception(await response.Content.ReadAsStringAsync());
                    }
                }
                return(await Task.Run(() => responseContext));
            }
        }
Beispiel #44
0
        private Pollux.Entities.DocumentoItem MontarDocumentoPasta(DateTime datacriacao, string nomedapasta, string urlrelativa, string urlSite, ClientContext spClientContext)
        {
            Pollux.Entities.DocumentoItem        docItem   = new Pollux.Entities.DocumentoItem();
            List <Pollux.Entities.DocumentoItem> listaDocs = new List <Pollux.Entities.DocumentoItem>();

            // preenche com as informações da pasta
            docItem.DataCriacao   = datacriacao;
            docItem.Nome          = nomedapasta;
            docItem.Tamanho       = string.Empty;
            docItem.TipoDocumento = 993520001;
            docItem.URL           = ObterUrlArquivo(urlSite, urlrelativa);

            #region  Obtem os documentos da subpasta
            var    rootWeb        = spClientContext.Web;
            Folder pastaPrincipal = rootWeb.GetFolderByServerRelativeUrl(urlrelativa);

            spClientContext.Load(pastaPrincipal, fs => fs.Files, p => p.Folders);
            spClientContext.ExecuteQuery();

            FileCollection fileCollection = pastaPrincipal.Files;

            //lista os documentos da pasta
            foreach (var arquivo in fileCollection)
            {
                listaDocs.Add(MontarDocumento(arquivo, urlSite));
            }
            #endregion

            #region Obtem as subpasta que estão em camasas existem na subpasta pai
            var rootweb = spClientContext.Web;
            FolderCollection folderCollection = rootweb.GetFolderByServerRelativeUrl(urlrelativa).Folders;

            spClientContext.Load(folderCollection, fs => fs.Include(f => f.ListItemAllFields));
            spClientContext.ExecuteQuery();
            //lista os arquivos da subpasta
            foreach (Folder subFolder in folderCollection)
            {
                // This property is now populated
                var item = subFolder.ListItemAllFields;

                // This is where the dates you want are stored
                var created             = (DateTime)item["Created"];
                var nomedasubpasta      = (string)item["Title"];
                var urlrelativaSubpasta = (string)item["FileRef"];

                //Cria recursividade de documentos e subpastas
                listaDocs.Add(MontarDocumentoPasta(created, nomedasubpasta, urlrelativaSubpasta, urlSite, spClientContext));
            }
            #endregion

            docItem.DocumentoItens = listaDocs;

            return(docItem);
        }
        /// <summary>
        /// Groupifies a classic team site by creating a group for it and connecting the site with the newly created group
        /// </summary>
        /// <param name="clientContext">ClientContext object of a regular site</param>
        /// <param name="siteCollectionGroupifyInformation">information about the site to create</param>
        /// <returns>ClientContext object for the created site collection</returns>
        public static async Task <ClientContext> GroupifyAsync(ClientContext clientContext, TeamSiteCollectionGroupifyInformation siteCollectionGroupifyInformation)
        {
            if (siteCollectionGroupifyInformation == null)
            {
                throw new ArgumentException("Missing value for siteCollectionGroupifyInformation", "sitecollectionGroupifyInformation");
            }

            if (!string.IsNullOrEmpty(siteCollectionGroupifyInformation.Alias) && siteCollectionGroupifyInformation.Alias.Contains(" "))
            {
                throw new ArgumentException("Alias cannot contain spaces", "Alias");
            }

            if (string.IsNullOrEmpty(siteCollectionGroupifyInformation.DisplayName))
            {
                throw new ArgumentException("DisplayName is required", "DisplayName");
            }

            await new SynchronizationContextRemover();

            ClientContext responseContext = null;

            var accessToken = clientContext.GetAccessToken();

            if (clientContext.IsAppOnly())
            {
                throw new Exception("App-Only is currently not supported.");
            }
            using (var handler = new HttpClientHandler())
            {
                clientContext.Web.EnsureProperty(w => w.Url);
                // we're not in app-only or user + app context, so let's fall back to cookie based auth
                if (String.IsNullOrEmpty(accessToken))
                {
                    handler.SetAuthenticationCookies(clientContext);
                }

                using (var httpClient = new PnPHttpProvider(handler))
                {
                    string requestUrl = String.Format("{0}/_api/GroupSiteManager/CreateGroupForSite", clientContext.Web.Url);

                    Dictionary <string, object> payload = new Dictionary <string, object>();
                    payload.Add("displayName", siteCollectionGroupifyInformation.DisplayName);
                    payload.Add("alias", siteCollectionGroupifyInformation.Alias);
                    payload.Add("isPublic", siteCollectionGroupifyInformation.IsPublic);

                    var optionalParams = new Dictionary <string, object>();
                    optionalParams.Add("Description", siteCollectionGroupifyInformation.Description ?? "");
                    optionalParams.Add("Classification", siteCollectionGroupifyInformation.Classification ?? "");
                    // Handle groupify options
                    var creationOptionsValues = new List <string>();
                    if (siteCollectionGroupifyInformation.KeepOldHomePage)
                    {
                        creationOptionsValues.Add("SharePointKeepOldHomepage");
                    }
                    creationOptionsValues.Add($"HubSiteId:{siteCollectionGroupifyInformation.HubSiteId}");
                    optionalParams.Add("CreationOptions", creationOptionsValues);
                    if (siteCollectionGroupifyInformation.Owners != null && siteCollectionGroupifyInformation.Owners.Length > 0)
                    {
                        optionalParams.Add("Owners", siteCollectionGroupifyInformation.Owners);
                    }

                    payload.Add("optionalParams", optionalParams);

                    var body = payload;

                    // Serialize request object to JSON
                    var jsonBody    = JsonConvert.SerializeObject(body);
                    var requestBody = new StringContent(jsonBody);

                    // Build Http request
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    request.Content = requestBody;
                    request.Headers.Add("accept", "application/json;odata.metadata=none");
                    request.Headers.Add("odata-version", "4.0");
                    MediaTypeHeaderValue sharePointJsonMediaType = null;
                    MediaTypeHeaderValue.TryParse("application/json;odata.metadata=none;charset=utf-8", out sharePointJsonMediaType);
                    requestBody.Headers.ContentType = sharePointJsonMediaType;

                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    }

                    requestBody.Headers.Add("X-RequestDigest", await clientContext.GetRequestDigest());

                    // Perform actual post operation
                    HttpResponseMessage response = await httpClient.SendAsync(request, new System.Threading.CancellationToken());

                    if (response.IsSuccessStatusCode)
                    {
                        // If value empty, URL is taken
                        var responseString = await response.Content.ReadAsStringAsync();

                        var responseJson = JObject.Parse(responseString);

                        // SiteStatus 1 = Provisioning, SiteStatus 2 = Ready
#if !NETSTANDARD2_0
                        if (Convert.ToInt32(responseJson["SiteStatus"]) == 2 || Convert.ToInt32(responseJson["SiteStatus"]) == 1)
#else
                        if (responseJson["SiteStatus"].Value <int>() == 2 || responseJson["SiteStatus"].Value <int>() == 1)
#endif
                        {
                            responseContext = clientContext;
                        }
                        else
                        {
                            throw new Exception(responseString);
                        }
                    }
                    else
                    {
                        // Something went wrong...
                        throw new Exception(await response.Content.ReadAsStringAsync());
                    }
                }
                return(await Task.Run(() => responseContext));
            }
        }
        /// <summary>
        /// Creates a new Team Site Collection and waits for it to be created
        /// </summary>
        /// <param name="clientContext">ClientContext object of a regular site</param>
        /// <param name="siteCollectionCreationInformation">information about the site to create</param>
        /// <returns>ClientContext object for the created site collection</returns>
        public static ClientContext Create(ClientContext clientContext, TeamSiteCollectionCreationInformation siteCollectionCreationInformation)
        {
            var context = CreateAsync(clientContext, siteCollectionCreationInformation).GetAwaiter().GetResult();

            return(context);
        }
Beispiel #47
0
        protected override void ExecuteCmdlet()
        {
            var list = Identity.GetList(SelectedWeb);

            if (list != null)
            {
                list.EnsureProperties(l => l.EnableAttachments, l => l.EnableVersioning, l => l.EnableMinorVersions, l => l.Hidden, l => l.EnableModeration, l => l.BaseType, l => l.HasUniqueRoleAssignments, l => l.ContentTypesEnabled);

                var enableVersioning    = list.EnableVersioning;
                var enableMinorVersions = list.EnableMinorVersions;
                var hidden            = list.Hidden;
                var enableAttachments = list.EnableAttachments;

                var updateRequired = false;
                if (BreakRoleInheritance)
                {
                    list.BreakRoleInheritance(CopyRoleAssignments, ClearSubscopes);
                    updateRequired = true;
                }

                if ((list.HasUniqueRoleAssignments) && (ResetRoleInheritance))
                {
                    list.ResetRoleInheritance();
                    updateRequired = true;
                }

                if (!string.IsNullOrEmpty(Title))
                {
                    list.Title     = Title;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(Hidden)) && Hidden != list.Hidden)
                {
                    list.Hidden    = Hidden;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(EnableContentTypes)) && list.ContentTypesEnabled != EnableContentTypes)
                {
                    list.ContentTypesEnabled = EnableContentTypes;
                    updateRequired           = true;
                }

                if (ParameterSpecified(nameof(EnableVersioning)) && EnableVersioning != enableVersioning)
                {
                    list.EnableVersioning = EnableVersioning;
                    updateRequired        = true;
                }

                if (ParameterSpecified(nameof(EnableMinorVersions)) && EnableMinorVersions != enableMinorVersions)
                {
                    list.EnableMinorVersions = EnableMinorVersions;
                    updateRequired           = true;
                }

                if (ParameterSpecified(nameof(EnableModeration)) && list.EnableModeration != EnableModeration)
                {
                    list.EnableModeration = EnableModeration;
                    updateRequired        = true;
                }

                if (ParameterSpecified(nameof(EnableAttachments)) && EnableAttachments != enableAttachments)
                {
                    list.EnableAttachments = EnableAttachments;
                    updateRequired         = true;
                }

                if (ParameterSpecified(nameof(Description)))
                {
                    list.Description = Description;
                    updateRequired   = true;
                }

                if (ParameterSpecified(nameof(EnableFolderCreation)))
                {
                    list.EnableFolderCreation = EnableFolderCreation;
                    updateRequired            = true;
                }

                if (ParameterSpecified(nameof(ForceCheckout)))
                {
                    list.ForceCheckout = ForceCheckout;
                    updateRequired     = true;
                }

#if !ONPREMISES
                if (ParameterSpecified(nameof(ListExperience)))
                {
                    list.ListExperienceOptions = ListExperience;
                    updateRequired             = true;
                }
#endif

                if (updateRequired)
                {
                    list.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                updateRequired = false;

                if (list.EnableVersioning)
                {
                    // list or doclib?

                    if (list.BaseType == BaseType.DocumentLibrary)
                    {
                        if (ParameterSpecified(nameof(MajorVersions)))
                        {
                            list.MajorVersionLimit = (int)MajorVersions;
                            updateRequired         = true;
                        }

                        if (ParameterSpecified(nameof(MinorVersions)) && list.EnableMinorVersions)
                        {
                            list.MajorWithMinorVersionsLimit = (int)MinorVersions;
                            updateRequired = true;
                        }
                    }
                    else
                    {
                        if (ParameterSpecified(nameof(MajorVersions)))
                        {
                            list.MajorVersionLimit = (int)MajorVersions;
                            updateRequired         = true;
                        }
                    }
                }
                if (updateRequired)
                {
                    list.Update();
                    ClientContext.ExecuteQueryRetry();
                }
            }
        }
Beispiel #48
0
 public CatalogueBuilder(ClientContext context)
 {
     _context = context;
 }
        public override List <ServiceObject> DescribeServiceObjects()
        {
            List <ServiceObject> SOs = new List <ServiceObject>();

            using (ClientContext context = InitializeContext(base.SiteURL))
            {
                Web            spWeb = context.Web;
                ListCollection lists = spWeb.Lists;
                context.Load(lists);
                context.ExecuteQuery();
                //Making this dummy call to load the Micorsoft.Sharepoint.Client.Taxanomy assembly (https://blogs.msdn.microsoft.com/boodablog/2014/07/04/taxonomy-fields-return-as-dictionaries-using-the-client-objcet-model-in-sharepoint-2013/)
                TaxonomyItem dummy = new TaxonomyItem(context, null);
                foreach (List list in lists)
                {
                    if (list.Hidden == false || (list.Hidden && base.IncludeHiddenLists))
                    {
                        if (list.BaseType == BaseType.DocumentLibrary)
                        {
                            context.Load(list.ContentTypes);
                            context.ExecuteQuery();
                        }

                        ServiceObject so = Helper.CreateServiceObject(list.Title, list.Title, list.Description);

                        so.MetaData.DisplayName = list.Title;
                        so.MetaData.Description = list.Description;
                        if (list.BaseType == BaseType.DocumentLibrary)
                        {
                            so.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "Document Libraries");
                        }
                        else
                        {
                            so.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "List Items");
                        }

                        so.MetaData.AddServiceElement(Constants.InternalProperties.ListTitle, list.Title);
                        so.MetaData.AddServiceElement(Constants.InternalProperties.IsFolderEnabled, list.EnableFolderCreation);
                        so.MetaData.AddServiceElement(Constants.InternalProperties.ListBaseType, list.BaseType);
                        if (list.BaseType == BaseType.DocumentLibrary && GetDocumentSetContentType(list.ContentTypes) != null)
                        {
                            so.MetaData.AddServiceElement(Constants.InternalProperties.IsListDocumentSet, true);
                        }
                        else
                        {
                            so.MetaData.AddServiceElement(Constants.InternalProperties.IsListDocumentSet, false);
                        }


                        FieldCollection fields = list.Fields;
                        context.Load(fields);
                        context.ExecuteQuery();
                        foreach (Field f in fields)
                        {
                            if (f.Hidden == false || (f.Hidden == true && base.IncludeHiddenFields))
                            {
                                // We'll use InternalName as the system name and Title as the display name.
                                // See http://blogs.perficient.com/microsoft/2009/04/static-name-vs-internal-name-vs-display-name-in-sharepoint/ for some background

                                // Some fields have no title, so then we just take the internalname.
                                string fieldTitle = f.Title;
                                if (string.IsNullOrEmpty(fieldTitle))
                                {
                                    fieldTitle = f.InternalName;
                                }

                                // Because the field title can be duplicate, we see if it already exists.
                                // If it does, we change the displayname of both existing and newly found property to something unique.
                                // This behaviour can also be forced by the Show Internal Names option.

                                Property existingProp = GetExistingProperty(so, fieldTitle);
                                string   displayName  = fieldTitle;
                                if (ShowInternalNames)
                                {
                                    displayName = string.Format("{0} ({1})", fieldTitle, f.InternalName);
                                }

                                if (existingProp != null)
                                {
                                    existingProp.MetaData.DisplayName = string.Format("{0} ({1})",
                                                                                      existingProp.MetaData.GetServiceElement <string>(Constants.InternalProperties.Title),
                                                                                      existingProp.MetaData.GetServiceElement <string>(Constants.InternalProperties.InternalName));
                                    displayName = string.Format("{0} ({1})", fieldTitle, f.InternalName);
                                }

                                AddFieldProperty(so, f);
                                FieldType _fieldtype; //We will find the Fieldtype from the MapHelper class (To get the correctoutput for field type Calculated)

                                SoType   soType = MapHelper.SPTypeField(f, out _fieldtype);
                                Property prop   = Helper.CreateSpecificProperty(f.InternalName, displayName, f.Description, soType);

                                prop.MetaData.AddServiceElement(Constants.InternalProperties.Hidden, f.Hidden);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.Title, fieldTitle);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.InternalName, f.InternalName);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.Id, f.Id);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.ReadOnly, AssignReadonly(f));
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.Required, f.Required);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.FieldTypeKind, _fieldtype);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.SPFieldType, f.TypeAsString);
                                prop.MetaData.AddServiceElement(Constants.InternalProperties.Internal, false);
                                so.Properties.Add(prop);
                            }
                        }

                        AddInputServiceObjectPropertie(so);

                        AddServiceObjectMethods(so);

                        SOs.Add(so);
                    }
                }

                ServiceObject ctSo = Helper.CreateServiceObject("ContentTypes", "Content Types", "Manage the collection of content types, which enables consistent handling of content across sites.");

                ctSo.MetaData.DisplayName = "Content Types";
                ctSo.MetaData.Description = "Manage the collection of content types, which enables consistent handling of content across sites.";
                ctSo.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "Management");

                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeName, "Name", "Name", SoType.Text));
                //so.Properties.Add(Helper.CreateSpecificProperty("SiteURL", "Site URL", "Site URL", SoType.Text));
                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeGroup, "Group", "Group", SoType.Text));
                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeReadOnly, "ReadOnly", "ReadOnly", SoType.YesNo));
                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeHidden, "Hidden", "Hidden", SoType.Text));
                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeCount, "Count", "Count", SoType.Number));
                ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeID, "Content Type ID", "Content Type ID", SoType.Text));

                AddContentTypeServiceObjectMethods(ctSo);

                SOs.Add(ctSo);

                return(SOs);
            }
        }
Beispiel #50
0
        /// <summary>
        /// Configures the variation settings
        /// 1. Go to "Site Actions" -> "Site settings"
        /// 2. Under "Site collection administration", click "Variation Settings".
        /// This method is for the page above to change or update the "Variation Settings"
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="variationSettings">Variation settings</param>
        public static void ConfigureVariationsSettings(this ClientContext context, VariationInformation variationSettings)
        {
            if (variationSettings == null)
            {
                throw new ArgumentException("variationSettings");
            }

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

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

            // Try to get _VarRelationshipsListId property from web property bag
            string variationListId = web.GetPropertyBagValueString(VARIATIONRELATIONSHIPSLISTID, string.Empty);

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

                // Get the "Variation RelationShips" List by id
                Guid varRelationshipsListId    = new Guid(variationListId);
                var  variationRelationshipList = lists.GetById(varRelationshipsListId);

                if (variationRelationshipList != null)
                {
                    // Get the root folder
                    Folder rootFolder = variationRelationshipList.RootFolder;
                    context.Load(rootFolder);
                    context.Load(variationRelationshipList);
                    context.ExecuteQueryRetry();

                    // Automatic creation
                    rootFolder.Properties["EnableAutoSpawnPropertyName"] = variationSettings.AutomaticCreation.ToString();

                    // Recreate Deleted Target Page; set to false to enable recreation
                    rootFolder.Properties["AutoSpawnStopAfterDeletePropertyName"] = variationSettings.RecreateDeletedTargetPage.ToString();

                    // Update Target Page Web Parts
                    rootFolder.Properties["UpdateWebPartsPropertyName"] = variationSettings.UpdateTargetPageWebParts.ToString();

                    // Resources
                    rootFolder.Properties["CopyResourcesPropertyName"] = variationSettings.CopyResources.ToString();

                    // Notification
                    rootFolder.Properties["SendNotificationEmailPropertyName"] = variationSettings.SendNotificationEmail.ToString();

                    // Configuration setting site template to be used for the top sites of each label
                    rootFolder.Properties["SourceVarRootWebTemplatePropertyName"] = variationSettings.RootWebTemplate;

                    rootFolder.Update();
                    context.ExecuteQueryRetry();

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

                    if (collListItems.Count > 0)
                    {
                        // Update the first item
                        ListItem item = collListItems[0];
                        item["Deleted"]      = false;
                        item["ObjectID"]     = web.ServerRelativeUrl;
                        item["ParentAreaID"] = String.Empty;

                        item.Update();
                        context.ExecuteQueryRetry();
                    }
                    else
                    {
                        // Create the new item
                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem olistItem = variationRelationshipList.AddItem(itemCreateInfo);

                        // Root web relationship which should always have this guid
                        olistItem["GroupGuid"]    = new Guid("F68A02C8-2DCC-4894-B67D-BBAED5A066F9");
                        olistItem["Deleted"]      = false;
                        olistItem["ObjectID"]     = web.ServerRelativeUrl;
                        olistItem["ParentAreaID"] = String.Empty;

                        olistItem.Update();
                        context.ExecuteQueryRetry();
                    }
                }
            }
        }
Beispiel #51
0
        /// <summary>
        /// Update Pipeline list
        /// </summary>
        /// <param name="clientContextWeb">client context url</param>
        /// <param name="backupListTarget">list that is exported and deleted</param>
        /// <param name="excelIndexTarget">list that needs to be backedup</param>
        /// <param name="sharepointIndexTarget">doc library for backup of excel file</param>
        public UpdatePipelineList(string clientContextWeb, string backupListTarget, string excelIndexTarget, string sharepointIndexTarget)
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\");

            string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\";
            string filter = "*.xlsx";

            string[] files = Directory.GetFiles(folder, filter);

            string pipelinefile = "Pipeline.xlsx";
            string dhcfile      = "DHCUpdate.xlsx";

            Regex regexPipeline = FindFilesPatternToRegex.Convert("*pipeline*.xlsx");
            Regex regexDHC      = FindFilesPatternToRegex.Convert("*dhc*.xlsx");

            foreach (string file in files)
            {
                //Console.WriteLine("Inside File check: {0}", file);
                if (regexPipeline.IsMatch(file.ToLower()))
                {
                    pipelinefile = file;
                }
                else if (regexDHC.IsMatch(file.ToLower()))
                {
                    dhcfile = file;
                }
            }

            Console.WriteLine("------Update Pipeline ----------------");
            //Console.WriteLine("Folder      : {0}", folder);
            Console.WriteLine("Pipelinefile: {0}", pipelinefile);
            Console.WriteLine("DHCfile     : {0}", dhcfile);
            Console.WriteLine("--------------------------------------");
            log.Debug(string.Format("------   Update Pipeline Files   ------"));
            log.Debug(string.Format("Pipelinefile: {0}", pipelinefile));
            log.Debug(string.Format("DHCfile     : {0}", dhcfile));
            log.Debug(string.Format("---------------------------------------"));

            FileStream stream, streamDHC;

            try
            {
                //update for reading files
                stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read);

                //update for reading files
                streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Please close the excel file and press enter");
                Console.ReadLine();
                //update for reading files
                stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read);

                //update for reading files
                streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read);
            }



            IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            reader.IsFirstRowAsColumnNames = true;

            DataSet ds = reader.AsDataSet();

            IExcelDataReader readerDHC = ExcelReaderFactory.CreateOpenXmlReader(streamDHC);

            readerDHC.IsFirstRowAsColumnNames = true;

            DataSet dsDHC = readerDHC.AsDataSet();

            DataRowSharepointMappingCollection mapping    = MyRetriever.GetTheCollection();
            DataRowSharepointMappingCollection mappingDHC = MyRetriever.GetTheCollection("DataRowDHCMappingsSection");



            DataTable  dt       = ds.Tables[0];
            DataColumn dcParent = dt.Columns["Opportunity Name"];

            //using (var clientContext = new ClientContext(clientContextWeb))
            using (ClientContext clientContext = ClaimClientContext.GetAuthenticatedContext(clientContextWeb))
            {
                Web web = clientContext.Web;

                //------------------------------------
                // GetItems for PipeLine list
                //------------------------------------
                // DEV NOTES:
                //     Aug. 4, 2017 - Removed 2000  limitation from CamlQueries   (MAT)
                //
                List               oldList  = web.Lists.GetByTitle(backupListTarget);
                CamlQuery          query    = CamlQuery.CreateAllItemsQuery();
                ListItemCollection oldItems = oldList.GetItems(query);

                clientContext.Load(oldItems);

                var listFields = oldList.Fields;
                clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName, field => field.ReadOnlyField, field => field.StaticName));

                clientContext.ExecuteQuery();

                //--------------------------------------------------
                // GetItems from LOB (LineOfBusiness list here.....
                //--------------------------------------------------
                // DEV NOTES:
                //     Aug. 4, 2017 - Removed 1000 limitation from CamlQueries   (MAT)
                //
                List               LOBList  = web.Lists.GetByTitle("LOB-MPP-Map");
                CamlQuery          LOBquery = CamlQuery.CreateAllItemsQuery();
                ListItemCollection LOBitems = LOBList.GetItems(LOBquery);

                clientContext.Load(LOBitems);

                var LOBFields = LOBList.Fields;
                clientContext.Load(LOBFields, fields => fields.Include(field => field.Title, field => field.InternalName));

                clientContext.ExecuteQuery();

                //UpdateLOBFields( clientContext, oldList, oldItems, LOBitems);
                // Console.WriteLine("Finished return from LOB update");
                //oldList.Update();
                //Console.WriteLine("Finished return from oldList update");
                //clientContext.ExecuteQuery();
                //-------------------------
                //Stop here for now.
                //-------------------------
                // Console.ReadLine();
                // System.Environment.Exit(0);

                //log.Debug(string.Format("Opening List: {0}", backupListTarget));
                //log.Debug("Internal fields");
                //log.Debug("-------------------------");
                //foreach (Field f in listFields)
                //{
                //    log.Debug(string.Format("Title: {0},   Internal Name: {1}", f.Title, f.InternalName));
                //    log.Debug(string.Format("Static Name: {0}", f.StaticName));
                //    log.Debug("-----------------");
                //    //log.Debug(f.InternalName);
                //}

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //log.Debug("-------  Inside For  -----------------");
                    //log.Debug(dr[excelIndexTarget].ToString());

                    var my_itemlist = oldItems.ToList();

                    // ---------------BEGIN MY COMMENT SECTION --------------------------
                    //Console.WriteLine("Sales Opportunity Id: {0}", dr["Sales Opportunity Id"].ToString());
                    //Console.WriteLine(" My_itemlist count: {0}", my_itemlist.Count);

                    ////---------MAT ----DEBUG TEST--------------------
                    ////--  List out item list for verification ---
                    //// ---------------------------------------------
                    //if (my_itemlist.Count() == 0)
                    //{
                    //    Console.WriteLine("My List count in 0");
                    //}
                    //else
                    //{
                    //    log.Debug("-- Item List ------");
                    //    foreach (ListItem targetListItem in my_itemlist)
                    //    {
                    //        log.Debug(string.Format("Title: {0}, HPOppID: {1}", targetListItem["Title"], targetListItem["HPOppID"].ToString()));
                    //        Console.WriteLine(targetListItem["Title"]);
                    //    }
                    //}
                    //log.Debug(string.Format(".....MAT - Listing COMPLETED HERE"));

                    //Console.WriteLine("  --------  MAT list completed here  ---------------");
                    // ---------------END MY COMMENT SECTION --------------------------

                    var page = from ListItem itemlist in oldItems.ToList()
                               // var page = from ListItem itemlist in my_itemlist
                               //where itemlist["HPOppID"].ToString() == dr["Sales Opportunity Id"].ToString()
                               where itemlist["HPOppID"].ToString() == dr[excelIndexTarget.ToString()].ToString()
                               select itemlist;

                    //Console.WriteLine("Page Count is: {0}", page.Count());
                    //this is an update
                    if (page.Count() == 1)
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        //Console.WriteLine(string.Format("UPDATE RECORD:  Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString()));
                        //log.Debug(string.Format("UPDATE: Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString()));
                        Console.WriteLine(string.Format("UPDATE RECORD:  Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString()));
                        log.Debug(string.Format("UPDATE: Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString()));


                        ListItem item = page.FirstOrDefault();

                        //iterate the mapping between sharepoint list items and excel spreadsheet items
                        foreach (DataRowSharepointMapping map in mapping)
                        {
                            UpdateField(item, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget);
                        }
                        CompareSalesStage(item, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget);

                        //Console.WriteLine("- Before Item update.");
                        // just update the item
                        item.Update();

                        //Console.WriteLine("- Before List update.");
                        //update the list
                        oldList.Update();


                        countupdate++;
                    }
                    // This is a new record
                    //else if (page.Count() == 0 && !string.IsNullOrEmpty(dr["Sales Opportunity Id"].ToString()))   ----MAT
                    else if (page.Count() == 0 && !string.IsNullOrEmpty(dr[excelIndexTarget.ToString()].ToString()))
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        //Console.WriteLine(string.Format("-------  Inside ELSE NEW RECORD-----------------"));
                        //Console.WriteLine(string.Format("NEW RECORD: Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString()));
                        Console.WriteLine(string.Format("NEW RECORD: Name:{0}  ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString()));
                        //log.Debug("-------  Inside ELSE NEW RECORD-----------------");

                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem oListItem = oldList.AddItem(itemCreateInfo);
                        // -- iterate the mapping between sharepoint list items and excel spreadsheet items
                        foreach (DataRowSharepointMapping map in mapping)
                        {
                            UpdateField(oListItem, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget);
                        }
                        CompareSalesStage(oListItem, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget);

                        // -- just update the item
                        //Console.WriteLine("- Before Item update.");
                        oListItem.Update();
                        // -- update the list
                        //Console.WriteLine("- Before List update.");
                        oldList.Update();

                        countnew++;
                    }

                    else
                    {
                        //-----------------------------------------------------
                        // DUPLICATE RECORDS CHECK  (MAT) - 8/31/17
                        //-----------------------------------------------------
                        //log.Debug(string.Format("DUPLICATE RECORD TEST inside PAGE: {0}", page.ToList().Count()));
                        if (page.ToList().Count() > 1)
                        {
                            Console.ForegroundColor = ConsoleColor.DarkGray;
                            log.Debug(string.Format("DUPLICATE RECORD (NO ACTION TAKEN): Name:{0}  ID:{1} --- ", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString()));
                            Console.WriteLine(string.Format("DUPLICATE RECORD (NO ACTION TAKEN): Name:{0}  ID:{1} -- ", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString()));
                            dupcount++;
                        }

                        //-------------------------------------------------------

                        //Console.ForegroundColor = ConsoleColor.Red;
                        //Console.WriteLine("ERROR");
                    }

                    //  Not sure about this one. (MAT)
                    clientContext.ExecuteQuery();
                }
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(string.Format("We updated: {0} records and added {1} records", countupdate.ToString(), countnew.ToString()));
                Console.WriteLine(string.Format("Duplicates found: {0} records", dupcount.ToString()));
                log.Debug(string.Format("------------------------------------------------------------"));
                log.Debug(string.Format("We updated: {0} records and added {1} records", countupdate.ToString(), countnew.ToString()));
                log.Debug(string.Format("Duplicates found: {0} records", dupcount.ToString()));
                Console.WriteLine("Completed first set of updates. \n");
                Console.WriteLine("Starting LOB checks........ \n");
                log.Debug(string.Format("------------------------------------------------------------"));
                log.Debug(string.Format("Starting LOB Checks........"));
                UpdateLOBFields(clientContext, oldList, oldItems, LOBitems, sharepointIndexTarget);
                //Console.WriteLine("Finished return from LOB update...");
                //oldList.Update();
                clientContext.ExecuteQuery();
                Console.WriteLine("Finished Line Of Business updates... \n");
            }
        }
        protected override async Task OnProvisioningAsync()
        {
            Web.Features.Add(FeatureId, Force, FeatureDefinitionScope);

            await ClientContext.ExecuteQueryAsync();
        }
Beispiel #53
0
        public static void UpdateLOBFields(ClientContext myclientContext, List myitemList, ListItemCollection myoldItems, ListItemCollection myLOBitems, string sharepointIndexTarget)
        {
            //Console.WriteLine("Inside UpdateLOBField");

            var     my_pipecount = 0;
            int     counter      = 0;
            Boolean my_pipemarker;
            Boolean isAssignable;


            //Console.Write("---- LIST CHECK ---------- \n");
            foreach (ListItem pipeItem in myoldItems)
            {
                my_pipemarker           = false;
                isAssignable            = true;
                Console.ForegroundColor = ConsoleColor.Green;
                //Console.Write("-------------------------- \n");
                var testobject = pipeItem["AccountName"];

                if (!Object.ReferenceEquals(null, testobject))
                {
                    //Console.Write("AccountName: {0} \n", pipeItem["AccountName"].ToString());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("AccountName -- NOT assignable here. --- Title: {0} entry", pipeItem["Title"].ToString());
                    isAssignable = false;
                }

                //-----------------------------------------------------------
                // Check to see if object is assignable
                //-----------------------------------------------------------
                if (isAssignable)
                {
                    //-----------------------------------------------------------
                    // If the pipeline item is not null, then update MPP the abject.
                    //-----------------------------------------------------------
                    var testobject1 = pipeItem["MPP"];
                    if (!Object.ReferenceEquals(null, testobject1))
                    {
                        //Console.Write("MPP {0} \n", pipeItem["MPP"].ToString());
                    }
                    else
                    {
                        //----------------------------------------------
                        // select matching record from LOB items
                        // Note: Try block to check for Null Reference in LOB table
                        //----------------------------------------------
                        try
                        {
                            var page = from ListItem itemlist in myLOBitems
                                       where itemlist["Title"].ToString() == pipeItem["AccountName"].ToString()
                                       select itemlist;

                            ListItem item = page.FirstOrDefault();

                            //----------------------------------------------
                            //Check if LOB item is null
                            //----------------------------------------------
                            var checkobject = item["MPP"];
                            if (checkobject != null)
                            {
                                //Console.WriteLine("MPP reference check");
                                Console.ForegroundColor = ConsoleColor.Blue;
                                Console.WriteLine("{0}: [{1}] -- MPP has been assigned. ({2})", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString(), item["MPP"].ToString());
                                pipeItem["MPP"] = item["MPP"];
                                log.Debug(string.Format("{0}: [{1}]  -- MPP has been assigned. ({2})", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString(), item["MPP"].ToString()));
                                my_pipemarker = true;
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("{0}: [{1}] -- MPP has NOT been assigned (Value not present)", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString());
                                log.Debug(string.Format("{0}: [{1}] -- MPP has NOT been assigned (Value not present)", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString()));
                            }
                        }
                        catch (NullReferenceException ex)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("ERROR: {0} not found in LOB list.  MPP is not assignable.", pipeItem["AccountName"].ToString());
                            log.Debug(string.Format("ERROR: {0} not found in LOB list.  MPP is not assignable.", pipeItem["AccountName"].ToString()));
                            //Console.WriteLine("Null Reference found: {0}", ex.Message);
                            //Console.ReadLine();
                        }
                    }
                }

                //-----------------------------------------------------------
                // Check to see if object is assignable
                //-----------------------------------------------------------
                if (isAssignable)
                {
                    //-----------------------------------------------------------
                    // If the pipeline item is not null, then update MPP the abject.
                    //-----------------------------------------------------------
                    var testobject2 = pipeItem["LineOfBusiness"];
                    if (!Object.ReferenceEquals(null, testobject2))
                    {
                        //Console.Write("LineOfBusiness: {0} \n", pipeItem["LineOfBusiness"].ToString());
                    }
                    else
                    {
                        //----------------------------------------------
                        // select matching record from LOB items
                        // Note: Try block to check for Null Reference in LOB table
                        //----------------------------------------------
                        try
                        {
                            var page = from ListItem itemlist in myLOBitems
                                       where itemlist["Title"].ToString() == pipeItem["AccountName"].ToString()
                                       select itemlist;

                            ListItem item = page.FirstOrDefault();

                            var checkobject = item["LineOfBusiness"];
                            if (checkobject != null)
                            {
                                //Console.WriteLine("Inside LineOfBusiness reference check");
                                Console.ForegroundColor = ConsoleColor.Blue;
                                Console.WriteLine("{0}: [{1}] -- LineOfBusiness has been assigned. ({2})", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString(), item["LineOfBusiness"].ToString());
                                pipeItem["LineOfBusiness"] = item["LineOfBusiness"];
                                log.Debug(string.Format("{0}: [{1}]  -- LineOfBusiness has been assigned. ({2})", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString(), item["LineOfBusiness"].ToString()));
                                my_pipemarker = true;
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("{0}: [{1}] -- LineOfBusiness has NOT been assigned (Value not present)", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString());
                                log.Debug(string.Format("{0}: [{1}] -- LineOfBusiness has NOT been assigned (Value not present)", sharepointIndexTarget.ToString(), pipeItem["HPOppID"].ToString()));
                            }
                        }
                        catch (NullReferenceException ex)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("ERROR: {0} not found in LOB list.  LineOfBusiniess is not assignable.", pipeItem["AccountName"].ToString());
                            log.Debug(string.Format("ERROR: {0} not found in LOB list.  LineOfBusiness is not assignable.", pipeItem["AccountName"].ToString()));
                            //Console.WriteLine("Null Reference found: {0}", ex.Message);
                            //Console.ReadLine();
                        }
                    }
                }

                if (my_pipemarker)
                {
                    my_pipecount++;
                    //Console.WriteLine("LOB change count is: {0}", my_pipecount);
                    pipeItem.Update();
                    myitemList.Update();
                    if (counter > 100)
                    {
                        try
                        {
                            myclientContext.ExecuteQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("caught an exception in during LOB updates object", ex);
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(string.Format("We had an issue within LOB Update:{0}", ex.ToString()));
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            counter = 0;
                            //Console.WriteLine("Connectivity was lost please try again");
                            throw ex;
                        }
                    }
                    else
                    {
                        counter++;
                    }
                    //myitemList.Update();
                    //myoldItems.ToList();
                }
            }


            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(string.Format("-----------------------------------------------"));
            Console.WriteLine(string.Format("Total LOB changes: {0}", my_pipecount));
            log.Debug(string.Format("Total LOB changes: {0}", my_pipecount));
            // Console.ReadLine();
        }
Beispiel #54
0
        private async static void CreateGraphGroup(string title)
        {
            string nick        = UrlFriendlyString(title);
            string accessToken = ContextHelper.GetAccessToken().Result;


            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async(requestMessage) =>
            {
                // Append the access token to the request.
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            }));



            Microsoft.Graph.Group addedGroup = null;

            var existinggroups = await graphClient.Groups.Request().Filter("mailNickName eq '" + nick + "'").GetAsync();

            if (existinggroups.Count > 0)
            {
                addedGroup = existinggroups[0];
            }

            if (addedGroup == null)
            {
                var newGroup = new Microsoft.Graph.Group
                {
                    DisplayName     = title,
                    Description     = title,
                    MailNickname    = nick,
                    MailEnabled     = true,
                    SecurityEnabled = false,
                    Visibility      = "Private",
                    GroupTypes      = new List <string> {
                        "Unified"
                    }
                };

                addedGroup = await graphClient.Groups.Request().AddAsync(newGroup);

                var user = await graphClient.Users["*****@*****.**"].Request().GetAsync();
                await graphClient.Groups[addedGroup.Id].Owners.References.Request().AddAsync(user);
            }

            string webUrl  = "";
            int    seconds = 0;

            do
            {
                Thread.Sleep(2000);
                seconds += 2;
                try
                {
                    var site = await graphClient.Groups[addedGroup.Id].Sites["root"].Request().Select("webUrl").GetAsync();
                    webUrl = site.WebUrl;
                }
                catch (Exception)
                {
                    Console.WriteLine("not found at " + seconds);
                    if (seconds > 30)
                    {
                        break;
                    }
                }
            } while (webUrl == "");
            Console.WriteLine(webUrl);
            using (ClientContext ctx = ContextHelper.GetContext(webUrl))
            {
                ctx.Load(ctx.Web);
                ctx.ExecuteQuery();

                Console.WriteLine(ctx.Web.Title);
            }
        }
Beispiel #55
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your user name");
            // Console.ForegroundColor = defaultForeground;
            string userName = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your password.");
            // Console.ForegroundColor = defaultForeground;
            SecureString password = GetPasswordFromConsoleInput();

            using (context = new ClientContext("https://microsoft.sharepoint.com/teams/USDXISVCJ/"))
            {
                context.Credentials = new SharePointOnlineCredentials(userName, password);
                Web currentWeb = context.Web;
                context.Load(currentWeb);
                context.ExecuteQuery();

                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(currentWeb.Context);

                TermStoreCollection termStores = taxonomySession.TermStores;

                currentWeb.Context.Load(termStores);

                currentWeb.Context.ExecuteQuery();

                TermStore termStore = termStores[0];

                currentWeb.Context.Load(termStore);

                currentWeb.Context.ExecuteQuery();

                TermGroupCollection termGroups = termStore.Groups;

                currentWeb.Context.Load(termGroups);

                currentWeb.Context.ExecuteQuery();

                TermGroup group = termGroups.GetByName("Site Collection - microsoft.sharepoint.com-teams-USDXISVCJ");

                TermSetCollection termSets = group.TermSets;

                currentWeb.Context.Load(termSets);

                currentWeb.Context.ExecuteQuery();

                TermCollection terms = termSets.GetByName("Workload").Terms;

                currentWeb.Context.Load(terms);

                currentWeb.Context.ExecuteQuery();

                Console.WriteLine(terms.Count);

                foreach (Term term in terms)
                {
                    Console.WriteLine(term.Name);
                }
            }
        }
Beispiel #56
0
 public VetModelsController(ClientContext context)
 {
     _context = context;
 }
Beispiel #57
0
        /// <summary>
        /// Sets the search center URL on site collection (Site Settings -> Site collection administration --> Search Settings)
        /// </summary>
        /// <param name="web">SharePoint site - root web</param>
        /// <param name="searchCenterUrl">Search center URL</param>
        public static void SetSiteCollectionSearchCenterUrl(this Web web, string searchCenterUrl)
        {
            if (searchCenterUrl == null)
            {
                throw new ArgumentNullException(nameof(searchCenterUrl));
            }

            // Currently there is no direct API available to set the search center URL on web.
            // Set search setting at site level

#if !ONPREMISES
            #region Enable scripting if needed and context has access
            Tenant        tenant       = null;
            Site          site         = null;
            ClientContext adminContext = null;
            if (web.IsNoScriptSite() && TenantExtensions.IsCurrentUserTenantAdmin(web.Context as ClientContext))
            {
                site = ((ClientContext)web.Context).Site;
                site.EnsureProperty(s => s.Url);

                var adminSiteUrl = web.GetTenantAdministrationUrl();
                adminContext = web.Context.Clone(adminSiteUrl);
                tenant       = new Tenant(adminContext);
                tenant.SetSiteProperties(site.Url, noScriptSite: false);
            }
            #endregion
#endif

            try
            {
                // if another value was set then respect that
                if (String.IsNullOrEmpty(web.GetPropertyBagValueString("SRCH_SB_SET_SITE", string.Empty)))
                {
                    web.SetPropertyBagValue("SRCH_SB_SET_SITE", "{'Inherit':false,'ResultsPageAddress':null,'ShowNavigation':true}");
                }

                if (!string.IsNullOrEmpty(searchCenterUrl))
                {
                    // Set search center URL
                    web.SetPropertyBagValue("SRCH_ENH_FTR_URL_SITE", searchCenterUrl);
                }
                else
                {
                    // When search center URL is blank remove the property (like the SharePoint UI does)
                    web.RemovePropertyBagValue("SRCH_ENH_FTR_URL_SITE");
                }
            }
            finally
            {
#if !ONPREMISES
                #region Disable scripting if previously enabled
                if (adminContext != null)
                {
                    // Reset disabling setting the property bag if needed
                    tenant.SetSiteProperties(site.Url, noScriptSite: true);
                    adminContext.Dispose();
                }
                #endregion
#endif
            }
        }
Beispiel #58
0
        /// <summary>
        /// Sets the search results page URL on current web (Site Settings -> Search --> Search Settings)
        /// </summary>
        /// <param name="web">SharePoint current web</param>
        /// <param name="searchCenterUrl">Search results page URL</param>
        public static void SetWebSearchCenterUrl(this Web web, string searchCenterUrl)
        {
            if (searchCenterUrl == null)
            {
                throw new ArgumentNullException(nameof(searchCenterUrl));
            }

            // Currently there is no direct API available to set the search center URL on web.
            // Set search setting at web level

#if !ONPREMISES
            #region Enable scripting if needed and context has access
            Tenant        tenant       = null;
            Site          site         = null;
            ClientContext adminContext = null;
            if (web.IsNoScriptSite() && TenantExtensions.IsCurrentUserTenantAdmin(web.Context as ClientContext))
            {
                site = ((ClientContext)web.Context).Site;
                site.EnsureProperty(s => s.Url);

                var adminSiteUrl = web.GetTenantAdministrationUrl();
                adminContext = web.Context.Clone(adminSiteUrl);
                tenant       = new Tenant(adminContext);
                tenant.SetSiteProperties(site.Url, noScriptSite: false);
            }
            #endregion
#endif

            try
            {
                string keyName = web.IsSubSite() ? "SRCH_SB_SET_WEB" : "SRCH_SB_SET_SITE";

                if (!string.IsNullOrEmpty(searchCenterUrl))
                {
                    // Set search results page URL
                    web.SetPropertyBagValue(keyName, "{\"Inherit\":false,\"ResultsPageAddress\":\"" + searchCenterUrl + "\",\"ShowNavigation\":false}");
                }
                else
                {
                    // When search results page URL is blank remove the property (like the SharePoint UI does)
                    web.RemovePropertyBagValue(keyName);
                }
            }
            catch (ServerUnauthorizedAccessException e)
            {
                const string errorMsg = "For modern sites you need to be a SharePoint admin when setting the search redirect URL programatically.\n\nPlease use the classic UI at '/_layouts/15/enhancedSearch.aspx?level=sitecol'.";
                Log.Error(e, Constants.LOGGING_SOURCE, errorMsg);
                throw new ApplicationException(errorMsg, e);
            }
            finally
            {
#if !ONPREMISES
                #region Disable scripting if previously enabled
                if (adminContext != null)
                {
                    // Reset disabling setting the property bag if needed
                    tenant.SetSiteProperties(site.Url, noScriptSite: true);
                    adminContext.Dispose();
                }
                #endregion
#endif
            }
        }
        private string RESTSave(ClientContext clientContext, string ItemData)
        {
            RestService restService = new RestService();

            return(restService.SaveItem(clientContext, "INT_SliderTx", ItemData));
        }
Beispiel #60
0
        public void sentdatatoSPLIst()
        {
            string careeractivities = "";
            string otheractivities  = "";
            string k = "";

            for (int i = 0; i < chk_CareerActivities.Items.Count; i++)
            {
                if (chk_CareerActivities.Items[i].Selected)
                {
                    k = k + chk_CareerActivities.Items[i].Value + ";";
                }
            }
            careeractivities = k;

            string j = "";

            for (int n = 0; n < chk_OtherActivities.Items.Count; n++)
            {
                if (chk_OtherActivities.Items[n].Selected)
                {
                    j = j + chk_OtherActivities.Items[n].Value + ";";
                }
            }
            otheractivities = j;

            int sem  = 0;
            int Year = LibraryMOD.SeperateTerm(LibraryMOD.GetCurrentTerm(), out sem);

            int    iYear     = Year;
            int    iSem      = sem;
            string sSemester = LibraryMOD.GetSemesterString(iSem);

            string languageoption = "";

            if (Session["LanguageOption"].ToString() == "True")
            {
                languageoption = "<b>Language:</b> " + ddlLanguage.SelectedItem.Text + "";
            }

            string login          = "******"; //give your username here
            string password       = "******";                 //give your password
            var    securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            string        siteUrl       = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices";
            ClientContext clientContext = new ClientContext(siteUrl);

            Microsoft.SharePoint.Client.List myList   = clientContext.Web.Lists.GetByTitle("Students_Requests");
            ListItemCreationInformation      itemInfo = new ListItemCreationInformation();

            Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo);
            string refno = Create16DigitString();

            myItem["Title"] = refno;
            //myItem["RequestID"] = refno;
            myItem["Year"]        = iYear;
            myItem["Semester"]    = iSem;
            myItem["Request"]     = "<b>Service ID:</b> " + lbl_ServiceID.Text + "<br/> <b>Service Name:</b> " + lbl_ServiceNameEn.Text + " (" + lbl_ServiceNameAr.Text + " )<br/><b>Date of Birth:</b> " + lbl_DOB.Text + "<br/><b>Graduation Semester:</b> " + lbl_GraduationSemester.Text + "<br/><b>Graduation Year:</b> " + lbl_GraduationYear.Text + "<br/><b>Major:</b> " + lbl_Major.Text + "<br/><b>Address:</b> " + txt_Address.Text + "<br/><b>Mobile #1:</b> " + txt_StudentContact1.Text + "<br/><b>Mobile #2:</b> " + txt_StudentContact2.Text + "<br/><b>Email:</b> " + txt_Email.Text + "<br/><b>Work Place:</b> " + txt_WorkPlace.Text + "<br/><b>Job Title:</b> " + txt_JobTitle.Text + "<br/><b>Direct Supervisor Name:</b> " + txt_DirSupName.Text + "<br/><b>Direct Supervisor Job Title:</b> " + txt_DirSupJobtitle.Text + "<br/><b>Contact Details:</b> " + txt_ContactDetails.Text + "<br/><b>Career Development Activities (Workshop/Seminar):</b> " + careeractivities + "<br/><b>Other Activities:</b> " + otheractivities + "<br/><b>Other Suggestion for Alumni services & Activities:</b> " + txt_Remarks.Text + "<br/>" + languageoption + "<br/>";
            myItem["RequestNote"] = txt_Remarks.Text.Trim();
            myItem["ServiceID"]   = lbl_ServiceID.Text;
            myItem["Fees"]        = hdf_Price.Value;
            myItem["Requester"]   = clientContext.Web.EnsureUser(hdf_StudentEmail.Value);
            //myItem["Requester"] = clientContext.Web.EnsureUser("*****@*****.**");
            myItem["StudentID"]     = lbl_StudentID.Text;
            myItem["StudentName"]   = lbl_StudentName.Text;
            myItem["Contact"]       = txt_StudentContact1.Text;
            myItem["Finance"]       = clientContext.Web.EnsureUser(Session["FinanceEmail"].ToString());
            myItem["FinanceAction"] = "Initiate";
            myItem["FinanceNote"]   = "";
            myItem["Host"]          = clientContext.Web.EnsureUser(Session["HostEmail"].ToString());//Session["HostEmail"].ToString();
            myItem["HostAction"]    = "Initiate";
            myItem["HostNote"]      = "";
            //myItem["Provider"] = "";
            myItem["ProviderAction"] = "Initiate";
            myItem["ProviderNote"]   = "";
            myItem["Status"]         = "Finance Approval Needed";
            //myItem["Modified"] = DateTime.Now;
            //myItem["Created"] = DateTime.Now;
            //myItem["Created By"] = hdf_StudentEmail.Value;
            //myItem["Modified By"] = hdf_StudentEmail.Value;
            try
            {
                myItem.Update();

                //if (flp_Upload.HasFile)
                //{
                //    var attachment = new AttachmentCreationInformation();

                //    flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName));
                //    string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName);

                //    string filePath = FileUrl;
                //    attachment.FileName = Path.GetFileName(filePath);
                //    attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath));
                //    Attachment att = myItem.AttachmentFiles.Add(attachment);
                //}

                var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
                clientContext.Credentials = onlineCredentials;
                clientContext.ExecuteQuery();

                //string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName);
                //System.IO.File.Delete(FileUrls);

                lbl_Msg.Text         = "Request (ID# " + refno + ") Generated Successfully";
                lbl_Msg.Visible      = true;
                div_msg.Visible      = true;
                lnk_Generate.Enabled = false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //Console.ReadLine();
        }