Accessing embedded xml file using C#

I have recently been embedding xml files into assemblies so the information can be accessed in code.

This is how I get a reference to the current assembly where the code and xml file is residing

Assembly currentAssembly = Assembly.GetExecutingAssembly();

I invoke the method to get my xml file by doing the following:

Stream stream = currentAssembly.GetManifestResourceStream(this.GetType(), “ValidationRules.xml”);

I create a new XmlDocument and load the content of the xml file into there:

XmlDocument doc = new XmlDocument();
doc.Load(stream);

Given my xml is kind of like this:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<Fields>

<Field>
<Name>Question 1a</Name>
<ValidationRule>Mandatory</ValidationRule>
<ValidationMessage>The Question 1a field cannot be empty</ValidationMessage>
<DependentFields>Question 2a</DependentFields>
</Field>
<Field>
<Name>Question1b</Name>
<ValidationRule>Mandatory</ValidationRule>
<ValidationMessage>Question 1b cannot be empty</ValidationMessage>
<DependentFields>Question2b</DependentFields>
</Field>

</Fields>

Depending on the structure of your xml, I would iterate through the element nodes using a foreach. I would go through each element by doing the following:

 foreach (XmlElement xmlField in doc.SelectNodes(“/Fields/Field”))
{
string fieldName = xmlField.SelectSingleNode(“Name”).InnerText;
string dependentFields = xmlField.SelectSingleNode(“DependentFields”).InnerText;
}

I can now use the data from the xml file to do other processing in my code.

Adding role assignment to sharepoint list. The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

I recently received this  error “The system cannot find the path specified. (Exception from HRESULT: 0x80070003)” while attempting to add a role assignment to a SharePoint tasks list. I tried breaking role inheiritance and reseting role inheiritance on the list but nothing worked.

It turned out that the list was not ‘provisioned’ and it was still in memory.  There are certain changes you can make to a list that is still in memory and there are others which require the list to exist in the site before they can be made.  I was able to add the role assignments to the SharePoint list by placing my code in a method that was called after site provisioning.

This also explains why I could add the role definition to the list when I tested my code using a console application.

Add site administrator using C#

Here is some code to give an existing site collection user the Site Administrator level access.

string webURL = “http://testserver:12345/“;
                  using (SPSite site = new SPSite(webURL)) {
                      using (SPWeb web = site.RootWeb)
                      {
                           try
                           {
                                 SPUser user = web.SiteUsers[“domain\\UserName”];
                                 user.IsSiteAdmin = true;                             
                                 user.Update();            
                          }

                          catch(Exception ex)
                          {                            

                                    // Log exception 
                          }
                      }
                   }

Replace “domain\\UserName”, with the real domain and user name that you want to provide the Site Administrator access to.

Also,  use the SPWeb.EnsureUser method to add the user login to the site if you do not know if the user has or has not been added to the site collection.

Sorting a DataTable

I have a datatable called dtSchoolResults

I grab the default view of the datatable

DataView dvSchoolResults = dtSchoolResults.DefaultView;

I specifiy the column name and sort expression for the Sort propertyof the dataview.

 dvSchoolResults.Sort = “Date Created DESC”;

I convert the view to a datatable and assign it back into dtSchoolResults

 dtSchoolResults= dvSchoolResults.ToTable();

 

The sort expression format is : COLUMN NAME SORT ORDER

e.g.  NAME ASC

First Name ASC

Last Name DESC

DOB DESC

The best overloaded method match for ‘Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(…) has some invalid arguments

I came across a issue today why attempting to use SPSecurity.RunWithElevatedPrivileges in code. The two exceptions I got when I tried building the solution was:

The best overloaded method match for ‘Microsoft.SharePoint.RunWithElevatedPrivileges(Microsoft.SharePoint.SPSecurity.CodeToRunElevated)’ has some invalid arugments

Argument ‘1’: cannot convert from ‘anonymous method’ to ‘Microsoft.SharePoint.SPSecurity.CodeToRunElevated’

And the code was

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(Web.ParentWeb.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        if (web != null)
                        {
                            String groupName = DateTime.Now() + ” Contributors”;
                           return  Groups.Get(web, groupName);

                        }                       
                    }
                }
            });
            return null;

All the two errors were trying to tell me in ‘another language was that I cannot have ‘return’ calls in the code that is being elevated.  So I moved the ‘return’ calls outside of the code that was being run under elevated privileges.

  Group group = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(Web.ParentWeb.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        if (web != null)
                        {
                            String groupName = DateTime.Now() + ” Contributors”;
                            group = Groups.Get(web, groupName);

                        }                       
                    }
                }
            });
            return group;               

 After doing this, the code compiled.

Done.

Custom SPSecurityTrimmedControl

The SPSecurityTrimmedControl is a very handy control to use especially when you want to hide a control(s) or text from the user based on their permissions on the site.

I have come across situations where I needed to extend the SPSecurityTrimmed control to limit the content displayed to the current logged in user. Permissions on the site was dynamically changing so I can’t rely on using the out of the box SPSecurityTrimmed control and setting ‘static’ permissions for it to hide/show content. Also, the item is accessible by multiple users but there were some controls and text that only the author of the item should see and use.

So…… I developed my custom SPSecurityTrimmedControl.

public partial class ShowHideUIControls:Microsoft.SharePoint.WebControls.SPSecurityTrimmedControl
 {
        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {
            if(IsUserTheAuthor())
            {
                base.Render(output);
            }
        }

        protected bool IsUserTheAuthor()
        {
            return SPContext.Current.Web.CurrentUser.Sid.Equals(SPContext.Current.ListItem.File.Author.Sid);
        }
 }

On the aspx page where I wanted to place this control, I added the following to the top of the page.

<%@ Register TagPrefix=”CustomTrimControl” Namespace=”CustomProjectDevelopment.UserControls” Assembly=”CustomProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=o6b1a8da1u6d1903″ %>

And I added my custom SPSecurityTrimmedControl around the content and controls I wanted to hide conditionally:

<CustomTrimControl:ShowHideUIControls runat=”server” ID=”HideUIControls1″>
          <tr>
         <td style=”font-size: 133%;  padding-top: 32px; border-bottom: 1px solid #83b0ec;”>
       Site Audit Access History      
   </td>
        </tr>
 <tr><td>
 <br /> <!– Other controls or text you want to be hidden from other users are placed here e.g. like the control below –>
    <CustomDevControl:SiteAuditAccessHistory runat=”server”  id=”customDevControl1″></CustomDevControl:SiteAuditAccessHistory>
   
 </td></tr>
 </CustomTrimControl:ShowHideUIControls>

There you have it. Everything between the <CustomTrimControl:ShowHideUIControls>… <\CustomTrimControl:ShowHideUIControls> will only be visible to the author of the item.