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();
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast<JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F3851068";

            if (!string.IsNullOrEmpty(typedDefinition.Standalone))
                item["DisplayTemplateJSTemplateType"] = typedDefinition.Standalone;

            if (!string.IsNullOrEmpty(typedDefinition.TargetControlType))
                item["DisplayTemplateJSTargetControlType"] = typedDefinition.TargetControlType;

            if (!string.IsNullOrEmpty(typedDefinition.TargetListTemplateId))
                item["DisplayTemplateJSTargetListTemplate"] = typedDefinition.TargetListTemplateId;

            if (!string.IsNullOrEmpty(typedDefinition.TargetScope))
                item["DisplayTemplateJSTargetScope"] = typedDefinition.TargetScope;

            if (!string.IsNullOrEmpty(typedDefinition.IconUrl))
            {
                var iconValue = new FieldUrlValue { Url = typedDefinition.IconUrl };

                if (!string.IsNullOrEmpty(typedDefinition.IconDescription))
                    iconValue.Description = typedDefinition.IconDescription;

                item["DisplayTemplateJSIconUrl"] = iconValue;
            }
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast<FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F38510660400F643FF79F6BD764F8A469B6F153396EE";


            if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileURL))
            {
                var crawlerXSLFileValue = new FieldUrlValue { Url = typedDefinition.CrawlerXSLFileURL };

                if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileDescription))
                    crawlerXSLFileValue.Description = typedDefinition.CrawlerXSLFileDescription;

                item["CrawlerXSLFile"] = crawlerXSLFileValue;
            }

            if (!string.IsNullOrEmpty(typedDefinition.CompatibleManagedProperties))
                item["CompatibleManagedProperties"] = typedDefinition.CompatibleManagedProperties;

            if (typedDefinition.CompatibleSearchDataTypes.Count > 0)
            {
                item["CompatibleSearchDataTypes"] = typedDefinition.CompatibleSearchDataTypes.ToArray();
            }
        }
Ejemplo n.º 4
0
        public static School GetSchoolFromItem(ClientContext ctx, int ItemId)
        {
            List     list = ctx.Web.GetListByTitle("Schools");
            ListItem item = list.GetItemById(ItemId);

            ctx.Load(item);
            ctx.ExecuteQuery();

            School school = new School();

            school.Title      = item["Title"].ToString();
            school.NrStudents = int.Parse(item["School_StudAmt"].ToString());
            school.Address    = "";
            if (item["School_Address"] != null)
            {
                school.Address = item["School_Address"].ToString();
            }
            school.PicDescription = "";
            school.PicUrl         = "";
            if (item["School_Picture"] != null)
            {
                FieldUrlValue urlval = item["School_Picture"] as FieldUrlValue;
                school.PicDescription = urlval.Description;
                school.PicUrl         = urlval.Url;
            }

            school.students = StudentsFromSchoolId(ctx, ItemId);

            return(school);
        }
Ejemplo n.º 5
0
        private static void FixUrlForItem(string url, int id)
        {
            FieldUrlValue furl = new FieldUrlValue();

            furl.Description = "Open Quot.";
            furl.Url         = url;

            using (var cc2 = new ClientContext(adminUrl))
            {
                cc2.Credentials = new SharePointOnlineCredentials(userName, password);
                cc2.Load(cc2.Web, w => w.Webs);
                cc2.Load(cc2.Web, w => w.Lists);
                cc2.ExecuteQuery();
                var _web = cc2.Web;

                var quotList2 = _web.Lists.First(x => x.Title == "Quotation Log");
                cc2.Load(quotList2);
                cc2.ExecuteQuery();

                var item2 = quotList2.GetItemById(id);

                item2["Quote_x0020_Link"] = furl;
                item2.Update();
                cc2.ExecuteQuery();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Adds a new entry to the site directory list
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="siteDirectoryProvisioningPage">Path to a page used as url when the site collection is not yet provisioned</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <param name="title">Title of the site collection</param>
        /// <param name="siteUrl">Url of the site collection</param>
        /// <param name="template">Template used to provision this site collection</param>
        /// <param name="requestor">Person that requested the provisioning</param>
        /// <param name="owner">Person that will be the primary owner of the site collection</param>
        /// <param name="backupOwners">Person(s) that will be the backup owner(s) of the site collection</param>
        /// <param name="permissions">Chosen permission model</param>
        public void AddSiteDirectoryEntry(ClientContext cc, Web web, string siteDirectoryHost, string siteDirectoryProvisioningPage, string listName, string title, string siteUrl, string template, string[] ownerLogins)
        {
            List listToInsertTo = web.Lists.GetByTitle(listName);
            ListItemCreationInformation lici = new ListItemCreationInformation();
            ListItem listItem = listToInsertTo.AddItem(lici);
            listItem["Title"] = title;

            //URL = hyperlink field
            FieldUrlValue url = new FieldUrlValue();
            url.Description = title;
            url.Url = String.Format("{0}/{1}", siteDirectoryHost, siteDirectoryProvisioningPage);
            listItem["SiteTitle"] = url;
            // store url also as text field to facilitate easy CAML querying afterwards
            listItem["UrlText"] = siteUrl;

            // Owners = Person field with multiple values
            FieldUserValue[] users = new FieldUserValue[ownerLogins.Length];

            int i = 0;
            foreach (string ownerLogin in ownerLogins)
            {
                FieldUserValue ownersField = FieldUserValue.FromUser(ownerLogin);
                users[i] = ownersField;
                i++;
            }
            listItem["Owners"] = users;
            listItem["Template"] = template;
            listItem["Status"] = "Requested";
            listItem.Update();
            cc.ExecuteQuery();
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast <FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F38510660400F643FF79F6BD764F8A469B6F153396EE";


            if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileURL))
            {
                var crawlerXSLFileValue = new FieldUrlValue {
                    Url = typedDefinition.CrawlerXSLFileURL
                };

                if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileDescription))
                {
                    crawlerXSLFileValue.Description = typedDefinition.CrawlerXSLFileDescription;
                }

                item["CrawlerXSLFile"] = crawlerXSLFileValue;
            }

            if (!string.IsNullOrEmpty(typedDefinition.CompatibleManagedProperties))
            {
                item["CompatibleManagedProperties"] = typedDefinition.CompatibleManagedProperties;
            }

            if (typedDefinition.CompatibleSearchDataTypes.Count > 0)
            {
                item["CompatibleSearchDataTypes"] = typedDefinition.CompatibleSearchDataTypes.ToArray();
            }
        }
Ejemplo n.º 8
0
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast <ItemControlTemplateDefinitionBase>("model", value => value.RequireNotNull());

            if (typedDefinition.TargetControlTypes.Count > 0)
            {
                item["TargetControlType"] = typedDefinition.TargetControlTypes.ToArray();
            }

            if (!string.IsNullOrEmpty(typedDefinition.PreviewURL))
            {
                var htmlPreviewValue = new FieldUrlValue {
                    Url = typedDefinition.PreviewURL
                };

                if (!string.IsNullOrEmpty(typedDefinition.PreviewDescription))
                {
                    htmlPreviewValue.Description = typedDefinition.PreviewDescription;
                }

                item["HtmlDesignPreviewUrl"] = htmlPreviewValue;
            }
        }
