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.

Advertisements

Failed to activate feature ‘PublishingPrerequisites’ issue

This morning, I created a site collection and tried to activate the Office SharePoint Server Publishing Infrastructure feature. I received this error

Failed to activate feature ‘PublishingPrerequisites’ (ID: a392da98-270b-4e85-9769-04c0fde267aa) ……………

Followed by a long stack trace…

I addressed this issue by doing the following:

Start -> Run -> type IISRESET and hit enter.

I went back into the Site Collection Features gallery, and activated the Office SharePoint Server Publishing Infrastructure feature successfully.

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.

SharePoint and displaying OCS Presence using JavaScript

I found a really neat way of displaying presence information using JavaScript. Of course, I got help from various tutorials, but I have decided to share some of my findings as well 🙂

The Init.JS javascript file contains the methods you need to use to get and display OCS presence information.

To simply check if a user has an OCS presence of online or offline via javascript, you can create an instance of Name.NameCtrl.1 active x object and call the get status method. This method will return you a number that determines the different presence statues (i.e. online, busy, away, do not disturb, offline).

<javascript type=’text/javascript’>

var IMNControlObj=new ActiveXObject(“Name.NameCtrl.1”);

var state = (IMNControlObj.GetStatus(‘phil.lau@phillau.com’,1));

if(state ==1)
{
 document.write(‘Offline’);

}
else
{
 document.write(‘Online’);
}

</script>

The following example will show the presence icon plus the dropdown menu that is available in the OCS client  followed by Phil Lau.

<span><img border=”0″ valign=”middle” height=”12″ width=”12″ src=”/_layouts/images/imnhdr.gif” onload=”IMNRC(‘phil.lau@philau.com’)” id=’sampleId1′ ShowOfflinePawn=1/>Phil Lau</span>

You can place a content editor web part onto a sharepoint web part zone and test out the JavaScript functions available for displaying the presence information of a user.

A prequisite for this to work is to have Office Communicator client  installed on your machine and of course, SharePoint 🙂

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.