public string Get(string title, string description)
        {
            String result = "";

            string siteUrl = "https://xxxxx.sharepoint.com/sites/xxxxx";                                                                 // Sharepoint URL where you have administrative permisions

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "xxxxxxx", "xxxxxxx")) //put the client id and secret generate in sharepoint app registration site
            {
                cc.Load(cc.Web, p => p.Title);
                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                Web web = cc.Web;

                if (ProvisionSubSite(title, description, cc))
                {
                    result = "Hola el Site group fue creado satisfactoriamente: " + title + " Descripción: " + description;
                }
                else
                {
                    result = "Algo salio mal";
                }
            };
            return(result);
        }
Exemplo n.º 2
0
 private bool TrySharePointConnection(string url, string clientId, string clientSecret)
 {
     try
     {
         using (var Context = new AuthenticationManager().GetAppOnlyAuthenticatedContext(url, clientId, clientSecret))
         {
             var web = Context.Web;
             try
             {
                 Context.Load(web);
                 Context.ExecuteQuery();
                 return(true);
             }
             catch (Exception)
             {
                 return(false);
             }
         };
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Exemplo n.º 3
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function BetterCopyFunction processed a request.");

            string errorMsg = "";

            try
            {
                dynamic data = await req.Content.ReadAsAsync <object>();

                string targetUrl     = data?.targetUrl;
                string sourceUrl     = data?.sourceUrl;
                Uri    targetSiteUri = new Uri(targetUrl);
                Uri    sourceSiteUri = new Uri(sourceUrl);
                string pageLayout    = data?.pageLayout;

                string fileName = ""; // we get this from the source item

                int sourceId;

                try
                {
                    string strSourceId = data?.sourceId;
                    sourceId = int.Parse(strSourceId);
                }
                catch (Exception)
                {
                    log.Error("Setting up variables failed.");
                    errorMsg += "Setting up variables failed.";
                    throw;
                }

                log.Info("Got the variables! Now connecting to SharePoint...");

                // Get the realm for the URL
                var realm = TokenHelper.GetRealmFromTargetUrl(targetSiteUri);
                // parse tenant admin url from the sourceUrl (there's probably a cuter way to do this but this is simple :])
                string tenantAdminUrl = sourceUrl.Substring(0, sourceUrl.IndexOf(".com") + 4).TrimEnd(new[] { '/' }).Replace(".sharepoint", "-admin.sharepoint");
                // parse tenant url from the admin url
                var tenantUrl        = tenantAdminUrl.Substring(0, tenantAdminUrl.IndexOf(".com") + 4).Replace("-admin", "");
                AzureEnvironment env = TokenHelper.getAzureEnvironment(tenantAdminUrl);

                using (var ctx_target = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(targetSiteUri.ToString(), clientId, clientSecret, env))
                {
                    log.Info("Target site context built successfully!");

                    using (var ctx_source = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(sourceSiteUri.ToString(), clientId, clientSecret, env))
                    {
                        log.Info("Source site context built successfully!");

                        var exists = ctx_target.WebExistsFullUrl(targetUrl);

                        string targetWebUrl = targetUrl.Replace(tenantUrl, "");
                        var    targetWeb    = ctx_target.Site.OpenWeb(targetWebUrl);

                        ctx_target.Load(ctx_target.Site);
                        ctx_target.Load(targetWeb);
                        ctx_target.ExecuteQuery();

                        var sourceWeb = ctx_source.Site.OpenWeb(sourceUrl.Replace(tenantUrl, ""));
                        ctx_source.Load(sourceWeb);
                        ctx_source.ExecuteQuery();

                        log.Info("SharePoint connection fine! Connected to: " + targetWeb.Title);

                        pageLayout = ctx_target.Site.Url + pageLayout.Substring(pageLayout.IndexOf("/_catalogs"));

                        var sourceList = sourceWeb.Lists.GetByTitle("Pages");
                        ctx_source.Load(sourceList);
                        ctx_source.ExecuteQuery();

                        var targetList = targetWeb.Lists.GetByTitle("Pages");
                        ctx_target.Load(targetList);
                        ctx_target.ExecuteQuery();

                        log.Info("... and: " + targetList.Title + " " + targetList.ItemCount);

                        string publishingPageContent = "";

                        ListItem sourceItem = null;
                        try
                        {
                            sourceItem = sourceList.GetItemById(sourceId);

                            if (sourceItem == null)
                            {
                                string    qs    = String.Format("<View><Query><Where><Eq><FieldRef Name=\"ID\"></FieldRef><Value Type=\"Number\">{0}</Value></Eq></Where></Query></View>", sourceId);
                                CamlQuery query = new CamlQuery();
                                query.ViewXml = qs;
                                var items = sourceList.GetItems(query);

                                ctx_source.Load(items);
                                ctx_source.ExecuteQuery();

                                sourceItem = items.First();
                            }
                        }
                        catch (Exception ex)
                        {
                            sourceItem = sourceWeb.GetListItem("/Pages/Forms/DispForm.aspx?ID=" + sourceId);
                            errorMsg  += ex.Message + " ";
                        }
                        finally
                        {
                            ctx_source.Load(sourceItem);
                            ctx_source.Load(sourceItem.File);
                            ctx_source.Load(sourceItem, r => r.Client_Title, r => r.Properties);
                            ctx_source.ExecuteQueryRetry();

                            log.Info("Got source item! Title: " + sourceItem.Client_Title);

                            if (sourceItem["PublishingPageContent"] != null)
                            {
                                publishingPageContent = sourceItem["PublishingPageContent"].ToString();
                            }
                        }

                        fileName = sourceItem.File.Name;

                        // at this point, we've fetched all the info we needed. On to getting the target item, and then updating the fields there.
                        ListItem targetItem = null;
                        try
                        {
                            targetItem = targetList.GetItemById(sourceId);

                            if (targetItem == null)
                            {
                                string    qs1    = String.Format("<View><Query><Where><Eq><FieldRef Name=\"ID\"></FieldRef><Value Type=\"Number\">{0}</Value></Eq></Where></Query></View>", sourceId);
                                CamlQuery query1 = new CamlQuery();
                                query1.ViewXml = qs1;
                                var items1 = targetList.GetItems(query1);

                                ctx_target.Load(items1);
                                ctx_target.ExecuteQuery();

                                targetItem = items1.First();
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Warning("Getting source item via conventional ways failed. Trying the unorthodox ones...");

                            targetItem = targetWeb.GetListItem("/Pages/Forms/DispForm.aspx?ID=" + sourceId);

                            var items = targetList.GetItems(CamlQuery.CreateAllItemsQuery());
                            ctx_target.Load(items);
                            ctx_target.ExecuteQueryRetry();

                            for (int i = 0; i < items.Count; i++)
                            {
                                if (items[i].Id == sourceId)
                                {
                                    targetItem = items[i];
                                }
                            }
                        }
                        finally
                        {
                            try
                            {
                                string str = "Published automatically by an Azure Function (BetterCopyFunction).";
                                targetItem.File.CheckIn(str, CheckinType.MajorCheckIn);
                                targetItem.File.Publish(str);

                                ctx_target.Load(targetItem);

                                ctx_target.ExecuteQueryRetry();
                            }
                            catch (Exception ex)
                            {
                                log.Info("Error: " + ex.Message);
                            }

                            ctx_target.Load(targetItem);
                            ctx_target.Load(targetItem, r => r.Client_Title, r => r.Properties);
                            ctx_target.ExecuteQueryRetry();
                        }

                        log.Info("Target item title: " + targetItem.Client_Title);

                        try
                        {
                            targetItem["PublishingPageLayout"]  = pageLayout;
                            targetItem["PublishingPageContent"] = publishingPageContent;
                            targetItem.SystemUpdate();

                            ctx_target.ExecuteQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Warning("There was an error in saving target item values. Values were: " + pageLayout + " " + publishingPageContent);
                            log.Warning("Error was: " + ex.Message);
                        }
                        finally
                        {
                            log.Info("Target item updated!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMsg += ex.Message;
                errorMsg += "\r\n " + ex.StackTrace;

                throw;
            }

            return(String.IsNullOrEmpty(errorMsg)
                ? req.CreateResponse(HttpStatusCode.OK, "Function run was a success.")
                : req.CreateResponse(HttpStatusCode.InternalServerError, errorMsg));
        }
Exemplo n.º 4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            // string appOnlyId = ConfigurationManager.AppSettings["AppOnlyID"];
            // string appOnlySecret = ConfigurationManager.AppSettings["AppOnlySecret"];

            // parse query parameter
            log.LogInformation("C# HTTP trigger function processed a request.");

            // // parse query parameter
            string title           = req.Query["title"];
            string nameFR          = req.Query["spacenamefr"];
            string owner1          = req.Query["owner1"];
            string owner2          = req.Query["owner2"];
            string owner3          = req.Query["owner3"];
            string description     = req.Query["description"];
            string template        = req.Query["template"];
            string descriptionFr   = req.Query["descriptionFr"];
            string business        = req.Query["business"];
            string requester_name  = req.Query["requester_name"];
            string requester_email = req.Query["requester_email"];

            // // Get request body
            //dynamic data = await req.Content.ReadAsAsync<object>();
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // // Set name to query string or body data
            title           = title ?? data?.name.title;
            nameFR          = nameFR ?? data?.name.nameFR;
            owner1          = owner1 ?? data?.name.owner1;
            owner2          = owner2 ?? data?.name.owner2;
            owner3          = owner3 ?? data?.name.owner3;
            description     = description ?? data?.name.description;
            template        = template ?? data?.name.template;
            descriptionFr   = descriptionFr ?? data?.name.descriptionFr;
            business        = business ?? data?.name.business;
            requester_name  = requester_name ?? data?.name.requester_name;
            requester_email = requester_email ?? data?.name.requester_email;

            log.LogInformation("get info" + title);

            //  string name = req.Query["name"];

            // string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            // dynamic data = JsonConvert.DeserializeObject(requestBody);
            //name = name ?? data?.name;


            //using (var cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, "1d4139b1-fd16-4f06-8ac6-7b9ac7b58864", "tbssctdev.onmicrosoft.com", @"C:\test.pfx", "password123"))

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteURL, "", "", KeyVaultAccess.GetKeyVaultCertificate("", "")))
            {
                cc.Load(cc.Web, p => p.Title);
                cc.Load(cc.Web, p => p.Description);

                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                Console.WriteLine(cc.Web.Description);



                //ClientContext ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteURL, appOnlyId, appOnlySecret);
                log.LogInformation("get context");

                Web  web  = cc.Web;
                List list = cc.Web.Lists.GetByTitle("Space Requests");
                log.LogInformation("get list");

                ListItemCreationInformation oListItemCreationInformation = new ListItemCreationInformation();
                ListItem oItem = list.AddItem(oListItemCreationInformation);

                User userTest  = web.EnsureUser(owner1);
                User userTest2 = web.EnsureUser(owner2);


                cc.Load(userTest);
                cc.ExecuteQuery();
                log.LogInformation("get user");
                owner1 = userTest.Id.ToString() + ";#" + userTest.LoginName.ToString();
                cc.Load(userTest2);
                cc.ExecuteQuery();
                owner2 = userTest2.Id.ToString() + ";#" + userTest2.LoginName.ToString();
                if (owner3 != "")
                {
                    User userTest3 = web.EnsureUser(owner3);
                    cc.Load(userTest3);
                    cc.ExecuteQuery();
                    owner3 = userTest3.Id.ToString() + ";#" + userTest3.LoginName.ToString();
                }

                oItem["Space_x0020_Name"]          = title;
                oItem["Space_x0020_Name_x0020_FR"] = nameFR;
                oItem["Owner1"] = owner1 + ";#" + owner2 + ";#" + owner3;
                oItem["Space_x0020_Description_x0020__x"]  = description;
                oItem["Template_x0020_Title"]              = template;
                oItem["Space_x0020_Description_x0020__x0"] = descriptionFr;
                oItem["Team_x0020_Purpose_x0020_and_x00"]  = business;
                oItem["Business_x0020_Justification"]      = business;
                oItem["Requester_x0020_Name"]              = requester_name;
                oItem["Requester_x0020_email"]             = requester_email;
                oItem["_Status"] = "Submitted";
                oItem.Update();
                cc.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = string.Format(@"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Space_x0020_Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                    </Query>
                    <ViewFields>
                        <FieldRef Name='ID'/>
                        <FieldRef Name='Space_x0020_Name'/>
                    </ViewFields>
                    <RowLimit>1</RowLimit>
                </View>", title);

                ListItemCollection collListItemID = list.GetItems(camlQuery);
                cc.Load(collListItemID);
                cc.ExecuteQuery();

                int requestID = 0;

                foreach (ListItem oListItem in collListItemID)
                {
                    log.LogInformation(oListItem["Space_x0020_Name"].ToString());
                    requestID = oListItem.Id;
                }
                ListItem collListItem = list.GetItemById(requestID);
                // changes some fields
                collListItem["SharePoint_x0020_Site_x0020_URL"] = "https://.sharepoint.com/teams/1000" + requestID;
                collListItem.Update();
                // executes the update of the list item on SharePoint
                cc.ExecuteQuery();

                //req.CreateResponse(HttpStatusCode.InternalServerError, "Create item successfully ");

                //  }
                //return null;

                string responseMessage = "Create item successfully ";

                return(new OkObjectResult(responseMessage));
            }
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            // Office 365 Multi-tenant sample
            ClientContext cc = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com/sites/130020", "*****@*****.**", GetPassWord());
            
            //if (!cc.Site.IsInPlaceRecordsManagementActive())
            //{
            //    cc.Site.EnableSiteForInPlaceRecordsManagement();
            //}
            
            FileStream ostrm;
            StreamWriter writer = null;
            TextWriter oldOut = Console.Out;
            string fileName = @"c:\temp\recordsmanagement.txt";

            //Redirect console to file if needed
            if (!toConsole)
            {
                try
                {
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }
                    ostrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                    writer = new StreamWriter(ostrm);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open recordsmanagement.txt for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
                Console.SetOut(writer);
            }

            List ecm = cc.Web.GetListByTitle("Documents");

            //List ecm = cc.Web.GetListByTitle("ECMTest");
            cc.Load(ecm.RootFolder, p => p.Properties);
            cc.Load(ecm.EventReceivers);
            cc.Load(cc.Web, t => t.AllProperties);
            cc.ExecuteQuery();

            Console.WriteLine("Web properties:");
            foreach(var prop in cc.Web.AllProperties.FieldValues)
            {
                Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : ""));
            }

            Console.WriteLine("=======================================================");
            Console.WriteLine("Rootfolder props = list props:");
            foreach(var prop in ecm.RootFolder.Properties.FieldValues)
            {
                Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : ""));
            }
            Console.WriteLine("=======================================================");
            Console.WriteLine("List event receivers:");
            foreach (var eventReceiver in ecm.EventReceivers)
            {
                Console.WriteLine(String.Format("Name: {0}", eventReceiver.ReceiverName));
                Console.WriteLine(String.Format("Type: {0}", eventReceiver.EventType));
                Console.WriteLine(String.Format("Assembly: {0}", eventReceiver.ReceiverAssembly));
                Console.WriteLine(String.Format("Class: {0}", eventReceiver.ReceiverClass));
                Console.WriteLine(String.Format("Url: {0}", eventReceiver.ReceiverUrl));
                Console.WriteLine(String.Format("Sequence: {0}", eventReceiver.SequenceNumber));
                Console.WriteLine(String.Format("Synchronisation: {0}", eventReceiver.Synchronization));
            }

            Console.WriteLine("=======================================================");
            Console.WriteLine("List items:");
            CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
            ListItemCollection items = ecm.GetItems(query);

            cc.Load(items);
            cc.ExecuteQuery();
            foreach (ListItem listItem in items)
            {
                foreach (var field in listItem.FieldValues)
                {
                    Console.WriteLine("{0} : {1}", field.Key, field.Value);
                }
                Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            }

            if (!toConsole)
            {
                writer.Flush();
                Console.Out.Close();
                Console.SetOut(oldOut);
            }
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();

        }