Ejemplo n.º 9
0
        private static void LoopThroughListItems(ClientContext ctx)
        {
            ListItemCollection list = ctx.Web.Lists.GetByTitle("Employee").GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(list);
            ctx.ExecuteQuery();

            int i = 1;

            foreach (var item in list)
            {
                FieldUserValue Username  = item["TIM_Employee"] as FieldUserValue;
                FieldUrlValue  picUrl    = item["TIM_Picture"] as FieldUrlValue;
                FieldUrlValue  LinkinUrl = item["TIM_Linkedin"] as FieldUrlValue;
                //FieldLookupValue empType = item[] as FieldLookupValue;
                //FieldLookupValue managerType = item[] as FieldLookupValue;

                Console.WriteLine("Person " + i++);
                Console.WriteLine();
                Console.WriteLine(item["Title"]);
                Console.WriteLine(Username.Email);
                Console.WriteLine(picUrl.Url);
                Console.WriteLine("descrip " + picUrl.Description);
                Console.WriteLine(LinkinUrl.Url);
                Console.WriteLine("descrip " + LinkinUrl.Description);
                Console.WriteLine(item["TIM_Age"]);
                Console.WriteLine(item["TIM_Education"]);
            }
        }
        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();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Adds a new entry to the site directory list
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="siteDirectoryProvisioningPage">Path to a page used as url when the site collection is not yet provisioned</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <param name="title">Title of the site collection</param>
        /// <param name="siteUrl">Url of the site collection</param>
        /// <param name="template">Template used to provision this site collection</param>
        /// <param name="requestor">Person that requested the provisioning</param>
        /// <param name="owner">Person that will be the primary owner of the site collection</param>
        /// <param name="backupOwners">Person(s) that will be the backup owner(s) of the site collection</param>
        /// <param name="permissions">Chosen permission model</param>
        public void AddSiteDirectoryEntry(ClientContext cc, Web web, string siteDirectoryHost, string siteDirectoryProvisioningPage, string listName, string title, string siteUrl, string template, string[] ownerLogins)
        {
            List listToInsertTo = web.Lists.GetByTitle(listName);
            ListItemCreationInformation lici = new ListItemCreationInformation();
            ListItem listItem = listToInsertTo.AddItem(lici);

            listItem["Title"] = title;

            //URL = hyperlink field
            FieldUrlValue url = new FieldUrlValue();

            url.Description       = title;
            url.Url               = String.Format("{0}/{1}", siteDirectoryHost, siteDirectoryProvisioningPage);
            listItem["SiteTitle"] = url;
            // store url also as text field to facilitate easy CAML querying afterwards
            listItem["UrlText"] = siteUrl;

            // Owners = Person field with multiple values
            FieldUserValue[] users = new FieldUserValue[ownerLogins.Length];

            int i = 0;

            foreach (string ownerLogin in ownerLogins)
            {
                FieldUserValue ownersField = FieldUserValue.FromUser(ownerLogin);
                users[i] = ownersField;
                i++;
            }
            listItem["Owners"]   = users;
            listItem["Template"] = template;
            listItem["Status"]   = "Requested";
            listItem.Update();
            cc.ExecuteQuery();
        }
        public IEnumerable <Profile> GetProfile(string email)
        {
            var profiles = new List <Profile>();

            using (var clientContext = new ClientContext(ConfigurationManager.AppSettings.Get("mClubSiteUrl")))
            {
                var passWord = new SecureString();
                foreach (char c in ConfigurationManager.AppSettings.Get("password").ToCharArray())
                {
                    passWord.AppendChar(c);
                }

                clientContext.Credentials = new SharePointOnlineCredentials(ConfigurationManager.AppSettings.Get("userName"), passWord);
                var contributionTypesList = clientContext.Web.Lists.GetByTitle("Employee Profile");

                var userQuery = new CamlQuery()
                {
                    ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where></Query></View>", "Title", email)
                };

                var userItems = contributionTypesList.GetItems(userQuery);

                // Retrieve all items in the ListItemCollection from List.GetItems(Query).
                clientContext.Load(userItems);
                clientContext.ExecuteQuery();

                foreach (var item in userItems)
                {
                    var profile = new Profile();
                    profile.About            = Convert.ToString(item["About"]);
                    profile.Contact          = Convert.ToString(item["Contact"]);
                    profile.Designation      = Convert.ToString(item["Designation"]);
                    profile.DisplayName      = Convert.ToString(item["Login_x0020_Name"]);
                    profile.DownloadedTheApp = Convert.ToBoolean(item["Downloaded_x0020_App"]);
                    profile.Email            = Convert.ToString(item["Title"]);
                    var profileUrl = new FieldUrlValue();
                    if (profileUrl != null)
                    {
                        profileUrl    = item["ProfileUrl"] as FieldUrlValue;
                        profile.Image = profileUrl.Url;
                    }
                    var level = item["Level"] as FieldLookupValue;

                    if (level != null)
                    {
                        profile.Level = level.LookupValue;
                    }

                    profile.Location = Convert.ToString(item["Location"]);
                    profile.mCoins   = Convert.ToString(item["mCoins_x0020_In_x0020_Hand"]);
                    profile.Team     = Convert.ToString(item["Team"]);
                    profile.WebLogin = Convert.ToBoolean(item["Web_x0020_Login"]);

                    profiles.Add(profile);
                }
            }

            return(profiles.ToList());
        }
        public HttpResponseMessage UpdateEmployee([FromBody] EmployeeUpdateDto employeeUpdateDto)
        {
            try
            {
                // check the valdation of the date
                if (employeeUpdateDto.EmployeeBirthdate >= DateTime.Today)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Birthday less than today"));
                }
                // check the model state
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                using (var ctx = new ClientContext(webUrl))
                {
                    //get user from token
                    var claims = (ClaimsIdentity)ClaimsPrincipal.Current.Identity;
                    //check user permission on the Item
                    ClientResult <BasePermissions> permissions = ctx.Web.Lists.GetByTitle(listTitle).GetItemById(employeeUpdateDto.ID).GetUserEffectivePermissions(claims.Name);
                    ctx.ExecuteQuery();
                    Boolean hasPermission = permissions.Value.Has(PermissionKind.AddListItems);
                    if (!hasPermission)
                    {
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized, "you're not allow to update employee"));
                    }

                    //Get Item
                    ListItem oListItem = ctx.Web.Lists.GetByTitle(listTitle).GetItemById(employeeUpdateDto.ID);

                    foreach (var property in typeof(EmployeeUpdateDto).GetProperties())
                    {
                        if (property.Name != "ID" & property.Name != "ProfileURL" & property.Name != "Description" & property.GetValue(employeeUpdateDto) != null)
                        {
                            oListItem[property.Name] = property.GetValue(employeeUpdateDto);
                        }
                    }
                    if (!String.IsNullOrWhiteSpace(employeeUpdateDto.ProfileURL))
                    {
                        FieldUrlValue fieldUrl = new FieldUrlValue();
                        fieldUrl.Url = employeeUpdateDto.ProfileURL;
                        if (!String.IsNullOrWhiteSpace(employeeUpdateDto.Description))
                        {
                            fieldUrl.Description = employeeUpdateDto.Description;
                        }
                        oListItem["ProfileURL"] = fieldUrl;
                    }
                    oListItem.Update();
                    ctx.ExecuteQuery();
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Ejemplo n.º 14
0
        public Employee GetEmployeeInfo(ListItem item)
        {
            FieldUrlValue fileUrl = null;
            Picture       picture = null;

            if (item[dictionarys[Constant.Picture]] != null)
            {
                fileUrl = item[dictionarys[Constant.Picture]] as FieldUrlValue;
            }
            if (fileUrl != null)
            {
                if (!Directory.Exists(Constant.PictureSaveDirectory))
                {
                    Directory.CreateDirectory(Constant.PictureSaveDirectory);
                }
                picture = WebDownload.GetPictureContent(fileUrl.Url, Constant.PictureSaveDirectory + "/" + fileUrl.Url.Substring(fileUrl.Url.LastIndexOf('/') + 1));
            }


            var employee = new Employee()
            {
                NO                     = item[dictionarys[Constant.NO]] == null ? "" : item[dictionarys[Constant.NO]].ToString(),
                MediumPicture          = fileUrl == null ? "" : picture.Content,
                MediumPicturePath      = fileUrl == null ? "" : fileUrl.Url,
                ID                     = item[dictionarys[Constant.ID]] == null ? "" : item[dictionarys[Constant.ID]].ToString(),
                Name                   = item[dictionarys[Constant.Name]] == null ? "" : item[dictionarys[Constant.Name]].ToString(),
                Sex                    = item[dictionarys[Constant.Sex]] == null ? "" : item[dictionarys[Constant.Sex]].ToString(),
                EnglishName            = item[dictionarys[Constant.EnglishName]] == null ? "" : item[dictionarys[Constant.EnglishName]].ToString(),
                LoginDomainName        = item[dictionarys[Constant.LoginDomainName]] == null ? "" : item[dictionarys[Constant.LoginDomainName]].ToString(),
                SkypeId                = item[dictionarys[Constant.SkypeID]] == null ? "" : item[dictionarys[Constant.SkypeID]].ToString(),
                LyncId                 = item[dictionarys[Constant.LyncID]] == null ? "" : item[dictionarys[Constant.LyncID]].ToString(),
                Office                 = item[dictionarys[Constant.Office]] == null ? "" : item[dictionarys[Constant.Office]].ToString(),
                Department             = item[dictionarys[Constant.Department]] == null ? "" : item[dictionarys[Constant.Department]].ToString(),
                Band                   = item[dictionarys[Constant.Band]] == null ? "" : item[dictionarys[Constant.Band]].ToString(),
                Province               = item[dictionarys[Constant.Province]] == null ? "" : item[dictionarys[Constant.Province]].ToString(),
                PostCode               = item[dictionarys[Constant.PostCode]] == null ? "" : item[dictionarys[Constant.PostCode]].ToString(),
                EducationBackgroud     = item[dictionarys[Constant.EducationBackgroud]] == null ? "" : item[dictionarys[Constant.EducationBackgroud]].ToString(),
                Position               = item[dictionarys[Constant.Position]] == null ? "" : item[dictionarys[Constant.Position]].ToString(),
                DirectLeader           = item[dictionarys[Constant.DirectLeader]] == null ? "" : item[dictionarys[Constant.DirectLeader]].ToString(),
                ArrivalDate            = item[dictionarys[Constant.ArrivalDate]] == null ? "" : item[dictionarys[Constant.ArrivalDate]].ToString(),
                LaborContractStartDate = item[dictionarys[Constant.LaborContractStartDate]] == null ? "" : item[dictionarys[Constant.LaborContractStartDate]].ToString(),
                ConversionDate         = item[dictionarys[Constant.ConversionDate]] == null ? "" : item[dictionarys[Constant.ConversionDate]].ToString(),
                LaborContractEndDate   = item[dictionarys[Constant.LaborContractEndDate]] == null ? "" : item[dictionarys[Constant.LaborContractEndDate]].ToString(),
                LaborContractUtilDate  = item[dictionarys[Constant.LaborContractUtilDate]] == null ? "" : item[dictionarys[Constant.LaborContractUtilDate]].ToString(),
                Birthday               = item[dictionarys[Constant.Birthday]] == null ? "" : item[dictionarys[Constant.Birthday]].ToString(),
                IsIntern               = item[dictionarys[Constant.IsIntern]] == null ? "" : item[dictionarys[Constant.IsIntern]].ToString(),
                GraduateSchool         = item[dictionarys[Constant.GraduateSchool]] == null ? "" : item[dictionarys[Constant.GraduateSchool]].ToString(),
                GraduateTime           = item[dictionarys[Constant.GraduateTime]] == null ? "" : item[dictionarys[Constant.GraduateTime]].ToString(),
                HouseAddress           = item[dictionarys[Constant.HouseAddress]] == null ? "" : item[dictionarys[Constant.HouseAddress]].ToString(),
                Mobile                 = item[dictionarys[Constant.Mobile]] == null ? "" : item[dictionarys[Constant.Mobile]].ToString(),
                IsLeave                = item[dictionarys[Constant.IsLeave]] == null ? "" : item[dictionarys[Constant.IsLeave]].ToString(),
                LeaveDate              = item[dictionarys[Constant.LeaveDate]] == null ? "" : item[dictionarys[Constant.LeaveDate]].ToString(),
                EditInHRIS             = item[dictionarys[Constant.EditInHRIS]] == null ? "" : item[dictionarys[Constant.EditInHRIS]].ToString(),
                IDNumber               = item[dictionarys[Constant.IDNumber]] == null ? "" : item[dictionarys[Constant.IDNumber]].ToString()
            };

            return(employee);
        }
Ejemplo n.º 15
0
        public static void SetUrlValue(this ListItem item, string internalName, string url)
        {
            var field = new FieldUrlValue()
            {
                Url = url
            };

            item[internalName] = field;
        }
Ejemplo n.º 16
0
 public static string ToFileUrlStr(this FieldUrlValue url, string file_name)
 {
     if (url == null)
     {
         return("http://netping.ru/Pub/Files/" + file_name);
     }
     else
     {
         return(url.Url);
     }
 }
        private void SetUrlFieldValue(ListItem newItem, string fieldName, string url, string description)
        {
            if (!string.IsNullOrEmpty(url))
            {
                var urlFieldValue = new FieldUrlValue { Url = url };

                if (!string.IsNullOrEmpty(description))
                    urlFieldValue.Description = description;

                newItem[fieldName] = urlFieldValue;
            }
        }
