コード例 #1
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("Triggering Azure Function to process the JSON");

            // parse query parameter
            string fileName = req.GetQueryNameValuePairs()
                              .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                              .Value;

            string tenantAdminUrl = "https://m365x131504-admin.sharepoint.com";
            // User name and pwd to login to the tenant
            string userName = "";
            string pwd      = "";

            string fileUrl = "https://m365x131504.sharepoint.com/sites/PowerApps/Shared%20Documents/" + fileName;
            ClientResult <Guid> workItemId;
            string status = string.Empty;

            // Get access to source tenant with tenant permissions
            using (var ctx = new ClientContext(tenantAdminUrl))
            {
                //Provide count and pwd for connecting to the source
                var passWord = new SecureString();
                foreach (char c in pwd.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

                // Only to check connection and permission, could be removed
                ctx.Load(ctx.Web);
                ctx.ExecuteQuery();
                string title = ctx.Web.Title;

                // Let's get started on the actual code!!!
                Office365Tenant tenant = new Office365Tenant(ctx);
                ctx.Load(tenant);
                ctx.ExecuteQuery();

                /// /// /// /// /// /// /// /// ///
                /// DO import based on file whcih is already uploaded to tenant
                /// /// /// /// /// /// /// /// ///

                // Type of user identifier ["PrincipleName", "EmailAddress", "CloudId"]
                // in the User Profile Service.
                // In this case we use email as the identifier at the UPA storage
                ImportProfilePropertiesUserIdType userIdType = ImportProfilePropertiesUserIdType.Email;

                // Name of user identifier property in the JSON
                var userLookupKey = "IdName";

                var propertyMap = new System.Collections.Generic.Dictionary <string, string>();
                // First one is the file, second is the target at User Profile Service
                // Notice that we have here 2 custom properties in UPA called 'City' and 'Office'
                propertyMap.Add("MyCustomProperty", "MyCustomProperty");
                propertyMap.Add("MyCustomProperty1", "MyCustomProperty1");

                // Returns a GUID, which can be used to see the status of the execution and end results
                workItemId = tenant.QueueImportProfileProperties(
                    userIdType, userLookupKey, propertyMap, fileUrl
                    );

                ctx.ExecuteQuery();

                var job = tenant.GetImportProfilePropertyJob(workItemId.Value);
                ctx.Load(job);
                ctx.ExecuteQuery();

                status = string.Format("ID: {0} - Request status: {1} - Error status: {2}",
                                       job.JobId, job.State.ToString(), job.Error.ToString());
            }


            return(workItemId == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Some Error Occurred")
                : req.CreateResponse(HttpStatusCode.OK, status));
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: t30d13/PnP
        static void Main(string[] args)
        {
            ConsoleColor defaultForeground = Console.ForegroundColor;
            // Something like: https://contoso-admin.sharepoint.com
            string tenantAdminUrl = GetInput("Enter the admin URL of your tenant", false, defaultForeground);
            // User name and pwd to login to the tenant
            string userName = GetInput("Enter your user name", false, defaultForeground);
            string pwd      = GetInput("Enter your password", true, defaultForeground);
            // File URL to the profile value like: https://contoso.sharepoint.com/Shared%20Documents/sample.txt
            string fileUrl = GetInput("Enter the URL to the file located in your tenant", false, defaultForeground);

            // Get access to source tenant with tenant permissions
            using (var ctx = new ClientContext(tenantAdminUrl))
            {
                //Provide count and pwd for connecting to the source
                var passWord = new SecureString();
                foreach (char c in pwd.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

                // Only to check connection and permission, could be removed
                ctx.Load(ctx.Web);
                ctx.ExecuteQuery();
                string title = ctx.Web.Title;

                // Let's get started on the actual code!!!
                Office365Tenant tenant = new Office365Tenant(ctx);
                ctx.Load(tenant);
                ctx.ExecuteQuery();

                /// /// /// /// /// /// /// /// ///
                /// DO import based on file whcih is already uploaded to tenant
                /// /// /// /// /// /// /// /// ///

                // Type of user identifier ["PrincipleName", "EmailAddress", "PrincipalName"]
                // in the User Profile Service.
                // In this case we use email as the identifier at the UPA storage
                ImportProfilePropertiesUserIdType userIdType =
                    ImportProfilePropertiesUserIdType.Email;

                // Name of user identifier property in the JSON
                var userLookupKey = "IdName";

                var propertyMap = new System.Collections.Generic.Dictionary <string, string>();
                // First one is the file, second is the target at User Profile Service
                // Notice that we have here 2 custom properties in UPA called 'City' and 'OfficeCode'
                propertyMap.Add("Title", "Title");
                propertyMap.Add("City", "City");
                propertyMap.Add("Office", "OfficeCode");

                // Returns a GUID, which can be used to see the status of the execution and end results
                var workItemId = tenant.QueueImportProfileProperties(
                    userIdType, userLookupKey, propertyMap, fileUrl
                    );

                ctx.ExecuteQuery();

                /// /// /// /// /// /// /// /// /// ///
                // CALL CHECK STATUS in OWN method with the received GUID
                /// /// /// /// /// /// /// /// /// ///
                CheckStatusOfRequestedProcess(ctx, workItemId.Value);

                // Just to pause and indicate that it's all done
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("\n-----------------------------------------");
                Console.WriteLine("We are all done. Press enter to continue.");
                Console.ReadLine();
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: PCfromDC/spc18-UPA
        static void Main(string[] args)
        {
            #region Variables:
            string adminURL      = "https://pcfromdc-admin.sharepoint.com";       // SPO Admin Site URL
            string siteURL       = "https://pcfromdc.sharepoint.com/sites/spc18"; // Site where we upload JSON file
            string importFileURL = "https://pcfromdc.sharepoint.com/sites/spc18/upaSync/upaOutput-WebJob.txt";
            string docLibName    = "UPA Sync";                                    // Document Library Name for upload
            string spoUserName   = ConfigurationManager.AppSettings["spoUserName"];
            string spoPassword   = ConfigurationManager.AppSettings["spoPassword"];
            #endregion

            #region Query SQL and Build JSON'ish String for upload to O365
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource     = "pcdemo.database.windows.net";
            builder.UserID         = ConfigurationManager.AppSettings["dataBaseUserName"];
            builder.Password       = ConfigurationManager.AppSettings["dataBasePW"];
            builder.InitialCatalog = "pcDemo_Personnel";
            #endregion

            #region Start to build jsonOutput string
            StringBuilder jsonSB = new StringBuilder();
            jsonSB.AppendLine("{");
            jsonSB.AppendLine("\"value\":");
            jsonSB.AppendLine("[");
            #endregion

            #region Get info from Azure SQL Table
            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();
                StringBuilder sb = new StringBuilder();
                sb.Append("SELECT TOP(10) mail, city  ");
                sb.Append("FROM pcDemo_SystemUsers ");
                sb.Append("Where city is not null ");
                sb.Append("and mail like '*****@*****.**' ");
                sb.Append("or mail like '%pcdemo.net'");
                String sql = sb.ToString();

                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            jsonSB.AppendLine("{");
                            jsonSB.AppendLine("\"IdName\": \"" + reader.GetString(0) + "\",");
                            jsonSB.AppendLine("\"Property1\": \"" + reader.GetString(1) + "\"");
                            jsonSB.AppendLine("},");
                        }
                    }
                }
            }
            Console.WriteLine("SQL query completed...");
            #endregion

            #region finish json'ish string and convert to stream
            // Clean up jsonSB and remove last comma
            string jasonClean = jsonSB.ToString();
            jasonClean = (jasonClean.Trim()).TrimEnd(',');
            // Add jasonClean back into StringBuilder
            StringBuilder jsonEnd = new StringBuilder(jasonClean);
            jsonEnd.AppendLine("");
            jsonEnd.AppendLine("]");
            jsonEnd.AppendLine("}");
            string jsonOutput = jsonEnd.ToString();
            Console.WriteLine("JSON build completed...");

            // Convert String to Stream
            byte[]       byteArray = Encoding.UTF8.GetBytes(jsonOutput);
            MemoryStream stream    = new MemoryStream(byteArray);
            Console.WriteLine("JSON converted...");
            #endregion

            #region Upload JSON file to SPO
            using (var clientContext = new ClientContext(siteURL))
            {
                // set username and password
                var passWord = new SecureString();
                foreach (char c in spoPassword.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(spoUserName, passWord);

                Web web = clientContext.Web;
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Overwrite     = true;
                newFile.ContentStream = stream;
                newFile.Url           = importFileURL;
                List docLibrary = web.Lists.GetByTitle(docLibName);
                docLibrary.RootFolder.Files.Add(newFile);
                clientContext.Load(docLibrary);
                clientContext.ExecuteQuery();
            }
            Console.WriteLine("File Uploaded...");
            #endregion

            #region Bulk Upload API
            using (var clientContext = new ClientContext(adminURL))
            {
                // set username and password
                var passWord = new SecureString();
                foreach (char c in spoPassword.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(spoUserName, passWord);

                // Get Tenant Context
                Office365Tenant tenant = new Office365Tenant(clientContext);
                clientContext.Load(tenant);
                clientContext.ExecuteQuery();

                // Only to check connection and permission, could be removed
                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();
                string title = clientContext.Web.Title;
                Console.WriteLine("Logged into " + title + "...");

                clientContext.Load(clientContext.Web);
                ImportProfilePropertiesUserIdType userIdType = ImportProfilePropertiesUserIdType.Email;
                var userLookupKey = "IdName";
                var propertyMap   = new System.Collections.Generic.Dictionary <string, string>();
                propertyMap.Add("Property1", "City");
                // propertyMap.Add("Property2", "Office");
                var workItemId = tenant.QueueImportProfileProperties(userIdType, userLookupKey, propertyMap, importFileURL);
                clientContext.ExecuteQuery();
            }
            Console.WriteLine("UPA Bulk Update Completed...");
            #endregion
        }