Pages

Friday, May 14, 2010

Adding Entries in SharePoint Web Configuration File using SPWebConfigModification

One of requirement in my project was to edit the web.config of the current SharePoint web application.

After some goggling I came to know that SharePoint provides us the powerful API (
SPWebConfigModification)  to interact with web.config directly.

So I will be explaining some points that how to use this API:

I created a feature at WebApplication Level so that we will be able to Modify configuration file as soon as feature gets activated.

Actually SPWebConfigModification Class has Members Like 
  1. Name : (Property) used for managing name of section or node to set or read
  2. Path : (Property) used for managing node and this is Xpath expression
  3. Owner: (property) unique Name for owner of the
  4. Sequence (Property) used for managing Sequence Number of Modification (usually 0)
  5. Value : (property) used for setting (or reading) value to node
More Info on : (Msdn-great Source)

I will be explaining this modification class in two ways 
  1. Part 1: Adding a sub-section inside a section
  2. Part 2: Setting Node value of a section
Part  1:

Adding a SafeControl Entry inside <SafeControls> section of the web.config file

private
 void AddSafeControlEntry(SPWebApplication webApplication)
{
    SPWebConfigModification entry = new SPWebConfigModification();
    entry.Path = "configuration/SharePoint/SafeControls";
    entry.Name = "SafeControl [@Namespace='YourNamespaceName']";
    entry.Sequence = 0;
    entry.Owner = "somethingUniqueName";
    entry.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    entry.Value =  "<SafeControl Assembly=\"YourfullAssemblyName\" Namespace=\"YourNamespaceName\" TypeName=\"*\" Safe=\"True\" />";
    webApplication.WebConfigModifications.Add (entry);   
}
Part 2:

Here I am setting users value of Node <allow users="*" /> to "?" in authorization section

private
}
 void ModifyAuthorization (SPWebApplication webApp)
{
    SPWebConfigModification testEntry = new SPWebConfigModification ("users",          "configuration/system.web/ authorization/ allow ");
    testEntry.Sequence = 0;
    testEntry.Owner = "somethingUniqueName";
    testEntry.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
    testEntry.Value = "?";
    webApp.WebConfigModifications.Add (testEntry);
}

If you noticed in Part 1 and Part 2 examples... type property of modification is different

That is because when you want to add a section inside configuration file then use EnsureChildNode and when you want to set node values which are already in configuration file then use EnsureAttribute .

Also while adding section in configuration file avoid using type as EnsureSection because sections created by using this type are permanent and cannot be removed from the configuration file.

So calling these two methods inside feature receiver will be like :

public
override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
   
AddSafeControlEntry(webApplication);
   
ModifyAuthorization(webApplication);      webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();              
     webApplication.Update();

Small Tip:

After doing changes in configuration file one should call method

webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();           
webApplication.Update();

because by using this method changes to web.config file gets applied at farm level and also use this method call only once rather using after each addition because this method creates timer job on server so if you call this method more than once in single cycle then you might face an error like .. There is timer job already running

So best practice is to call your methods to add your changes in configuration file and then finally call this method

References: great post : http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32
and http://blog.thekid.me.uk/archive/2007/03/20/removing-web-config-entries-from-sharepoint-using-spwebconfigmodification.aspx

Removing Entries From SharePoint Web Configuration File using SPWebConfigModification

In this section I will be explaining short code about how to remove entries from web configuration file of SharePoint using API SPWebConfigModification
in following function passing SPWebApplication and name of owner as parameters.

Then getting collection of all modifications in web configuration file and then while iterating through collection of these modifications , compare name of owner which is unique and remove that modification from collection and update web application.

private
 void RemoveTestEntry(SPWebApplication webApplication, string owner)
{
    Collection<SPWebConfigModification> allModifications = webApplication.WebConfigModifications;
    int initialCount = webApplication.Count;
    for (int i = initialCount - 1; i >= 0; i--)
    {
        SPWebConfigModification Testmodification = allModifications [i];
        if (Testmodification.Owner == owner)
            allModifications.Remove(Testmodification);
    }
    if (initialCount > allModifications.Count)
   {
        webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();               
        webApplication.Update();
    }
}