Ejemplo n.º 18
0
        private static bool SetFieldValue(ref ListItem item, string fieldName, FieldUrlValue fieldValue, bool overwrite = true)
        {
            var hasChanged = false;
            var itemValue  = item[fieldName] as FieldUrlValue;

            if ((itemValue == null && fieldValue != null) ||
                (overwrite && (!itemValue.Url.Equals(fieldValue.Url) || !itemValue.Description.Equals(fieldValue.Description))))
            {
                item[fieldName] = fieldValue;
                hasChanged      = true;
            }
            return(hasChanged);
        }
        public void GetAllDeactivatingSitesAndOperate(ClientContext clientContext, string spOnlineUserLogin, string spOnlineUserPassword, string adminTenantUrl)
        {
            try
            {
                ListProcessor sdlo = new ListProcessor(clientContext, cfg, logger);
                foreach (ListItem item in sdlo.GetAllDeactivatingSites())
                {
                    //connect to service and deactivate
                    PiwikPROServiceOperations pso = new PiwikPROServiceOperations(cfg.PiwikClientID, cfg.PiwikClientSecret, cfg.PiwikServiceUrl, cfg.PiwikOldApiToken, logger);
                    string        idSite          = Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]);
                    FieldUrlValue valueUrl        = (FieldUrlValue)(item[ConfigValues.PiwikPro_SiteDirectory_Column_Url]);
                    //idSite = pso.RemoveSiteFromPiwik(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]));
                    pso.ChangeNameSiteInPiwik("Inactive - " + Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_Title]), idSite);
                    if (idSite.Contains("Error: "))
                    {
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_Status]   = ConfigValues.PiwikPro_SiteDirectory_Column_Status_Error;
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_ErrorLog] = idSite;
                    }
                    else
                    {
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_Status] = ConfigValues.PiwikPro_SiteDirectory_Column_Status_NoActive;
                    }

                    item.Update();
                    clientContext.ExecuteQueryRetry();


                    if (!string.IsNullOrEmpty(spOnlineUserLogin))
                    {
                        SetEnablePropertyBagChange(adminTenantUrl, valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword, logger);

                        OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager();
                        using (ClientContext contextToPropBag = authMan.GetAppOnlyAuthenticatedContext(valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword))
                        {
                            CreateOrUpdateValueInPropertyBag("false", contextToPropBag, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                    else
                    {
                        using (ClientContext contextToPropBag = new ClientContext(valueUrl.Url))
                        {
                            CreateOrUpdateValueInPropertyBag("false", contextToPropBag, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                }
            }
            catch (Exception expcc)
            {
                logger.WriteLog(Category.Unexpected, "Piwik GetAllNewSitesAndOperateOnFinish", expcc.Message);
            }
        }
        public HttpResponseMessage AddEmployee([FromBody] EmployeeCreationDto employeeCreationDto)
        {
            try
            {
                // check the valdation of the date
                if (employeeCreationDto.EmployeeBirthdate >= DateTime.Today)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Birthday less than today"));
                }
                // check the model state
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Values));
                }

                using (var ctx = new ClientContext(webUrl))
                {
                    //check Permissions
                    //ClientResult<BasePermissions> permissions = ctx.Web.Lists.GetByTitle(listTitle).GetUserEffectivePermissions(userName);
                    //ctx.ExecuteQuery();
                    //Boolean hasPermission = permissions.Value.Has(PermissionKind.AddListItems);
                    //if (!hasPermission)
                    //    return Request.CreateResponse(HttpStatusCode.Unauthorized, "you're not allow to add employee");

                    //create item list
                    List oList = ctx.Web.Lists.GetByTitle(listTitle);

                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    foreach (var property in typeof(EmployeeCreationDto).GetProperties())
                    {
                        if (property.Name != "ProfileURL" & property.Name != "Description")
                        {
                            oListItem[property.Name] = property.GetValue(employeeCreationDto);
                        }
                    }
                    FieldUrlValue fieldUrl = new FieldUrlValue();
                    fieldUrl.Url            = employeeCreationDto.ProfileURL;
                    fieldUrl.Description    = employeeCreationDto.Description;
                    oListItem["ProfileURL"] = fieldUrl;
                    oListItem.Update();
                    ctx.ExecuteQuery();
                    return(Request.CreateResponse(HttpStatusCode.Created));
                }
            }
            catch (Exception ex)
            {
                // return the error back
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Ejemplo n.º 21
0
        static void Main()
        {
            //Added for O365
            SecureString password = GetPasswordFromConsoleInput();
            clientContext.Credentials = new SharePointOnlineCredentials(username, password);

              clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(site.Lists);
              clientContext.ExecuteQuery();

              listProducts = site.Lists.GetByTitle("Products");
              clientContext.Load(listProducts);

              listProductImages = site.Lists.GetByTitle("Product Images");
              //clientContext.Load(listProductImages, lib => lib.RootFolder.ServerRelativeUrl);
              clientContext.Load(listProductImages, lib => lib.RootFolder.Name);

              ListItemCollection products = listProducts.GetItems(new CamlQuery());
              clientContext.Load(products);
              clientContext.ExecuteQuery();

              Console.WriteLine();
              Console.WriteLine("Updating product image URL for all products");

              foreach (var product in products) {
            string title = product["Title"].ToString();
            string productCode = product["ProductCode"].ToString();
            //string productImageUrl = site.Url + listProductImages.RootFolder.ServerRelativeUrl + "/" + productCode + ".jpg";
            string productImageUrl = site.Url + "/" + listProductImages.RootFolder.Name + "/" + productCode + ".jpg";
            //
            Debug.WriteLine("Updating: " + productImageUrl);
            FieldUrlValue urlValue = new FieldUrlValue();

            urlValue.Url = productImageUrl;
            urlValue.Description = title;
            product["ProductImageUrl"] = urlValue;
            product.Update();
            Console.Write(".");
            clientContext.ExecuteQuery();
              }

              Console.WriteLine();
              Console.WriteLine();
              Console.WriteLine("Update complete. Press the ENTER key to continue.");
              Console.WriteLine();
              Console.WriteLine();
              Console.ReadLine();
        }
Ejemplo n.º 22
0
        private async Task Update_List(string candidateID, string dob)
        {
            try
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem newItem = CandList.AddItem(itemCreateInfo);
                lblStatus.Text = "Uploading Results";
                progressBar1.PerformStep();
                FieldLookupValue lval = await GetLookupValue(ctx, jobName, "Job", "JobFullName", "Text", false);

                newItem["CandidateID"] = CandID;
                newItem["First_name"]  = candidate_name.Split('_')[0];
                newItem["Last_name"]   = candidate_name.Split('_')[1];
                newItem["JobSite"]     = lval;
                newItem["DOB"]         = dob;
                newItem["Job"]         = jobName;
                // double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count);
                // string hireStatus = "";
                newItem["Hire_Status"] = hireStatus;
                //if (percent >= 0.7 && percent < 1.0)
                //{
                //    newItem["Hire_Status"] = hireStatus;
                //   // hireStatus = "Conditional Hire";
                //}
                //else
                //{
                //    newItem["Hire_Status"] = "Hired";
                //    hireStatus = "Hired";
                //}
                string        tempFolderurl = docFolder.ServerRelativeUrl;
                FieldUrlValue _url          = new FieldUrlValue();
                _url.Url                  = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));;
                _url.Description          = "View Tests";
                newItem["FolderUrl"]      = _url;
                newItem["Remaining_Test"] = remaining_test;
                newItem["Category"]       = pos_category;
                //newItem["FolderUrl"] = folder.ServerRelativeUrl;
                newItem.Update();
                ctx.Load(CandList);
                ctx.ExecuteQuery();

                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
        public void GetLinkDescriptionFromValueTest()
        {
            var expected = "Test Value";

            var item = CreateFakeItem();

            item["MyLink"] = new FieldUrlValue
            {
                Description = expected
            };

            var wrapper = new ListItemWrapper(item);
            var actual  = wrapper.GetLinkDescription("MyLink");

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 24
0
        public void GetLinkUrlFromValueTest()
        {
            var expected = "https://www.microsoft.com";

            var item = CreateFakeItem();

            item["MyLink"] = new FieldUrlValue
            {
                Url = expected
            };

            var wrapper = new ListItemWrapper(item);
            var actual  = wrapper.GetLinkUrl("MyLink");

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 25
0
        private void SetUrlFieldValue(ListItem newItem, string fieldName, string url, string description)
        {
            if (!string.IsNullOrEmpty(url))
            {
                var urlFieldValue = new FieldUrlValue {
                    Url = url
                };

                if (!string.IsNullOrEmpty(description))
                {
                    urlFieldValue.Description = description;
                }

                newItem[fieldName] = urlFieldValue;
            }
        }
        /// <summary>
        /// Url字段
        /// </summary>
        /// <param name="url"></param>
        /// <param name="description"></param>
        /// <param name="msg">返回成功或失败(即值在源列表中是否存在) 空则成功,不为空则失败</param>
        /// <returns></returns>
        public FieldUrlValue UrlValue(string url, string description, out string msg)
        {
            msg = "";
            FieldUrlValue uv = new FieldUrlValue();

            try
            {
                uv.Url         = url;
                uv.Description = description;
            }
            catch (Exception)
            {
                msg = "Url格式不正确";
            }
            return(uv);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Updates the provisioning status of an entry in the site directory list
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <param name="siteUrl">Url if the site directory entry</param>
        /// <param name="status">Status to use</param>
        /// <param name="ex">Exception caught during the provisioning process</param>
        public void UpdateSiteDirectoryStatus(ClientContext cc, Web web, string siteDirectoryHost, string listName, string siteUrl, string newSiteUrl, string status, Exception ex)
        {
            List listToInsertQuery = web.Lists.GetByTitle(listName);

            CamlQuery query = new CamlQuery();

            query.ViewXml = "<View>"
                            + "<Query>"
                            + String.Format("<Where><Eq><FieldRef Name='UrlText' /><Value Type='Text'>{0}</Value></Eq></Where>", siteUrl)
                            + "</Query>"
                            + "</View>";
            // execute the query
            ListItemCollection listItems = listToInsertQuery.GetItems(query);

            cc.Load(listItems);
            cc.ExecuteQuery();

            if (listItems.Count == 1)
            {
                listItems[0]["Status"] = status;

                if (status.Equals("Provisioning", StringComparison.InvariantCultureIgnoreCase))
                {
                    // update to the new siteUrl
                    listItems[0]["UrlText"]    = newSiteUrl;
                    listItems[0]["CreateYear"] = GetCreationYear(newSiteUrl);
                    listItems[0]["CreateSeq"]  = GetCreationSequence(newSiteUrl);
                }

                // Update the URL value now that the site status is available
                if (status.Equals("Available", StringComparison.InvariantCultureIgnoreCase))
                {
                    FieldUrlValue url = (FieldUrlValue)(listItems[0]["SiteTitle"]);
                    url.Url = siteUrl;
                    listItems[0]["SiteTitle"] = url;
                }

                if (ex != null)
                {
                    string error = string.Format("Error: {0}\r\nStacktrace: {1}", ex.Message, ex.StackTrace);
                    listItems[0]["Error"] = error;
                }

                listItems[0].Update();
                cc.ExecuteQuery();
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Encapsulates setting an item by internal name.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="internalName"></param>
        /// <param name="value"></param>
        protected void BaseSet(ListItem item, string internalName, object value)
        {
            if (_fields.ContainsKey(internalName))
            {
                var field = _fields[internalName.ToLowerInvariant()];

                if (field is FieldUrl && value is string)
                {
                    var urlValue = new FieldUrlValue()
                    {
                        Url = value.ToString()
                    };
                    value = urlValue;
                }
            }
            item[internalName] = value;
        }
Ejemplo n.º 29
0
        private async Task Update_List(string candidateID)
        {
            try
            {
                Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(quizListName);
                ctx.Load(list);
                //CamlQuery camlQuery = new CamlQuery();

                //camlQuery.ViewXml= "<View><Query><Where><Geq><FieldRef Name='CandidateID'/>" +
                //"<Value Type='Text'>"+candidateID+"</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
                Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(CreateCandidateQuery(CandID, CandName.Split('_')[0]));
                ctx.Load(listitems);
                ctx.ExecuteQuery();
                FieldLookupValue lval = await GetLookupValue(ctx, jobName, "Job", "JobFullName", "Text", false);

                foreach (ListItem oListItem in listitems)
                {
                    //oListItem["JobSite"] = lval.LookupValue;
                    oListItem["JobSite"] = lval;
                    oListItem["Job"]     = jobName;
                    //double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count);
                    //if (percent >= 0.7 && percent < 1.0)
                    //    oListItem["Hire_Status"] = "Conditional Hire";
                    //else
                    //    oListItem["Hire_Status"] = "Hired";
                    oListItem["Hire_Status"] = hireStatus;
                    string        tempFolderurl = docFolder.ServerRelativeUrl;
                    FieldUrlValue _url          = new FieldUrlValue();
                    _url.Url                    = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));;
                    _url.Description            = "View Tests";
                    oListItem["FolderUrl"]      = _url;
                    oListItem["Remaining_Test"] = remaining_test;
                    oListItem["Category"]       = pos_category;
                    //newItem["FolderUrl"] = folder.ServerRelativeUrl;

                    oListItem.Update();
                    ctx.Load(oListItem);
                    ctx.ExecuteQuery();
                }
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedTemplateModel = definition.WithAssertAndCast<ControlDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F385106601";

            if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileURL))
            {
                var crawlerXSLFileValue = new FieldUrlValue { Url = typedTemplateModel.CrawlerXSLFileURL };

                if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileDescription))
                    crawlerXSLFileValue.Description = typedTemplateModel.CrawlerXSLFileDescription;

                item["CrawlerXSLFile"] = crawlerXSLFileValue;
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string filePath       = "";
            string login          = "******";
            string password       = "******";
            var    securepassword = new SecureString();

            foreach (char c in password)
            {
                securepassword.AppendChar(c);
            }

            string siteUrl = "https://verinontechnology.sharepoint.com/sites/AppPractice/";

            ClientContext context           = new ClientContext(siteUrl);
            var           onlineCredentials = new SharePointOnlineCredentials(login, securepassword);

            context.Credentials = onlineCredentials;
            Web web = context.Web;

            context.ExecuteQuery();

            File file = web.GetFileByServerRelativeUrl(filePath);

            file.CheckOut();
            context.Load(web);
            context.Load(file);
            context.ExecuteQuery();

            context.ExecuteQuery();
            //Microsoft.SharePoint.Client.List listmylist = clientContext.Web.Lists.GetByTitle("employee");
            //clientContext.Load(listmylist);
            //clientContext.ExecuteQuery();
            var pagesList = context.Web.Lists.GetByTitle("2_Documents and Pages");
            var pageItem  = pagesList.GetItemById(5);

            pageItem["PublishingPageLayout"] = new FieldUrlValue()
            {
                Url = "/sites/rworldmssite1/_catalogs/masterpage/Ricoh/OneSmallOneLargeOneSmallColumnLayout.aspx", Description = " "
            };
            pageItem.Update();
            context.ExecuteQuery();
        }
Ejemplo n.º 32
0
        internal static void CreateCustomer(this Customer customer, ClientContext ctx)
        {
            var      customers = ctx.Web.Lists.GetByTitle("Customer");
            ListItem li        = customers.AddItem(new ListItemCreationInformation());

            li["Title"]         = customer.Title;
            li["Address"]       = customer.Address;
            li["contactPerson"] = customer.ContactPerson;
            li["phoneOffice"]   = customer.OfficePhone;
            li["phoneMobile"]   = customer.Mobile;
            li["Email"]         = customer.Email;
            li["DispLogo"]      = new FieldUrlValue()
            {
                Description = customer.Title + " Logo", Url = customer.Logo
            };

            li.Update();
            ctx.ExecuteQuery();
        }
Ejemplo n.º 33
0
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast <JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F3851068";

            if (!string.IsNullOrEmpty(typedDefinition.Standalone))
            {
                item["DisplayTemplateJSTemplateType"] = typedDefinition.Standalone;
            }

            if (!string.IsNullOrEmpty(typedDefinition.TargetControlType))
            {
                item["DisplayTemplateJSTargetControlType"] = typedDefinition.TargetControlType;
            }

            if (!string.IsNullOrEmpty(typedDefinition.TargetListTemplateId))
            {
                item["DisplayTemplateJSTargetListTemplate"] = typedDefinition.TargetListTemplateId;
            }

            if (!string.IsNullOrEmpty(typedDefinition.TargetScope))
            {
                item["DisplayTemplateJSTargetScope"] = typedDefinition.TargetScope;
            }

            if (!string.IsNullOrEmpty(typedDefinition.IconUrl))
            {
                var iconValue = new FieldUrlValue {
                    Url = typedDefinition.IconUrl
                };

                if (!string.IsNullOrEmpty(typedDefinition.IconDescription))
                {
                    iconValue.Description = typedDefinition.IconDescription;
                }

                item["DisplayTemplateJSIconUrl"] = iconValue;
            }
        }
