3

I have a List View web part (In the page > Add web part > App > document library name). I need to update the TitleUrl property of this web part through C# code.

The SaveChanges() method below works for my visual web parts, but not for the List view webpart. I get an error saying: Exception has been thrown by the target of an invocation

webpartManager = myPage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
webPart.TitleUrl = titleURL;
webpartManager.SaveChanges(webPart);

I did a casting as below

XsltListViewWebPart listViewWebPart = (XsltListViewWebPart)webPart;
listViewWebPart.TitleUrl = titleURL;
webpartManager.SaveChanges(listViewWebPart);

But I get the error at SaveChanges() method.

An exception of type 'System.Reflection.TargetInvocationException' occurred in Microsoft.SharePoint.dll but was not handled in user code

The error description is as below

>    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
> arguments, Signature sig, Boolean constructor)    at
> System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
> Object[] parameters, Object[] arguments)    at
> System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
> invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)  
> at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[]
> index)    at
> Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.DoesPersonalizedPropertValueMatchDefaultValue(SPPersonalizablePropertyEntry
> spPersonalizablePropertyEntry, Object value, Control defaultControl)  
> at
> Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.Serialize(PersonalizationScope
> scope, BinaryWebPartSerializerFlag binaryWebPartSerializerFlags,
> BinaryWebPartSerializerWriter writer)    at
> Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.Serialize(SerializationMode
> mode, BinaryWebPartSerializerFlag binaryWebPartSerializerFlags,
> SPSerializationBinderBase serializationBinder,
> BinaryWebPartSerializerWriter writer)    at
> Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.Serialize(SerializationMode
> mode, BinaryWebPartSerializerFlag binaryWebPartSerializerFlags,
> SPSerializationBinderBase serializationBinder)    at
> Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChangesCore(SPLayoutProperties
> layoutProperties, Boolean httpGet, Boolean saveCompressed, Boolean
> skipRightsCheck, Boolean skipSafeAgainstScriptCheck, WebPartTypeInfo&
> newTypeId, Byte[]& newAllUsersProperties, Byte[]&
> newPerUserProperties, String[]& newLinks)    at
> Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChangesInternal(SPLayoutProperties
> layoutProperties, Boolean skipRightsCheck, Boolean
> skipSafeAgainstScriptCheck)    at
> Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChanges(Guid
> storageKey)    at
> Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.SaveChanges(WebPart
> webPart)    at
> WSP.ABC.ABC.ABCWindow.<>c__DisplayClass5.<ChangeWebPartProperties>b__4()
> at
> Microsoft.SharePoint.SPSecurity.<>c__DisplayClass5.<RunWithElevatedPrivileges>b__3()
> at
> Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated
> secureCode)

any reason why ?

3
  • Try this ListViewWebPart wp = (ListViewWebPart)webpart; Dec 29, 2014 at 13:47
  • @AmalHashim Actually I tried that before. It gives a invalid cast exception which is the reason why i cast it now to a XsltListViewWebPart
    – Shaamil
    Dec 30, 2014 at 4:18
  • Even i too facing the same issue, can any one has solution to this, or any workaround.
    – user39442
    Feb 9, 2015 at 4:49

1 Answer 1

0

The following approach works for me. Instead of casting, I use the Properties collection.

You would of course have to change the creation of the context / authentication and the way you look for the specific WebPart which in this case is done by title.

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SharePointTest1 {


  class Program {

    private static void ShowWebPartProperties(string webFullUrl, string fileName, string webPartTitle) {
      using (var context = new ClientContext(webFullUrl)) {
        context.Credentials = System.Net.CredentialCache.DefaultCredentials;
        File file = context.Web.GetFileByServerRelativeUrl(fileName);

        LimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
        context.Load(wpm.WebParts,
        wps => wps.Include(
        wp => wp.WebPart.Title));
        context.ExecuteQuery();
        foreach (WebPartDefinition wpd in wpm.WebParts) {
          WebPart wp = wpd.WebPart;
          if (wp.Title == webPartTitle) {
            Console.WriteLine(wp.Title + " found. Showing properties:");
            var properties = wp.Properties;
            context.Load(properties);
            context.ExecuteQuery();
            foreach (var item in properties.FieldValues.Keys.OrderBy(m => m).ToList()) {
              Console.WriteLine(string.Format("{0} = {1}", item, properties.FieldValues[item]));
            }
            break;
          }
        }
        Console.WriteLine("");
      }
    }




    private static void ChangeWebPartProperty(string webFullUrl, string fileName, string webPartTitle, string propertyName, object propertyValue) {
      using (var context = new ClientContext(webFullUrl)) {
        context.Credentials = System.Net.CredentialCache.DefaultCredentials;
        File file = context.Web.GetFileByServerRelativeUrl(fileName);

        LimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared);

        context.Load(wpm.WebParts,
        wps => wps.Include(
        wp => wp.WebPart.Title));
        context.ExecuteQuery();
        foreach (WebPartDefinition wpd in wpm.WebParts) {
          WebPart wp = wpd.WebPart;
          if (wp.Title == webPartTitle) {
            Console.WriteLine(wp.Title + " found");
            wp.Properties[propertyName] = propertyValue;
            wpd.SaveWebPartChanges();
            context.ExecuteQuery();
            break;
          }
        }
      }
    }

    static void Main(string[] args) {
      try {
        ShowWebPartProperties("http://localhost/DocumentLibraryTest/",
          "/DocumentLibraryTest/SitePages/Home.aspx",
          "Documents");

        ChangeWebPartProperty("http://localhost/DocumentLibraryTest/",
        "/DocumentLibraryTest/SitePages/Home.aspx",
        "Documents", "TitleUrl", "http://evolootion.net");
      } catch (Exception ex) {
        Console.WriteLine(ex);
      }
      Console.WriteLine("Finished");
      Console.ReadLine();
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.