Monday, November 30, 2009

Item Level Security For SharePoint Document Libraries

Hi ,


after some long discussions with my collegues and by observations when I came to know that sharepoint document libraries don't have any UI to provide Item Level Security then I started thinking on this .
all we know that as in Sharepoint list we can set the read and write security by using UI in advanced settings and like this





but in case of SPDocumentLibrary things are in some different way
but I found one way by using custom solution for this
this can be done like:

actually there are some read and write security bits available with the SPList and SPDocumentLibrary.
by setting those with proper valued we can manage ItemLevelSecurity
  • Read Security
    1 - All users have Read access to all items.
    2 - Users have Read access only to items that they create.
  • Write security
    1 — All users can modify all items.
    2 — Users can modify only items that they create.
    4 — Users cannot modify any list item.

more details can be found here Read Security and Write Security

Get SharePoint WebApplication/Application Pool owner's password

Hi All,
I was trying to get the username and the password for the sharepoint webapplication owner.
after long searching in this thing I came up with one short custom solution and this can be done like this:
SPWebApplication webApp = SPContext.Current.Site.WebApplication; string userName =webApp.ApplicationPool.Username;
string password == webApp.ApplicationPool.Password;

this gets the username and password of the Application Pool Creator for web application

Thursday, September 17, 2009

Exciting Tool - stsadm

Hello All,

We all know that sharepoint central administration is the great UI which allows us to to all administration operation for the sharepoint.

but there is something more powerful command line tool in sharepoint known as STSADM.

location:- 12\BIN\STSADM.EXE

here is the link to all stsadm commands : all stsadm commands

there is some thing called customizationof these commands.

gl-tool is the great tool which is customized stsadm commands and allows you more power.
visit this link to know more

Playing Flash (.swf) Files in the SharePoint

Hello All,

actually I was trying my hands on the playing the animated images on the sharepoint web pages and was successful to show animated .gif files on web page.

so , I was thinking to play some more animations on the sharepoint site without use of any other custom web part.
what all I wanted was to play the flash file on sharepoint site without using video and other webparts.

so we can do this by using very useful webpart in sharepoint that is Content Editor Webpart.

what all you need to do is:


Upload the flash video file to the any document Library of the website open video file from document library and copy url.


1. open your page in the edit mode
2. add the content editor webpart on page

3. click on modify shared properties of the content editor webpart

4. open the tool pane and open source editor

5. write this code inside the source editor and you are done!!



<object width="1000" height="100">
<embed src="url to .swf file="1000" height="100"></embed>
</object>


(you can adjust height and width of the flash accordingly)

Thursday, September 10, 2009

Working with SharePoint Item Events

Hello All,

before some days I was working with the SharePoint list items and their events.

I just wanted to add small suggestion here that while working with the SPItemEventReceiver class or with the class that inherits from SPItemEventReceiver, we oftenly override the methods like

ItemAdding , ItemAdded, ItemUpdating, ItemUpdated.....etc

so many times scenario comes that we need to update something in the list and on some event but other events are stopping that
so to avoid this error

use

this.DisableEventFiring();
//update list or any listitem here
this.EnableEventFiring();

this works fine and avoids error.

please let me know If you find any improvement to be done in this.

Get HTML of .aspx page

Hello All,

before some days I was working with the .aspx pages and got in the situation that I needed the source of the page from code.

I am posting this small code snippet might be useful for others also

(Note:- There might be some issue while getting html source from the web page due to some network settings like proxies and secure sockets.)

//this creates a request to a web page.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url of webpage");

//use this for obtaining settings of network

request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;

request.Credentials = System.Net.CredentialCache.DefaultCredentials;

HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
Encoding encoding = Encoding.GetEncoding(responce.CharacterSet);

//gets responce in the format of stream

Stream stream = responce.GetResponseStream();

//use StreamReader to read the stream contents


StreamReader reader = new StreamReader(stream, encoding);

string content = reader.ReadToEnd();

then you can use this obtained string content for any purpose like writing to a file.

Please suggest me If you find some improvements to be done in this.