Ejemplo n.º 34
0
        static void Main()
        {
            clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(site.Lists);
              clientContext.ExecuteQuery();

              listProducts = site.Lists.GetByTitle("Products");
              clientContext.Load(listProducts);

              listProductImages = site.Lists.GetByTitle("Product Images");
              clientContext.Load(listProductImages, lib => lib.RootFolder.ServerRelativeUrl);

              ListItemCollection products = listProducts.GetItems(new CamlQuery());
              clientContext.Load(products);
              clientContext.ExecuteQuery();

              Console.WriteLine();
              Console.WriteLine("Updating product image URL for all products");

              foreach (var product in products) {
            string title = product["Title"].ToString();
            string productCode = product["ProductCode"].ToString();
            string productImageUrl = site.Url + listProductImages.RootFolder.ServerRelativeUrl + "/" + productCode + ".jpg";
            FieldUrlValue urlValue = new FieldUrlValue();

            urlValue.Url = productImageUrl;
            urlValue.Description = title;
            product["ProductImageUrl"] = urlValue;
            product.Update();
            Console.Write(".");
            clientContext.ExecuteQuery();
              }

              Console.WriteLine();
              Console.WriteLine();
              Console.WriteLine("Update complete. Press the ENTER ke to continue.");
              Console.WriteLine();
              Console.WriteLine();
              Console.ReadLine();
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast<ItemControlTemplateDefinitionBase>("model", value => value.RequireNotNull());

            if (typedDefinition.TargetControlTypes.Count > 0)
            {
                item["TargetControlType"] = typedDefinition.TargetControlTypes.ToArray();
            }

            if (!string.IsNullOrEmpty(typedDefinition.PreviewURL))
            {
                var htmlPreviewValue = new FieldUrlValue { Url = typedDefinition.PreviewURL };

                if (!string.IsNullOrEmpty(typedDefinition.PreviewDescription))
                    htmlPreviewValue.Description = typedDefinition.PreviewDescription;

                item["HtmlDesignPreviewUrl"] = htmlPreviewValue;
            }
        }
Ejemplo n.º 36
0
        public static void UpdateFirstCV(ClientContext ctx)
        {
            List list = ctx.Web.Lists.GetByTitle("CV's");

            ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery(1));

            ctx.Load(items);
            ctx.ExecuteQueryRetry();

            ListItem item = items[0];

            // setting a picture or link field
            Console.WriteLine(item["CV_Picture"]);
            Console.WriteLine(item["CV_Picture"].ToString());

            FieldUrlValue pictureValue = item["CV_Picture"] as FieldUrlValue;

            Console.WriteLine(pictureValue.Description);
            Console.WriteLine(pictureValue.Url);

            pictureValue.Url         = "https://s-media-cache-ak0.pinimg.com/originals/26/18/22/2618227f9e53768070739f89fb387fcf.gif";
            pictureValue.Description = "quack quack";
            item["CV_Picture"]       = pictureValue;

            // setting the person field
            Console.WriteLine(item["CV_person"]);
            FieldUserValue userVal = item["CV_person"] as FieldUserValue;

            Console.WriteLine(userVal.Email);
            Console.WriteLine(userVal.LookupValue);
            Console.WriteLine(userVal.LookupId);

            User user = ctx.Web.EnsureUser("*****@*****.**");

            ctx.Load(user);
            ctx.ExecuteQueryRetry();
            item["CV_person"] = user.Id;
            item.Update();
            ctx.ExecuteQueryRetry();
        }
        public static void SetFileUrlFee(string url, string user, string password, string listName, Guid guid, string serverFilePath)
        {
            string[] parts = user.Split('\\');

            using (ClientContext clientContext = new ClientContext(url))
            {
                clientContext.Credentials = new NetworkCredential(parts[1], password, parts[0]);

                Web site = clientContext.Web;

                List list = site.Lists.GetByTitle(listName);

                CamlQuery query = new CamlQuery()
                {
                    ViewXml = "<View Scope=\"RecursiveAll\">" +
                              "<Query>" +
                              "<Where>" +
                              "<Eq>" +
                              "<FieldRef Name=\"GUID\"/>" +
                              "<Value Type=\"GUID\">" + guid + "</Value>" +
                              "</Eq>" +
                              "</Where>" +
                              "</Query>" +
                              "</View>"
                };

                ListItemCollection itemColl = list.GetItems(query);
                clientContext.Load(itemColl);
                clientContext.ExecuteQuery();
                FieldUrlValue urlValue = new FieldUrlValue();
                urlValue.Url         = serverFilePath;
                urlValue.Description = "Quittung öffnen";
                ListItem item = itemColl.First();

                item["Receipt"] = urlValue;
                item.ParseAndSetFieldValue("ApprovalState", "PDF Quittung übergeben");
                item.Update();
                clientContext.ExecuteQuery();
            }
        }
Ejemplo n.º 38
0
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedTemplateModel = definition.WithAssertAndCast <ControlDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F385106601";

            if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileURL))
            {
                var crawlerXSLFileValue = new FieldUrlValue {
                    Url = typedTemplateModel.CrawlerXSLFileURL
                };

                if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileDescription))
                {
                    crawlerXSLFileValue.Description = typedTemplateModel.CrawlerXSLFileDescription;
                }

                item["CrawlerXSLFile"] = crawlerXSLFileValue;
            }
        }
        /// <summary>
        /// フィールド情報を元に値を変換します。
        /// </summary>
        /// <param name="fields">フィールド情報</param>
        /// <param name="value">値</param>
        /// <returns>変換した値を返します。</returns>
        public static object ConvertValue(this Field fields, object value)
        {
            // TODO: URL 判定処理を実装する。
#if true
            return(value);
#else
            if (value.GetType() == typeof(Uri))
            {
                var u   = value as Uri;
                var url = new FieldUrlValue()
                {
                    Url         = u.AbsolutePath,
                    Description = u.OriginalString,
                };
                return(url);
            }
            else
            {
                return(value.ToString());
            }
#endif
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var folderModelHost = modelHost.WithAssertAndCast<FolderModelHost>("modelHost", value => value.RequireNotNull());
            var definition = model.WithAssertAndCast<PublishingPageLayoutDefinition>("model", value => value.RequireNotNull());

            var folder = folderModelHost.CurrentListFolder;
            var list = folderModelHost.CurrentList;

            ContentType siteContentType = null;

            if (!string.IsNullOrEmpty(definition.AssociatedContentTypeId))
            {
                siteContentType = folderModelHost.HostSite.RootWeb.AvailableContentTypes.GetById(definition.AssociatedContentTypeId);

                folderModelHost.HostSite.Context.Load(siteContentType);
                folderModelHost.HostSite.Context.ExecuteQueryWithTrace();
            }

            var context = folder.Context;

            var pageName = GetSafePageFileName(definition);
            var currentPageFile = GetCurrentPage(list, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentPageFile,
                ObjectType = typeof(File),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            ModuleFileModelHandler.WithSafeFileOperation(list, currentPageFile, f =>
            {
                var file = new FileCreationInformation();

                file.Url = pageName;
                file.Content = Encoding.UTF8.GetBytes(definition.Content);
                file.Overwrite = definition.NeedOverride;

                return folder.Files.Add(file);

            },
            newFile =>
            {
                var newFileItem = newFile.ListItemAllFields;
                context.Load(newFileItem);
                context.ExecuteQueryWithTrace();

                var site = folderModelHost.HostSite;
                var currentPageLayoutItem = FindPageLayoutItem(site, definition.FileName);

                var currentPageLayoutItemContext = currentPageLayoutItem.Context;
                var publishingFile = currentPageLayoutItem.File;

                currentPageLayoutItemContext.Load(currentPageLayoutItem);
                currentPageLayoutItemContext.Load(currentPageLayoutItem, i => i.DisplayName);
                currentPageLayoutItemContext.Load(publishingFile);

                currentPageLayoutItemContext.ExecuteQueryWithTrace();

                newFileItem[BuiltInInternalFieldNames.Title] = definition.Title;
                newFileItem["MasterPageDescription"] = definition.Description;
                newFileItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout;

                if (!string.IsNullOrEmpty(definition.PreviewImageUrl))
                {
                    var urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                    {
                        Value = definition.PreviewImageUrl,
                        Context = context
                    }).Value;

                    var urlFieldValue = new FieldUrlValue { Url = urlValue };

                    if (!string.IsNullOrEmpty(definition.PreviewImageDescription))
                        urlFieldValue.Description = definition.PreviewImageDescription;

                    newFileItem["PublishingPreviewImage"] = urlFieldValue;
                }

                if (siteContentType != null)
                {
                    newFileItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", siteContentType.Name, siteContentType.Id.ToString());
                }

                newFileItem.Update();

                context.ExecuteQueryWithTrace();
            });

            currentPageFile = GetCurrentPage(folderModelHost.CurrentList, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = currentPageFile,
                ObjectType = typeof(File),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            context.ExecuteQueryWithTrace();
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Function to share the matter.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="subAreaOfLawList">String contains all sub area of law</param>
        /// <param name="mailListURL">URL contains list of mail recipients</param>
        /// <returns>Result of operation: Matter Shared successfully or not</returns>        
        internal GenericResponseVM  ShareMatterUtility(Client client, Matter matter, MatterDetails matterDetails, string mailSiteURL, string centralMailListURL, string matterLandingFlag, MatterConfigurations matterConfigurations)
        {
            bool shareFlag = false;
            string mailListName = centralMailListURL.Substring(centralMailListURL.LastIndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.OrdinalIgnoreCase) + 1);
            string matterLocation = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH, matter.Name);
            string ProvisionMatterValidation = string.Empty;
            GenericResponseVM genericResponse = null;
            if (!string.IsNullOrWhiteSpace(mailSiteURL))
            {
                using (ClientContext clientContext = spoAuthorization.GetClientContext(mailSiteURL))
                {
                    
                    genericResponse = validationFunctions.MatterDetailsValidation(matter, client, 
                        int.Parse(ServiceConstants.ProvisionMatterShareMatter, CultureInfo.InvariantCulture), matterConfigurations);
                    if(genericResponse!=null)
                    {
                        return genericResponse;
                    }
                    
                    // Get the current logged in User
                    clientContext.Load(clientContext.Web.CurrentUser);
                    clientContext.ExecuteQuery();
                    string matterMailBody, blockUserNames;
                    // Generate Mail Subject
                    string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSettings.MatterMailSubject, 
                        matter.Id, matter.Name, clientContext.Web.CurrentUser.Title);

                    // Logic to Create Mail body
                    // Step 1: Create Matter Information
                    // Step 2: Create Team Information
                    // Step 3: Create Access Information
                    // Step 4: Create Conflict check Information based on the conflict check flag and create mail body

                    // Step 1: Create Matter Information
                    string defaultContentType = string.Format(CultureInfo.InvariantCulture, 
                        mailSettings.MatterMailDefaultContentTypeHtmlChunk, matter.DefaultContentType);
                    string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);

                    // Step 2: Create Team Information
                    string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                        ServiceConstants.NO : ServiceConstants.YES;
                    string mailBodyTeamInformation = string.Empty;
                    mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

                    // Step 3: Create Access Information
                    if (ServiceConstants.TRUE == matterLandingFlag)
                    {
                        matterLocation = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH, 
                            matterSettings.MatterLandingPageRepositoryName.Replace(ServiceConstants.SPACE, string.Empty), 
                            ServiceConstants.FORWARD_SLASH, matter.MatterGuid, ServiceConstants.ASPX_EXTENSION);
                    }
                    string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH, 
                        matter.MatterGuid, matterSettings.OneNoteLibrarySuffix, 
                        ServiceConstants.FORWARD_SLASH, matter.MatterGuid, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);

                    // Step 4: Create Conflict check Information based on the conflict check flag and create mail body
                    if (matterConfigurations.IsConflictCheck)
                    {
                        string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                        ServiceConstants.NO : ServiceConstants.YES;
                        blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                        blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture, 
                            "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                        matterMailBody = string.Format(CultureInfo.InvariantCulture, 
                            mailSettings.MatterMailBodyMatterInformation, client.Name, client.Id, 
                            matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, 
                            mailSettings.MatterMailBodyConflictCheck, ServiceConstants.YES, matter.Conflict.CheckBy, 
                            Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(matterSettings.MatterCenterDateFormat, CultureInfo.InvariantCulture), 
                            conflictIdentified) + string.Format(CultureInfo.InvariantCulture, 
                            mailSettings.MatterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation, 
                            blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                    }
                    else
                    {
                        blockUserNames = string.Empty;
                        matterMailBody = string.Format(CultureInfo.InvariantCulture, mailSettings.MatterMailBodyMatterInformation, 
                            client.Name, client.Id, matter.Name, matter.Id, 
                            matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, mailSettings.MatterMailBodyTeamMembers, secureMatter, 
                            mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                    }

                    Web web = clientContext.Web;
                    List mailList = web.Lists.GetByTitle(mailListName);
                    List<FieldUserValue> userList = new List<FieldUserValue>();
                    List<FieldUserValue> userEmailList = GenerateMailList(matter, new Client {Url = mailSiteURL }, ref userList);
                    ///// Add the Matter URL in list
                    FieldUrlValue matterPath = new FieldUrlValue()
                    {
                        Url = string.Concat(client.Url.Replace(String.Concat(ServiceConstants.HTTPS, ServiceConstants.COLON, 
                        ServiceConstants.FORWARD_SLASH, ServiceConstants.FORWARD_SLASH), String.Concat(ServiceConstants.HTTP, ServiceConstants.COLON, 
                        ServiceConstants.FORWARD_SLASH, ServiceConstants.FORWARD_SLASH)), ServiceConstants.FORWARD_SLASH, matter.Name, 
                        ServiceConstants.FORWARD_SLASH, matter.Name),
                        Description = matter.Name
                    };
                    List<string> columnNames = new List<string>() { matterSettings.ShareListColumnMatterPath, matterSettings.ShareListColumnMailList,
                        mailSettings.ShareListColumnMailBody, mailSettings.ShareListColumnMailSubject };
                    List<object> columnValues = new List<object>() { matterPath, userEmailList, matterMailBody, matterMailSubject };
                    // To avoid the invalid symbol error while parsing the JSON, return the response in lower case 
                    matterRepositoy.AddItem(clientContext, mailList, columnNames, columnValues);
                    
                }
            }
            return genericResponse;
        }