Exemplo n.º 6
0
        public static async Task <object> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"Webhook was triggered!");

            // Grab the validationToken URL parameter
            string validationToken = req.GetQueryNameValuePairs()
                                     .FirstOrDefault(q => string.Compare(q.Key, "validationtoken", true) == 0)
                                     .Value;

            // If a validation token is present, we need to respond within 5 seconds by
            // returning the given validation token. This only happens when a new
            // web hook is being added
            if (validationToken != null)
            {
                log.Info($"Validation token {validationToken} received");
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(validationToken);
                return(response);
            }

            log.Info($"SharePoint triggered our webhook...great :-)");
            var content = await req.Content.ReadAsStringAsync();

            log.Info($"Received following payload: {content}");

            var notifications = JsonConvert.DeserializeObject <ResponseModel <NotificationModel> >(content).Value;

            log.Info($"Found {notifications.Count} notifications");

            // there should always be just one so let's get the first item
            var notification = notifications.First();

            // Get the realm for the URL
            var tenantAdminUrl   = ConfigurationManager.AppSettings["SiteCollectionRequests_TenantAdminSite"].TrimEnd(new[] { '/' });
            var tenantUrl        = tenantAdminUrl.Substring(0, tenantAdminUrl.IndexOf(".com") + 4).Replace("-admin", "");
            AzureEnvironment env = TokenHelper.getAzureEnvironment(tenantAdminUrl);

            log.Info($"Tenant url {tenantUrl} and notification from {notification.SiteUrl} ");

            string fullUrl = string.Format("{0}{1}", tenantUrl, notification.SiteUrl);

            log.Info($"{fullUrl}");
            Uri targetSiteUri = new Uri(fullUrl);

            log.Info($"Connecting to SharePoint at {targetSiteUri.AbsoluteUri}");

            var realm = TokenHelper.GetRealmFromTargetUrl(targetSiteUri);

            try
            {
                using (var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(targetSiteUri.ToString(), clientId, clientSecret, env))
                {
                    log.Info("Connected to SharePoint!");

                    var ctxWeb = ctx.Site.OpenWebById(new Guid(notification.WebId));
                    try
                    {
                        ctx.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error in ctx ExecuteQueryRetry, stage 1: " + ex.Message);
                        throw;
                    }

                    Guid listId = new Guid(notification.Resource);

                    List targetList = ctxWeb.Lists.GetById(listId);
                    ctx.Load(targetList, List => List.ParentWebUrl);
                    ctx.Load(targetList, List => List.Title);
                    ctx.Load(targetList, List => List.DefaultViewUrl);
                    ctx.Load(ctxWeb, Web => Web.Url);
                    ctx.ExecuteQueryRetry();

                    log.Info($"Got list {targetList.Title} at {ctxWeb.Url} !");

                    // now send the query to a custom API as a POST
                    var values = new Dictionary <string, string>();

                    if (notifications.Count > 0)
                    {
                        log.Info($"Processing notifications...");

                        StringContent       stringcontent;
                        HttpResponseMessage apiresponse;

                        if (enrichViaExternalAPI)
                        {
                            for (int i = 0; i < notifications.Count; i++)
                            {
                                var n = notifications[i];
                                //        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("<YOUR STORAGE ACCOUNT>");
                                //        // Get queue... create if does not exist.
                                //        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
                                //        CloudQueue queue = queueClient.GetQueueReference("sharepointlistwebhookeventazuread");
                                //        queue.CreateIfNotExists();

                                //        // add message to the queue
                                string m = JsonConvert.SerializeObject(n);
                                //        log.Info($"Before adding a message to the queue. Message content: {message}");
                                //        queue.AddMessage(new CloudQueueMessage(message));
                                //        log.Info($"Message added :-)");

                                values.Add("message" + i, m);

                                log.Info($"Notification {i} : {m}");
                            }

                            //stringcontent = new FormUrlEncodedContent(values);

                            apiresponse = await _client.PostAsync(_apiAddress, stringcontent);

                            var responseString = await apiresponse.Content.ReadAsStringAsync();

                            log.Info($"Got response: " + responseString);
                        }

                        // we have the response, now we let another flow know about it - through a call to the API!
                        var    message = JsonConvert.SerializeObject(notification);
                        string link    = tenantUrl + targetList.DefaultViewUrl;
                        var    obj     = new Dictionary <string, string>();
                        obj.Add("message", "New item on a list: " + targetList.Title);
                        obj.Add("link", link);

                        var serializer = new JavaScriptSerializer();
                        var json       = serializer.Serialize(obj);
                        stringcontent = new StringContent(json, Encoding.UTF8, "application/json");

                        //stringcontent = new FormUrlEncodedContent(obj);

                        log.Info($"Now pushing this: " + stringcontent);
                        apiresponse = await _client.PostAsync(_notificationFlowAddress, stringcontent);

                        log.Info($"Pushed to Flow! Got this back: " + apiresponse);

                        // if we get here we assume the request was well received
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }

            log.Info($"Got nothing! Logging bad request.");
            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            // You'll need this to add the local.settings.json file for local execution
            ExecutionContext context,
            ILogger log)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         // This gives you access to your application settings in your local development environment
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         // This is what actually gets you the application settings in Azure
                         .AddEnvironmentVariables()
                         .Build();

            log.LogInformation("C# HTTP trigger function processed a request.");

            string KeyVault_Name = config["KeyVault_Name"];
            string Cert_Name     = config["Cert_Name"];
            string appOnlyId     = config["AppOnlyID"];
            string tenant_URL    = config["Tenant_URL"];
            string siteURL       = "https://" + tenant_URL + ".sharepoint.com/teams/scw";

            // // parse query parameter
            string title           = req.Query["title"];
            string nameFR          = req.Query["spacenamefr"];
            string owner1          = req.Query["owner1"];
            string owner2          = req.Query["owner2"];
            string owner3          = req.Query["owner3"];
            string description     = req.Query["description"];
            string template        = req.Query["template"];
            string descriptionFr   = req.Query["descriptionFr"];
            string business        = req.Query["business"];
            string requester_name  = req.Query["requester_name"];
            string requester_email = req.Query["requester_email"];

            // // Get request body
            //dynamic data = await req.Content.ReadAsAsync<object>();
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // // Set name to query string or body data
            title           = title ?? data?.name.title;
            nameFR          = nameFR ?? data?.name.nameFR;
            owner1          = owner1 ?? data?.name.owner1;
            owner2          = owner2 ?? data?.name.owner2;
            owner3          = owner3 ?? data?.name.owner3;
            description     = description ?? data?.name.description;
            template        = template ?? data?.name.template;
            descriptionFr   = descriptionFr ?? data?.name.descriptionFr;
            business        = business ?? data?.name.business;
            requester_name  = requester_name ?? data?.name.requester_name;
            requester_email = requester_email ?? data?.name.requester_email;

            log.LogInformation("get info" + title);
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteURL, appOnlyId, tenant_URL + ".onmicrosoft.com", KeyVaultAccess.GetKeyVaultCertificate(KeyVault_Name, Cert_Name)))
            {
                cc.Load(cc.Web, p => p.Title);
                cc.Load(cc.Web, p => p.Description);

                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                Console.WriteLine(cc.Web.Description);

                log.LogInformation("get context");

                Web  web  = cc.Web;
                List list = cc.Web.Lists.GetByTitle("Space Requests");
                log.LogInformation("get list");

                ListItemCreationInformation oListItemCreationInformation = new ListItemCreationInformation();
                ListItem oItem = list.AddItem(oListItemCreationInformation);

                User userTest  = web.EnsureUser(owner1);
                User userTest2 = web.EnsureUser(owner2);


                cc.Load(userTest);
                cc.ExecuteQuery();
                log.LogInformation("get user");
                owner1 = userTest.Id.ToString() + ";#" + userTest.LoginName.ToString();
                cc.Load(userTest2);
                cc.ExecuteQuery();
                owner2 = userTest2.Id.ToString() + ";#" + userTest2.LoginName.ToString();
                if (owner3 != "")
                {
                    User userTest3 = web.EnsureUser(owner3);
                    cc.Load(userTest3);
                    cc.ExecuteQuery();
                    owner3 = userTest3.Id.ToString() + ";#" + userTest3.LoginName.ToString();
                }

                oItem["Space_x0020_Name"]          = title;
                oItem["Space_x0020_Name_x0020_FR"] = nameFR;
                oItem["Owner1"] = owner1 + ";#" + owner2 + ";#" + owner3;
                oItem["Space_x0020_Description_x0020__x"]  = description;
                oItem["Template_x0020_Title"]              = template;
                oItem["Space_x0020_Description_x0020__x0"] = descriptionFr;
                oItem["Team_x0020_Purpose_x0020_and_x00"]  = business;
                oItem["Business_x0020_Justification"]      = business;
                oItem["Requester_x0020_Name"]              = requester_name;
                oItem["Requester_x0020_email"]             = requester_email;
                oItem["_Status"] = "Submitted";
                oItem.Update();
                cc.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = string.Format(@"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Space_x0020_Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                    </Query>
                    <ViewFields>
                        <FieldRef Name='ID'/>
                        <FieldRef Name='Space_x0020_Name'/>
                    </ViewFields>
                    <RowLimit>1</RowLimit>
                </View>", title);

                ListItemCollection collListItemID = list.GetItems(camlQuery);
                cc.Load(collListItemID);
                cc.ExecuteQuery();

                int requestID = 0;

                foreach (ListItem oListItem in collListItemID)
                {
                    log.LogInformation(oListItem["Space_x0020_Name"].ToString());
                    requestID = oListItem.Id;
                }
                ListItem collListItem = list.GetItemById(requestID);
                // changes some fields
                collListItem["SharePoint_x0020_Site_x0020_URL"] = "https://" + tenant_URL + ".sharepoint.com/teams/1000" + requestID;
                collListItem.Update();
                // executes the update of the list item on SharePoint
                cc.ExecuteQuery();

                string responseMessage = "Create item successfully ";

                return(new OkObjectResult(responseMessage));
            }
        }