Ejemplo n.º 42
0
 public override object GetFieldValueTyped(string value)
 {
     var linkValue = new FieldUrlValue();
     var idx = value.IndexOf(',');
     linkValue.Url = (-1 != idx) ? value.Substring(0, idx) : value;
     linkValue.Description = (-1 != idx) ? value.Substring(idx + 1) : value;
     return linkValue;
 }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {

                if (template.Lists.Any())
                {
                    var rootWeb = (web.Context as ClientContext).Site.RootWeb;

                    web.EnsureProperties(w => w.ServerRelativeUrl);

                    web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                    web.Context.ExecuteQueryRetry();
                    var existingLists = web.Lists.AsEnumerable<List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                    var serverRelativeUrl = web.ServerRelativeUrl;

                    #region DataRows

                    foreach (var listInstance in template.Lists)
                    {
                        if (listInstance.DataRows != null && listInstance.DataRows.Any())
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title);
                            // Retrieve the target list
                            var list = web.Lists.GetByTitle(listInstance.Title);
                            web.Context.Load(list);

                            // Retrieve the fields' types from the list
                            FieldCollection fields = list.Fields;
                            web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind));
                            web.Context.ExecuteQueryRetry();

                            foreach (var dataRow in listInstance.DataRows)
                            {
                                try
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1);
                                    var listitemCI = new ListItemCreationInformation();
                                    var listitem = list.AddItem(listitemCI);

                                    foreach (var dataValue in dataRow.Values)
                                    {
                                        Field dataField = fields.FirstOrDefault(
                                            f => f.InternalName == parser.ParseString(dataValue.Key));

                                        if (dataField != null)
                                        {
                                            String fieldValue = parser.ParseString(dataValue.Value);

                                            switch (dataField.FieldTypeKind)
                                            {
                                                case FieldType.Geolocation:
                                                    // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                                    var geolocationArray = fieldValue.Split(',');
                                                    if (geolocationArray.Length == 4)
                                                    {
                                                        var geolocationValue = new FieldGeolocationValue
                                                        {
                                                            Altitude = Double.Parse(geolocationArray[0]),
                                                            Latitude = Double.Parse(geolocationArray[1]),
                                                            Longitude = Double.Parse(geolocationArray[2]),
                                                            Measure = Double.Parse(geolocationArray[3]),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = geolocationValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;
                                                case FieldType.Lookup:
                                                    // FieldLookupValue - Expected format: LookupID
                                                    var lookupValue = new FieldLookupValue
                                                    {
                                                        LookupId = Int32.Parse(fieldValue),
                                                    };
                                                    listitem[parser.ParseString(dataValue.Key)] = lookupValue;
                                                    break;
                                                case FieldType.URL:
                                                    // FieldUrlValue - Expected format: URL,Description
                                                    var urlArray = fieldValue.Split(',');
                                                    var linkValue = new FieldUrlValue();
                                                    if (urlArray.Length == 2)
                                                    {
                                                        linkValue.Url = urlArray[0];
                                                        linkValue.Description = urlArray[1];
                                                    }
                                                    else
                                                    {
                                                        linkValue.Url = urlArray[0];
                                                        linkValue.Description = urlArray[0];
                                                    }
                                                    listitem[parser.ParseString(dataValue.Key)] = linkValue;
                                                    break;
                                                case FieldType.User:
                                                    // FieldUserValue - Expected format: loginName
                                                    var user = web.EnsureUser(fieldValue);
                                                    web.Context.Load(user);
                                                    web.Context.ExecuteQueryRetry();

                                                    if (user != null)
                                                    {
                                                        var userValue = new FieldUserValue
                                                        {
                                                            LookupId = user.Id,
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = userValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;
                                                default:
                                                    listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    break;
                                            }
                                        }
                                        listitem.Update();
                                    }
                                    web.Context.ExecuteQueryRetry(); // TODO: Run in batches?

                                    if (dataRow.Security != null)
                                    {
                                        listitem.SetSecurity(parser, dataRow.Security);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace);
                                    throw;
                                }
                            }
                        }
                    }

                    #endregion
                }
            }

            return parser;
        }
Ejemplo n.º 44
0
 public static string UrlValueToString(FieldUrlValue value)
 {
     return value.Description + LookupValueSeparator + value.Url;
 }
        /// <summary>
        /// Processes the request list item
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="request"></param>
        private void ProcessSiteRequest(ClientContext ctx, ListItem request, SiteType siteType)
        {
            bool isSubSite = false;

            var web = ctx.Web;
            ctx.Load(web, w => w.Url);

            var title = request["Title"].ToString();
            Console.WriteLine("Found site request for new site with title '{0}'...", title);

            //Update list item to indicate that we are processing the request
            request["ProvisioningStatus"] = "Provisioning...";
            request.Update();
            ctx.ExecuteQueryRetry();
            Console.WriteLine("Updated list item with status 'Provisioning...'");

            string baseTemplate = string.Empty;
            string templateFileRelativeUrl = string.Empty;
            string templateFileName = string.Empty;
            string siteTitle = string.Empty;
            string siteUrl = string.Empty;
            string siteDescription = string.Empty;

            //Get basic metadata for logging
            siteTitle = title;
            siteUrl = GetNewSiteUrl(request);

            #region ProvisioningTemplate

            Console.WriteLine("Loading provisioning template...");

            //Throw exception request doesn't have a template
            var templateLookupValue = request["SiteTemplate"] as FieldLookupValue;
            if (templateLookupValue == null)
                throw new Exception(String.Format("Request with title {0} does not have a value for the Site Template field.", title));

            //Get provisioning template
            int id = templateLookupValue.LookupId;
            string lookupListTitle = "Site Templates";
            ListItem templateFile = GetListItemFromLookupList(ctx, id, lookupListTitle);
            string url = templateFile["FileRef"].ToString();
            templateFileName = templateFile["FileLeafRef"].ToString();
            templateFileRelativeUrl = url;

            baseTemplate = templateFile["BaseTemplate"].ToString();

            ProvisioningTemplate provisioningTemplate = GetProvisioningTemplate(ctx, this.SiteTemplatesListTitle, templateFileName);

            //Throw exception if can't find it
            if (provisioningTemplate == null)
                throw new Exception(string.Format("Could not find template {0}", templateFileName));

            //===========================================================
            //Un-comment to use template created from source web instead
            //===========================================================
            //template = clientContext.Web.GetProvisioningTemplate();
            #endregion

            #region ParentWeb
            string parentWebUrl = string.Empty;

            if (siteType == SiteType.Subsite)
            {
                var parentSiteLookupValue = request["ParentWeb"] as FieldLookupValue;
                if (parentSiteLookupValue == null)
                    throw new Exception(String.Format("Subsite request with title {0} does not have a value for the parent site collection field.", title));

                //Get provisioning template
                int clientSiteItemId = parentSiteLookupValue.LookupId;
                ListItem parentSiteListItem = GetListItemFromLookupList(ctx, clientSiteItemId, this.SiteCollectionRequestsListTitle);
                ctx.Load(parentSiteListItem, p => p["LinkToProvisionedSite"]);
                try
                {
                    var parentWeb = parentSiteListItem["LinkToProvisionedSite"] as FieldUrlValue;
                    parentWebUrl = parentWeb.Url;
                }
                catch (Exception ex)
                {
                    throw new Exception(String.Format("The parent site collection '{0}' for the requested subsite '{1}' has not been successfully provisioned.  Aborting subsite creation.",
                        parentSiteLookupValue.LookupValue, siteTitle));
                }
                isSubSite = true;
            }

            #endregion

            //Log all parameters before continuing
            Console.WriteLine("Found site request.  Properties: {0}");
            Console.WriteLine("Base template: {0}", baseTemplate);
            Console.WriteLine("Template file: {0}", templateFileRelativeUrl);
            Console.WriteLine("Template file name: {0}", templateFileName);
            Console.WriteLine("Requested title: {0}", siteTitle);
            Console.WriteLine("Requested URL: {0}", siteUrl);

            //Execute in limited try/catch scope so new web is deleted if any exceptions are thrown
            try
            {

                string newWebUrl = string.Empty;

                if (isSubSite)
                {
                    //Additional owners are added to parent site Owners group because sub-sites inherit security
                    string additionalOwnerEmail = GetListItemUserFieldAsEmail(ctx, request, "ProjectLeader");
                    newWebUrl = CreateSubsite(ctx, parentWebUrl, siteUrl, baseTemplate, siteTitle, "", additionalOwnerEmail, provisioningTemplate);

                }
                else
                {
                    string siteCollectionOwnerEmail = GetListItemUserFieldAsEmail(ctx, request, "SiteCollectionOwner");
                    newWebUrl = CreateSiteCollection(ctx, ctx.Web.Url, siteUrl, baseTemplate, siteTitle, "", siteCollectionOwnerEmail, provisioningTemplate);
                }

                //Update list item fields in list in source web
                request["Processed"] = DateTime.Now;
                FieldUrlValue linkToSite = new FieldUrlValue();
                linkToSite.Url = newWebUrl;
                linkToSite.Description = siteTitle;

                request["ProvisioningStatus"] = "Provisioned";
                request["LinkToProvisionedSite"] = linkToSite;
                request["ErrorMessage"] = "";

                request.Update();

                ctx.ExecuteQueryRetry();
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception of type {0} occurred creating or applying template to new web: {1}", ex.GetType(), ex.Message);

                Console.WriteLine("Stack trace: {0}", ex.StackTrace);

                Console.WriteLine("Attempting to roll back web creation...");

                if (ctx.Web.WebExists(siteUrl))
                {
                    var newWeb = ctx.Web.GetWeb(siteUrl);
                    ctx.Load(newWeb);
                    ctx.ExecuteQuery();

                    newWeb.DeleteObject();

                    ctx.ExecuteQuery();
                    Console.WriteLine("...Deleted newly-created web.");
                }

                //Bubble up
                throw;
            }
        }
Ejemplo n.º 46
0
		internal static void CreateCustomer(this Customer customer, ClientContext ctx) {
			var customers = ctx.Web.Lists.GetByTitle("Customer");
			ListItem li = customers.AddItem(new ListItemCreationInformation());
			li["Title"] = customer.Title;
			li["Address"] = customer.Address;
			li["contactPerson"] = customer.ContactPerson;
			li["phoneOffice"] = customer.OfficePhone;
			li["phoneMobile"] = customer.Mobile;
			li["Email"] = customer.Email;
			li["DispLogo"] = new FieldUrlValue() { Description = customer.Title + " Logo", Url = customer.Logo };

			li.Update();
			ctx.ExecuteQuery();
		}
Ejemplo n.º 47
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows);

            if (template.Lists.Any())
            {
                var rootWeb = (web.Context as ClientContext).Site.RootWeb;
                if (!web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    web.Context.Load(web, w => w.ServerRelativeUrl);
                    web.Context.ExecuteQueryRetry();
                }

                web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                web.Context.ExecuteQueryRetry();
                var existingLists = web.Lists.AsEnumerable<List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                var serverRelativeUrl = web.ServerRelativeUrl;

                #region DataRows

                foreach (var listInstance in template.Lists)
                {
                    if (listInstance.DataRows != null && listInstance.DataRows.Any())
                    {
                        // Retrieve the target list
                        var list = web.Lists.GetByTitle(listInstance.Title);
                        web.Context.Load(list);

                        // Retrieve the fields' types from the list
                        FieldCollection fields = list.Fields;
                        web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind));
                        web.Context.ExecuteQueryRetry();

                        foreach (var dataRow in listInstance.DataRows)
                        {
                            var listitemCI = new ListItemCreationInformation();
                            var listitem = list.AddItem(listitemCI);

                            foreach (var dataValue in dataRow.Values)
                            {
                                Field dataField = fields.FirstOrDefault(
                                    f => f.InternalName == dataValue.Key.ToParsedString());

                                if (dataField != null)
                                {
                                    String fieldValue = dataValue.Value.ToParsedString();

                                    switch (dataField.FieldTypeKind)
                                    {
                                        case FieldType.Geolocation:
                                            // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                            var geolocationArray = fieldValue.Split(',');
                                            if (geolocationArray.Length == 4)
                                            {
                                                var geolocationValue = new FieldGeolocationValue
                                                {
                                                    Altitude = Double.Parse(geolocationArray[0]),
                                                    Latitude = Double.Parse(geolocationArray[1]),
                                                    Longitude = Double.Parse(geolocationArray[2]),
                                                    Measure = Double.Parse(geolocationArray[3]),
                                                };
                                                listitem[dataValue.Key.ToParsedString()] = geolocationValue;
                                            }
                                            else
                                            {
                                                listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            }
                                            break;
                                        case FieldType.Lookup:
                                            // FieldLookupValue - Expected format: LookupID
                                            var lookupValue = new FieldLookupValue
                                            {
                                                LookupId = Int32.Parse(fieldValue),
                                            };
                                            listitem[dataValue.Key.ToParsedString()] = lookupValue;
                                            break;
                                        case FieldType.URL:
                                            // FieldUrlValue - Expected format: URL,Description
                                            var urlArray = fieldValue.Split(',');
                                            var linkValue = new FieldUrlValue();
                                            if (urlArray.Length == 2)
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[1];
                                            }
                                            else
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[0];
                                            }
                                            listitem[dataValue.Key.ToParsedString()] = linkValue;
                                            break;
                                        case FieldType.User:
                                            // FieldUserValue - Expected format: loginName
                                            var user = web.EnsureUser(fieldValue);
                                            web.Context.Load(user);
                                            web.Context.ExecuteQueryRetry();

                                            if (user != null)
                                            {
                                                var userValue = new FieldUserValue
                                                {
                                                    LookupId = user.Id,
                                                };
                                                listitem[dataValue.Key.ToParsedString()] = userValue;
                                            }
                                            else
                                            {
                                                listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            }
                                            break;
                                        default:
                                            listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            break;
                                    }
                                }
                                listitem.Update();
                            }
                            web.Context.ExecuteQueryRetry(); // TODO: Run in batches?
                        }
                    }
                }
                #endregion
            }
        }
Ejemplo n.º 48
0
    static void PopulateProductsList() {

      Console.WriteLine();
      Console.WriteLine("Adding sample items to Products list");
      Console.WriteLine("------------------------------------");
      Console.WriteLine();

      
      // add a few sample products
      ListItem product1 = listProducts.AddItem(new ListItemCreationInformation());
      product1["Title"] = "Batman Action Figure";
      product1["ProductCode"] = "WP0001";
      product1["ProductListPrice"] = 14.95;
      product1["ProductDescription"] = "A super hero who sometimes plays the role of a dark knight.";
      product1["ProductColor"] = new string[] { "Black" };
      product1["MinimumAge"] = 7;
      product1["MaximumAge"] = 12;
      FieldUrlValue urlValue1 = new FieldUrlValue();
      urlValue1.Url = listProductImagesUrl + "/WP0001.jpg";
      urlValue1.Description = "batman";
      product1["ProductImageUrl"] = urlValue1;
      product1.Update();
      Console.WriteLine("  Adding Batman Action Figure");
      clientContext.ExecuteQuery();


      ListItem product2 = listProducts.AddItem(new ListItemCreationInformation());
      product2["Title"] = "Captain America Action Figure";
      product2["ProductCode"] = "WP0002";
      product2["ProductListPrice"] = 12.95;
      product2["ProductDescription"] = "A super action figure that protects freedom and the American way of life.";
      product2["ProductColor"] = new string[] { "Red", "White", "Blue" };
      product2["MinimumAge"] = 7;
      product2["MaximumAge"] = 12;
      FieldUrlValue urlValue2 = new FieldUrlValue();
      urlValue2.Url = listProductImagesUrl + "/WP0002.jpg";
      urlValue2.Description = "batman";
      product2["ProductImageUrl"] = urlValue1;
      product2.Update();
      Console.WriteLine("  Adding Captain America Action Figure");
      clientContext.ExecuteQuery();

      ListItem product3 = listProducts.AddItem(new ListItemCreationInformation());
      product3["Title"] = "GI Joe Action Figure";
      product3["ProductCode"] = "WP0003";
      product3["ProductListPrice"] = 14.95;
      product3["ProductDescription"] = "A classic action figure from the 1970s.";
      product3["ProductColor"] = new string[] { "Green" };
      product3["MinimumAge"] = null;
      product3["MaximumAge"] = null;
      product3.Update();
      Console.WriteLine("  Adding GI Joe Action Figure");
      clientContext.ExecuteQuery();

      ListItem product4 = listProducts.AddItem(new ListItemCreationInformation());
      product4["Title"] = "Green Hulk Action Figure";
      product4["ProductCode"] = "WP0004";
      product4["ProductListPrice"] = 9.99;
      product4["ProductDescription"] = "An overly muscular action figure that strips naked when angry.";
      product4["ProductColor"] = "Green";
      product4["MinimumAge"] = 7;
      product4["MaximumAge"] = 12;
      product4.Update();
      Console.WriteLine("  Adding Green Hulk Action Figure");
      clientContext.ExecuteQuery();

      ListItem product5 = listProducts.AddItem(new ListItemCreationInformation());
      product5["Title"] = "Red Hulk Alter Ego Action Figure";
      product5["ProductCode"] = "WP0005";
      product5["ProductListPrice"] = 9.99;
      product5["ProductDescription"] = "A case of anabolic steroids with a most unfortunate outcome.";
      product5["ProductColor"] = "Red";
      product5["MinimumAge"] = 7;
      product5["MaximumAge"] = 12;
      product5.Update();
      Console.WriteLine("  Adding Red Hulk Alter Ego Action Figure");
      clientContext.ExecuteQuery();

      ListItem product6 = listProducts.AddItem(new ListItemCreationInformation());
      product6["Title"] = "Godzilla Action Figure";
      product6["ProductCode"] = "WP0006";
      product6["ProductListPrice"] = 19.95;
      product6["ProductDescription"] = "The classic and adorable action figure from those old Japanese movies.";
      product6["ProductColor"] = "Green";
      product6["MinimumAge"] = 10;
      product6["MaximumAge"] = null;
      product6.Update();
      Console.WriteLine("  Adding Godzilla Action Figure");
      clientContext.ExecuteQuery();

      ListItem product7 = listProducts.AddItem(new ListItemCreationInformation());
      product7["Title"] = "Perry the Platypus Action Figure";
      product7["ProductCode"] = "WP0007";
      product7["ProductListPrice"] = 21.95;
      product7["ProductDescription"] = "A platypus who plays an overly intelligent detective sleuth on TV.";
      product7["ProductColor"] = new string[] { "Green", "Yellow" };
      product7["MinimumAge"] = null;
      product7["MaximumAge"] = null;
      product7.Update();
      Console.WriteLine("  Adding Perry the Platypus Action Figure");
      clientContext.ExecuteQuery();

      ListItem product8 = listProducts.AddItem(new ListItemCreationInformation());
      product8["Title"] = "Green Angry Bird Action Figure";
      product8["ProductCode"] = "WP0008";
      product8["ProductListPrice"] = 4.95;
      product8["ProductDescription"] = "A funny looking green bird that really hates pigs.";
      product8["ProductColor"] = "Green";
      product8["MinimumAge"] = 5;
      product8["MaximumAge"] = 10;
      product8.Update();
      Console.WriteLine("  Adding Green Angry Bird Action Figure");
      clientContext.ExecuteQuery();

      ListItem product9 = listProducts.AddItem(new ListItemCreationInformation());
      product9["Title"] = "Red Angry Bird Action Figure";
      product9["ProductCode"] = "WP0009";
      product9["ProductListPrice"] = 14.95;
      product9["ProductDescription"] = "A funny looking red bird that also hates pigs.";
      product9["ProductColor"] = "Red";
      product9["MinimumAge"] = 5;
      product9["MaximumAge"] = 10;
      product9.Update();
      Console.WriteLine("  Adding Red Angry Bird Action Figure");
      clientContext.ExecuteQuery();

      ListItem product10 = listProducts.AddItem(new ListItemCreationInformation());
      product10["Title"] = "Phineas and Ferb Action Figure Set";
      product10["ProductCode"] = "WP0010";
      product10["ProductListPrice"] = 19.95;
      product10["ProductDescription"] = "The dynamic duo of the younger generation.";
      product10["ProductColor"] = new string[] { "Green", "Red" };
      product10["MinimumAge"] = 5;
      product10["MaximumAge"] = 51;
      product10.Update();
      Console.WriteLine("  Adding Phineas and Ferb Action Figure Set.");
      clientContext.ExecuteQuery();

      ListItem product11 = listProducts.AddItem(new ListItemCreationInformation());
      product11["Title"] = "Black Power Ranger Action Figure";
      product11["ProductCode"] = "WP0011";
      product11["ProductListPrice"] = 7.50;
      product11["ProductDescription"] = "A particularly violent action figure for violent children.";
      product11["ProductColor"] = new string[] { "Black", "White" };
      product11["MinimumAge"] = 8;
      product11["MaximumAge"] = 12;
      product11.Update();
      Console.WriteLine("  Adding Black Power Ranger Action Figure");
      clientContext.ExecuteQuery();

      ListItem product12 = listProducts.AddItem(new ListItemCreationInformation());
      product12["Title"] = "Woody Action Figure";
      product12["ProductCode"] = "WP0012";
      product12["ProductListPrice"] = 9.95;
      product12["ProductDescription"] = "The lovable, soft-spoken cowboy from Toy Story.";
      product12["ProductColor"] = new string[] { "Blue", "Yellow" };
      product12["MinimumAge"] = null;
      product12["MaximumAge"] = 12;
      product12.Update();
      Console.WriteLine("  Adding Woody Action Figure");
      clientContext.ExecuteQuery();

      ListItem product13 = listProducts.AddItem(new ListItemCreationInformation());
      product13["Title"] = "Spiderman Action Figure";
      product13["ProductCode"] = "WP0013";
      product13["ProductListPrice"] = 12.95;
      product13["ProductDescription"] = "The classic superhero who is quite the swinger.";
      product13["ProductColor"] = new string[] { "Red", "Blue" };
      product13["MinimumAge"] = 8;
      product13["MaximumAge"] = 12;
      product13.Update();
      Console.WriteLine("  Adding Spiderman Action Figure");
      clientContext.ExecuteQuery();

      ListItem product14 = listProducts.AddItem(new ListItemCreationInformation());
      product14["Title"] = "Twitter Follower Action Figure";
      product14["ProductCode"] = "WP0014";
      product14["ProductListPrice"] = 1.00;
      product14["ProductDescription"] = "An inexpensive action figure you can never have too many of.";
      product14["ProductColor"] = new string[] { "Yellow", "Blue" };
      product14["MinimumAge"] = 12;
      product14["MaximumAge"] = null;
      product14.Update();
      Console.WriteLine("  Adding Twitter Follower Action Figure");
      clientContext.ExecuteQuery();

      ListItem product15 = listProducts.AddItem(new ListItemCreationInformation());
      product15["Title"] = "Crayloa Crayon Set";
      product15["ProductCode"] = "WP0015";
      product15["ProductListPrice"] = 2.49;
      product15["ProductDescription"] = "A very fun set of crayons in every color.";
      product15["ProductColor"] = new string[] { "Blue", "Red", "Green", "Yellow" };
      product15["MinimumAge"] = 10;
      product15["MaximumAge"] = null;
      product15.Update();
      Console.WriteLine("  Adding Crayloa Crayon Set");
      clientContext.ExecuteQuery();

      ListItem product16 = listProducts.AddItem(new ListItemCreationInformation());
      product16["Title"] = "Sponge Bob Coloring Book";
      product16["ProductCode"] = "WP0016";
      product16["ProductListPrice"] = 2.95;
      product16["ProductDescription"] = "An action figure of America's most recognizable celebrity.";
      product16["ProductColor"] = "Yellow";
      product16["MinimumAge"] = 7;
      product16["MaximumAge"] = 12;
      product16.Update();
      Console.WriteLine("  Adding Sponge Bob Coloring Book");
      clientContext.ExecuteQuery();

      ListItem product17 = listProducts.AddItem(new ListItemCreationInformation());
      product17["Title"] = "Easel with Supply Trays";
      product17["ProductCode"] = "WP0017";
      product17["ProductListPrice"] = 49.95;
      product17["ProductDescription"] = "A serious easel for serious young artists.";
      product17["ProductColor"] = "White";
      product17["MinimumAge"] = 12;
      product17["MaximumAge"] = null;
      product17.Update();
      Console.WriteLine("  Adding Easel with Supply Trays");
      clientContext.ExecuteQuery();

      ListItem product18 = listProducts.AddItem(new ListItemCreationInformation());
      product18["Title"] = "Crate o' Crayons";
      product18["ProductCode"] = "WP0018";
      product18["ProductListPrice"] = 14.95;
      product18["ProductDescription"] = "More crayons that you can shake a stick at.";
      product18["ProductColor"] = new string[] { "Blue", "Red", "Green", "Yellow" };
      product18["MinimumAge"] = 7;
      product18["MaximumAge"] = 12;
      product18.Update();
      Console.WriteLine("  Adding Crate o' Crayons");
      clientContext.ExecuteQuery();

      ListItem product19 = listProducts.AddItem(new ListItemCreationInformation());
      product19["Title"] = "Etch A Sketch";
      product19["ProductCode"] = "WP0019";
      product19["ProductListPrice"] = 12.95;
      product19["ProductDescription"] = "A strategic planning tool for the Romney campaign.";
      product19["ProductColor"] = "Red";
      product19["MinimumAge"] = 7;
      product19["MaximumAge"] = null;
      product19.Update();
      Console.WriteLine("  Adding Etch A Sketch");
      clientContext.ExecuteQuery();

      ListItem product20 = listProducts.AddItem(new ListItemCreationInformation());
      product20["Title"] = "Green Hornet";
      product20["ProductCode"] = "WP0020";
      product20["ProductListPrice"] = 24.95;
      product20["ProductDescription"] = "A fast car for crusin' the strip at night.";
      product20["ProductColor"] = "Green";
      product20["MinimumAge"] = 10;
      product20["MaximumAge"] = null;
      product20.Update();
      Console.WriteLine("  Adding Green Hornet");
      clientContext.ExecuteQuery();

      ListItem product21 = listProducts.AddItem(new ListItemCreationInformation());
      product21["Title"] = "Red Wacky Stud Bumper";
      product21["ProductCode"] = "WP0021";
      product21["ProductListPrice"] = 24.95;
      product21["ProductDescription"] = "A great little vehicle for off road fun.";
      product21["ProductColor"] = "Red";
      product21["MinimumAge"] = 10;
      product21["MaximumAge"] = null;
      product21.Update();
      Console.WriteLine("  Adding Red Wacky Stud Bumper");
      clientContext.ExecuteQuery();

      ListItem product22 = listProducts.AddItem(new ListItemCreationInformation());
      product22["Title"] = "Red Stomper Bully";
      product22["ProductCode"] = "WP0022";
      product22["ProductListPrice"] = 29.95;
      product22["ProductDescription"] = "A great toy that can crush and destroy all your other toys.";
      product22["ProductColor"] = "Red";
      product22["MinimumAge"] = 10;
      product22["MaximumAge"] = null;
      product22.Update();
      Console.WriteLine("  Adding Red Stomper Bully");
      clientContext.ExecuteQuery();

      ListItem product23 = listProducts.AddItem(new ListItemCreationInformation());
      product23["Title"] = "Green Stomper Bully";
      product23["ProductCode"] = "WP0023";
      product23["ProductListPrice"] = 24.95;
      product23["ProductDescription"] = "A green alternative to crush and destroy the Red Stomper Bully.";
      product23["ProductColor"] = "Green";
      product23["MinimumAge"] = 10;
      product23["MaximumAge"] = null;
      product23.Update();
      Console.WriteLine("  Adding Green Stomper Bully");
      clientContext.ExecuteQuery();

      ListItem product24 = listProducts.AddItem(new ListItemCreationInformation());
      product24["Title"] = "Indy Race Car";
      product24["ProductCode"] = "WP0024";
      product24["ProductListPrice"] = 19.95;
      product24["ProductDescription"] = "The fastest remote control race car on the market today.";
      product24["ProductColor"] = "Black";
      product24["MinimumAge"] = 10;
      product24["MaximumAge"] = null;
      product24.Update();
      Console.WriteLine("  Adding Indy Race Car");
      clientContext.ExecuteQuery();

      ListItem product25 = listProducts.AddItem(new ListItemCreationInformation());
      product25["Title"] = "Turbo-boost Speedboat";
      product25["ProductCode"] = "WP0025";
      product25["ProductListPrice"] = 32.95;
      product25["ProductDescription"] = "The preferred water vehicle of gun runners and drug kingpins.";
      product25["ProductColor"] = "Red";
      product25["MinimumAge"] = 21;
      product25["MaximumAge"] = null;
      product25.Update();
      Console.WriteLine("  Adding Turbo-boost Speedboat");
      clientContext.ExecuteQuery();

      ListItem product26 = listProducts.AddItem(new ListItemCreationInformation());
      product26["Title"] = "Sandpiper Prop Plane";
      product26["ProductCode"] = "WP0026";
      product26["ProductListPrice"] = 24.95;
      product26["ProductDescription"] = "A simple RC prop plane for younger pilots.";
      product26["ProductColor"] = "White";
      product26["MinimumAge"] = 15;
      product26["MaximumAge"] = null;
      product26.Update();
      Console.WriteLine("  Adding Sandpiper Prop Plane");
      clientContext.ExecuteQuery();

      ListItem product27 = listProducts.AddItem(new ListItemCreationInformation());
      product27["Title"] = "Flying Badger";
      product27["ProductCode"] = "WP0027";
      product27["ProductListPrice"] = 27.95;
      product27["ProductDescription"] = "A tough fighter plane to root out evil anywhere it lives.";
      product27["ProductColor"] = "Blue";
      product27["MinimumAge"] = 15;
      product27["MaximumAge"] = null;
      product27.Update();
      Console.WriteLine("  Adding Flying Badger");
      clientContext.ExecuteQuery();

      ListItem product28 = listProducts.AddItem(new ListItemCreationInformation());
      product28["Title"] = "Red Barron von Richthofen";
      product28["ProductCode"] = "WP0028";
      product28["ProductListPrice"] = 32.95;
      product28["ProductDescription"] = "A classic RC plane to hunt down and terminate Snoopy.";
      product28["ProductColor"] = "Red";
      product28["MinimumAge"] = 15;
      product28["MaximumAge"] = null;
      product28.Update();
      Console.WriteLine("  Adding Red Barron von Richthofen");
      clientContext.ExecuteQuery();

      ListItem product29 = listProducts.AddItem(new ListItemCreationInformation());
      product29["Title"] = "Flying Squirrel";
      product29["ProductCode"] = "WP0029";
      product29["ProductListPrice"] = 69.95;
      product29["ProductDescription"] = "A stealthy remote control plane that flies on the down-low and under the radar.";
      product29["ProductColor"] = "Grey";
      product29["MinimumAge"] = 18;
      product29["MaximumAge"] = null;
      product29.Update();
      Console.WriteLine("  Adding Flying Squirrel");
      clientContext.ExecuteQuery();

      ListItem product30 = listProducts.AddItem(new ListItemCreationInformation());
      product30["Title"] = "FOX News Chopper";
      product30["ProductCode"] = "WP0030";
      product30["ProductListPrice"] = 29.95;
      product30["ProductDescription"] = "A new chopper which can generate new events on demand.";
      product30["ProductColor"] = "Blue";
      product30["MinimumAge"] = 18;
      product30["MaximumAge"] = null;
      product30.Update();
      Console.WriteLine("  Adding FOX News Chopper");
      clientContext.ExecuteQuery();

      ListItem product31 = listProducts.AddItem(new ListItemCreationInformation());
      product31["Title"] = "Seal Team 6 Helicopter";
      product31["ProductCode"] = "WP0031";
      product31["ProductListPrice"] = 59.95;
      product31["ProductDescription"] = "A serious helicopter that can open up a can of whoop-ass when required.";
      product31["ProductColor"] = "Green";
      product31["MinimumAge"] = 18;
      product31["MaximumAge"] = null;
      product31.Update();
      Console.WriteLine("  Adding Seal Team 6 Helicopter");
      clientContext.ExecuteQuery();

      ListItem product32 = listProducts.AddItem(new ListItemCreationInformation());
      product32["Title"] = "Personal Commuter Chopper";
      product32["ProductCode"] = "WP0032";
      product32["ProductListPrice"] = 99.95;
      product32["ProductDescription"] = "A partially-test remote control device that can actually carry real people.";
      product32["ProductColor"] = "Red";
      product32["MinimumAge"] = 18;
      product32["MaximumAge"] = null;
      product32.Update();
      Console.WriteLine("  Adding Personal Commuter Chopper");
      clientContext.ExecuteQuery();

      Console.WriteLine();
      Console.WriteLine("  Loading of product items has completed");
      Console.WriteLine();
    }
        /// <summary>
        /// Function to share the matter.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object</param>
        /// <param name="matterDetails">Matter object containing Matter data details</param>
        /// <param name="mailSiteURL">URL of the site</param>
        /// <param name="centralMailListURL">URL of the Send Mail list</param>
        /// <param name="matterLandingFlag">Flag to determine if Matter landing page exists</param>
        /// <param name="matterConfigurations">Object holding configuration for the matter</param>
        /// <returns>Result of operation: Matter Shared successfully or not</returns>        
        internal static string ShareMatterUtility(RequestObject requestObject, Client client, Matter matter, MatterDetails matterDetails, string mailSiteURL, string centralMailListURL, string matterLandingFlag, MatterConfigurations matterConfigurations)
        {
            string shareFlag = ConstantStrings.FALSE;
            string mailListName = centralMailListURL.Substring(centralMailListURL.LastIndexOf(ConstantStrings.ForwardSlash, StringComparison.OrdinalIgnoreCase) + 1);
            string matterLocation = string.Concat(client.Url, ConstantStrings.ForwardSlash, matter.Name);
            string ProvisionMatterValidation = string.Empty;
            if (!string.IsNullOrWhiteSpace(mailSiteURL))
            {
                using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(mailSiteURL), requestObject.RefreshToken))
                {

                    ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, null, int.Parse(ConstantStrings.ProvisionMatterShareMatter, CultureInfo.InvariantCulture), matterConfigurations);
                    if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                    {
                        // Get the current logged in User
                        clientContext.Load(clientContext.Web.CurrentUser);
                        clientContext.ExecuteQuery();
                        string matterMailBody, blockUserNames;
                        // Generate Mail Subject
                        string matterMailSubject = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailSubject, matter.Id, matter.Name, clientContext.Web.CurrentUser.Title);

                        // Logic to Create Mail body
                        // Step 1: Create Matter Information
                        // Step 2: Create Team Information
                        // Step 3: Create Access Information
                        // Step 4: Create Conflict check Information based on the conflict check flag and create mail body

                        // Step 1: Create Matter Information
                        string defaultContentType = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailDefaultContentTypeHtmlChunk, matter.DefaultContentType);
                        string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);

                        // Step 2: Create Team Information
                        string secureMatter = ConstantStrings.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ? ConstantStrings.NO : ConstantStrings.YES;
                        string mailBodyTeamInformation = string.Empty;
                        mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

                        // Step 3: Create Access Information
                        if (ConstantStrings.TRUE == matterLandingFlag)
                        {
                            matterLocation = string.Concat(client.Url, ConstantStrings.ForwardSlash, ServiceConstantStrings.MatterLandingPageRepositoryName.Replace(ConstantStrings.Space, string.Empty), ConstantStrings.ForwardSlash, matter.MatterGuid, ConstantStrings.AspxExtension);
                        }
                        string oneNotePath = string.Concat(client.Url, ConstantStrings.ForwardSlash, matter.MatterGuid, ServiceConstantStrings.OneNoteLibrarySuffix, ConstantStrings.ForwardSlash, matter.MatterGuid, ConstantStrings.ForwardSlash, matter.MatterGuid);

                        // Step 4: Create Conflict check Information based on the conflict check flag and create mail body
                        if (matterConfigurations.IsConflictCheck)
                        {
                            string conflictIdentified = ConstantStrings.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ? ConstantStrings.NO : ConstantStrings.YES;
                            blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                            blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture, "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                            matterMailBody = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyMatterInformation, client.Name, client.Id, matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyConflictCheck, ConstantStrings.YES, matter.Conflict.CheckBy, Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(ServiceConstantStrings.MatterCenterDateFormat, CultureInfo.InvariantCulture), conflictIdentified) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                        }
                        else
                        {
                            blockUserNames = string.Empty;
                            matterMailBody = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyMatterInformation, client.Name, client.Id, matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                        }

                        Web web = clientContext.Web;
                        List mailList = web.Lists.GetByTitle(mailListName);
                        List<FieldUserValue> userList = new List<FieldUserValue>();
                        List<FieldUserValue> userEmailList = ProvisionHelperFunctions.GenerateMailList(matter, clientContext, ref userList);
                        ///// Add the Matter URL in list
                        FieldUrlValue matterPath = new FieldUrlValue()
                        {
                            Url = string.Concat(client.Url.Replace(String.Concat(ConstantStrings.HTTPS, ConstantStrings.COLON, ConstantStrings.ForwardSlash, ConstantStrings.ForwardSlash), String.Concat(ConstantStrings.HTTP, ConstantStrings.COLON, ConstantStrings.ForwardSlash, ConstantStrings.ForwardSlash)), ConstantStrings.ForwardSlash, matter.Name, ConstantStrings.ForwardSlash, matter.Name),
                            Description = matter.Name
                        };
                        List<string> columnNames = new List<string>() { ServiceConstantStrings.ShareListColumnMatterPath, ServiceConstantStrings.ShareListColumnMailList, TextConstants.ShareListColumnMailBody, TextConstants.ShareListColumnMailSubject };
                        List<object> columnValues = new List<object>() { matterPath, userEmailList, matterMailBody, matterMailSubject };
                        // To avoid the invalid symbol error while parsing the JSON, return the response in lower case
                        shareFlag = Convert.ToString(Lists.AddItem(clientContext, mailList, columnNames, columnValues), CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentUICulture);
                    }
                }
            }
            return shareFlag;
        }
Ejemplo n.º 50
0
        static void UpdateProductsListWithImageUrls()
        {
            clientContext.Load(listProducts);
              ListItemCollection products = listProducts.GetItems(new CamlQuery());
              clientContext.Load(products);
              clientContext.ExecuteQuery();

              foreach (var product in products) {
            string title = product["Title"].ToString();
            string productCode = product["ProductCode"].ToString();
            string productImageUrl = site.Url + listProductImages.RootFolder.ServerRelativeUrl + "/" + productCode + ".jpg";
            FieldUrlValue urlValue = new FieldUrlValue();

            urlValue.Url = productImageUrl;
            urlValue.Description = title;
            product["ProductImageUrl"] = urlValue;
            product.Update();
            Console.WriteLine("  adding " + productImageUrl);
            clientContext.ExecuteQuery();
              }
        }
 private static FieldUrlValue GetFieldUrlValue(string ProductCode, string ImageDescription)
 {
     FieldUrlValue urlValue = new FieldUrlValue();
       urlValue.Url = listProductImagesUrl + "/" + ProductCode + ".jpg";
       urlValue.Description = ImageDescription;
       return urlValue;
 }
Ejemplo n.º 52
0
        public void SetFileProperties(File file, IDictionary<string, string> properties, bool checkoutIfRequired = true)
        {
            var context = file.Context;
            if (properties != null && properties.Count > 0)
            {
                // Get a reference to the target list, if any
                // and load file item properties
                var parentList = file.ListItemAllFields.ParentList;
                context.Load(parentList);
                context.Load(file.ListItemAllFields);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (ServerException ex)
                {
                    // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties)
                    if (ex.Message != "The object specified does not belong to a list.")
                    {
                        throw;
                    }
                }

                // Loop through and detect changes first, then, check out if required and apply
                foreach (var kvp in properties)
                {
                    var propertyName = kvp.Key;
                    var propertyValue = kvp.Value;

                    var targetField = parentList.Fields.GetByInternalNameOrTitle(propertyName);
                    targetField.EnsureProperties(f => f.TypeAsString, f => f.ReadOnlyField);

                    // Changed by PaoloPia because there are fields like PublishingPageLayout
                    // which are marked as read-only, but have to be overwritten while uploading
                    // a publishing page file and which in reality can still be written
                    if (!targetField.ReadOnlyField || WriteableReadOnlyFields.Contains(propertyName.ToLower()))
                    {
                        switch (propertyName.ToUpperInvariant())
                        {
                            case "CONTENTTYPE":
                                {
                                    Microsoft.SharePoint.Client.ContentType targetCT = parentList.GetContentTypeByName(propertyValue);
                                    context.ExecuteQueryRetry();

                                    if (targetCT != null)
                                    {
                                        file.ListItemAllFields["ContentTypeId"] = targetCT.StringId;
                                    }
                                    else
                                    {
                                        Log.Error(Constants.LOGGING_SOURCE, "Content Type {0} does not exist in target list!", propertyValue);
                                    }
                                    break;
                                }
                            default:
                                {
                                    switch (targetField.TypeAsString)
                                    {
                                        case "User":
                                            var user = parentList.ParentWeb.EnsureUser(propertyValue);
                                            context.Load(user);
                                            context.ExecuteQueryRetry();

                                            if (user != null)
                                            {
                                                var userValue = new FieldUserValue
                                                {
                                                    LookupId = user.Id,
                                                };
                                                file.ListItemAllFields[propertyName] = userValue;
                                            }
                                            break;
                                        case "URL":
                                            var urlArray = propertyValue.Split(',');
                                            var linkValue = new FieldUrlValue();
                                            if (urlArray.Length == 2)
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[1];
                                            }
                                            else
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[0];
                                            }
                                            file.ListItemAllFields[propertyName] = linkValue;
                                            break;
                                        case "MultiChoice":
                                            var multiChoice = JsonUtility.Deserialize<String[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = multiChoice;
                                            break;
                                        case "LookupMulti":
                                            var lookupMultiValue = JsonUtility.Deserialize<FieldLookupValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = lookupMultiValue;
                                            break;
                                        case "TaxonomyFieldType":
                                            var taxonomyValue = JsonUtility.Deserialize<TaxonomyFieldValue>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValue;
                                            break;
                                        case "TaxonomyFieldTypeMulti":
                                            var taxonomyValueArray = JsonUtility.Deserialize<TaxonomyFieldValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValueArray;
                                            break;
                                        default:
                                            file.ListItemAllFields[propertyName] = propertyValue;
                                            break;
                                    }
                                    break;
                                }
                        }
                    }
                    file.ListItemAllFields.Update();
                    context.ExecuteQueryRetry();
                }
            }
        }