<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>where coding happens !</title>
	<atom:link href="http://oricode.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://oricode.wordpress.com</link>
	<description>useful coding tips from my everyday experiences</description>
	<pubDate>Thu, 03 Jul 2008 16:26:52 +0000</pubDate>
	<generator>http://wordpress.org/?v=MU</generator>
	<language>en</language>
			<item>
		<title>Upload a file to Sharepoint 2007 using webservices with a specific content type</title>
		<link>http://oricode.wordpress.com/2008/07/03/upload-a-file-to-sharepoint-2007-using-webservices-with-a-specific-content-type/</link>
		<comments>http://oricode.wordpress.com/2008/07/03/upload-a-file-to-sharepoint-2007-using-webservices-with-a-specific-content-type/#comments</comments>
		<pubDate>Thu, 03 Jul 2008 16:25:27 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Coding]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Sharepoint upload 2001 2007]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=18</guid>
		<description><![CDATA[These days I&#8217;ve been involved in a migration project from Sharepoint 2001 to MOSS 2007, what  I had to do was move all the documents from a document workspace in SPS2001 to a WSS3.0 document library. Since some of the custom metada had to be migrated with the documents and the SP2001 profiles had to [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>These days I&#8217;ve been involved in a migration project from Sharepoint 2001 to MOSS 2007, what  I had to do was move all the documents from a document workspace in SPS2001 to a WSS3.0 document library. Since some of the custom metada had to be migrated with the documents and the SP2001 profiles had to be converted to MOSS content types I decided that the best approach would be to use MOSS 2007 web services interface, most specifically the <em>Copy.asmx </em>web service which has a <em>CopyIntoItems </em>method that enables to upload files to a document library.</p>
<p>Since SP2001 is an obsolete platform, I won&#8217;t talk here about how to access it and deal with the <em>PKMCDO </em>COM library (if there is enough interest, I might write an article about that) and I will focus on the file upload web service and the more challenging topic (imho) which is how to set a content type to the uploaded documents.</p>
<p>The first thing to do would be to get the files uploaded to MOSS. As I told, I will be using the <em>Copy.asmx </em>web service. Following is the code of the upload function:</p>
<pre name="code" class="csharp">

        public void UploadFile(string destinationFolderPath,
                               byte[] fileBytes,
                               string fileName,
                               bool overwrite,
                               string sourceFileUrl,
                               string lastVersionUrl)
        {

            List&lt;Sharepoint.FieldInformation&gt; fields = new List&lt;Sharepoint.FieldInformation&gt;();
            Sharepoint.FieldInformation fieldInfo;

            fieldInfo = new Sharepoint.FieldInformation();
            fieldInfo.Id = Microsoft.SharePoint.SPBuiltInFieldId.Title;
            fieldInfo.Value = &quot;New title&quot;;
            fieldInfo.DisplayName = &quot;Title&quot;;
            fieldInfo.Type = YetAnotherMigrationTool.Library.SP2007.Sharepoint.FieldType.Text;
            fieldInfo.InternalName = &quot;Title&quot;;
            fields.Add(fieldInfo);

            string[] url;
            if (string.IsNullOrEmpty(destinationFolderPath))
                url = new string[] { string.Format(&quot;{0}/{1}/{2}&quot;, _siteUrl, _name, fileName) };
            else
                url = new string[] { string.Format(&quot;{0}/{1}/{2}{3}&quot;, _siteUrl, _name, destinationFolderPath, fileName) };
            Sharepoint.CopyResult[] result;

            Sharepoint.Copy service = new Sharepoint.Copy();
            service.Url = _siteUrl + &quot;/_vti_bin/Copy.asmx&quot;;
            service.Credentials = new NetworkCredential(Settings.Instance.User, Settings.Instance.Password);
            service.Timeout = 600000;

            uint documentId = service.CopyIntoItems(sourceFileUrl, url, fields.ToArray(), fileBytes, out result);
        }
</pre>
<p>There is nothing really difficult there. It necessary to call the webservice with an account that has <em>Manage List</em> permissions on the target document library. Also we should estimate the maximum document size we plan to upload and network speed and set the <em>maxRequestLength</em> and <em>executionTimeout</em> values of the <em>httpRuntime</em> section in our <em>web.config</em> in accord to avoit any possible Timeout Exception.</p>
<p>I&#8217;ve included an example of how would we set any of the document&#8217;s properties when calling the <em>CopyIntoItems</em> method. I&#8217;ve used the <em>Title</em> property to show that even read only fields can be assigned with that method. So, can all the fields be assigned ? Unfortunately not.</p>
<p>One of my requirements was to map SP2001 document profiles to MOSS content types, in order to do that, I created the content types at the server with their custom columns and looked for a way to pass this info as a parameter to the <em>CopyIntoItems</em> service call. There was not a parameter such like that, but I was confident that I would be able to set the <em>ContentType</em> field just as I did with the <em>Title</em> field and that would be all. However, that solution didn&#8217;t work. No matter if you set the <em>ContentType</em> or the <em>ContentTypeId</em> fields before calling the <em>Copy.asmx</em> service that the uploaded document content type will always be the default content type of the library.</p>
<p>After doing that I tried another approach. As I saw that the default content type of the library was assigned to the uploaded files, I tried to change the default content type of the list before uploading each file. Unfortunately, I couldn&#8217;t find any webservice that provided that functionality, I tried the <em>UpdateList</em> method of the <em>Lists.asmx</em> service with a custom xml scheme where the <em>&lt;DEFAULT&gt;&lt;/DEFAULT&gt;</em> section of the content type element was replaced by the one I wanted to be with no luck. I couldn&#8217;t manage to get the default content type of a document library changed !</p>
<p>Finally, I tried the last solution I had thought of. It was to use the <em>UpdateListItems</em> method of the <em>Lists.asmx</em> service to change the item <em>ContentType</em> field. The reason why I didn&#8217;t try this approach first instead of trying to change the default content type of the document library (which would seem the obvious thing to do) was because I didn&#8217;t expect it to work. If I hadn&#8217;t been able to set that readonly field with the <em>CopyIntoItems</em> method of the <em>Copy.asmx</em> service it would be expected for the <em>UpdateListItems</em> to have the same behaviour. But it doesn&#8217;t. It is possible to update any field with this method and eventually change a document content type.</p>
<p>So here is the method I use to call that service and change the content type:</p>
<pre name="code" class="csharp">

        public void SetContentType(List&lt;string&gt; ids, string contentType)
        {
            ListsService.Lists service = new YetAnotherMigrationTool.Library.SP2007.ListsService.Lists();
            service.Url = _siteUrl + &quot;/_vti_bin/Lists.asmx&quot;;
            service.Credentials = new NetworkCredential(Settings.Instance.User, Settings.Instance.Password);

            string strBatch = &quot;&quot;;
            for (int i = 1; i &lt;= ids.Count; i++)
            {
                strBatch += @&quot;&lt;Method ID=&#039;&quot;+i.ToString()+@&quot;&#039; Cmd=&#039;Update&#039;&gt;&lt;Field Name=&#039;ID&#039;&gt;&quot; + ids[i-1] + &quot;&lt;/Field&gt;&lt;Field Name=&#039;ContentType&#039;&gt;&quot;+contentType+&quot;&lt;/Field&gt;&lt;/Method&gt;&quot;;
            }
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement elBatch = xmlDoc.CreateElement(&quot;Batch&quot;);
            elBatch.SetAttribute(&quot;OnError&quot;, &quot;Continue&quot;);
            elBatch.SetAttribute(&quot;ListVersion&quot;, &quot;10&quot;);
            elBatch.SetAttribute(&quot;ViewName&quot;, &quot;&quot;);
            elBatch.InnerXml = strBatch;

            result = service.UpdateListItems(_name, elBatch);
        }
</pre>
<p>I called this method passing as parameters the collection of ids I got from the <em>CopyIntoItems</em> call, grouping by content type and it worked ! Now I can set the content type to my uploaded files and my first big issue with that migration project is solved. Currently I am working on a more complicated step which is how to migrate the version history from the SP2001 documents to the MOSS 2007, if I finally manage to solve it I&#8217;ll surely post a new article on that topic. That&#8217;s all for now, as always, comments are welcome !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/18/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/18/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=18&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/07/03/upload-a-file-to-sharepoint-2007-using-webservices-with-a-specific-content-type/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Sharepoint webpart for Silverlight 2.0</title>
		<link>http://oricode.wordpress.com/2008/03/31/sharepoint-webpart-for-silverlight-20/</link>
		<comments>http://oricode.wordpress.com/2008/03/31/sharepoint-webpart-for-silverlight-20/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 07:12:44 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Silverlight]]></category>

		<category><![CDATA[Webpart]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=16</guid>
		<description><![CDATA[Before the last release of Silverlight 2.0 beta 1 embedding a silverlight application in a webpart was a somewhat tedious thing to do. Basically, you had to deploy your silverlight.dll and .xaml file within your Sharepoint solution as well as a bunch of javascript files that are called from your sharepoint webpart to create your silverlight content.
With [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Before the last release of Silverlight 2.0 beta 1 embedding a silverlight application in a webpart was a somewhat tedious thing to do. Basically, you had to deploy your silverlight.dll and .xaml file within your Sharepoint solution as well as a bunch of javascript files that are called from your sharepoint webpart to create your silverlight content.</p>
<p>With the last release of Silverlight 2.0 all this steps are no longer necessary and we can easily host Silverlight Applications in Sharepoint Webparts just by including Silverlight controls and deploying .xap files with our solution.</p>
<p>For this example, I&#8217;ll create a generic webpart that will be able to load any .xap file accessible at our server. It will have a <em>XapUrl</em> property where we will be able to write a Url where the webpart will search for the xap file. Obviously this means that the .xap file must be deployed in our server, I usually do that by including the file in my Sharepoint Solution and deploying it in the <em>_layouts</em> folder of my server.</p>
<p>So following, is the code of my Silverlight Webpart</p>
<pre name="code" class="csharp">

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Runtime.InteropServices;
using System.Web.UI;

namespace Examples.SilverLight
{
    public class SilverLightWebpart : System.Web.UI.WebControls.WebParts.WebPart
    {
        private ScriptManager _scriptHandler;
        private System.Web.UI.SilverlightControls.Silverlight _silverlightControl;

        private string _xapUrl = string.Empty;
        [WebBrowsable(true), Personalizable(true)]
        public string XapUrl
        {
            get { return _xapUrl; }
            set { _xapUrl = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _scriptHandler = ScriptManager.GetCurrent(this.Page);
            if (_scriptHandler == null)
            {
                _scriptHandler = new ScriptManager();
                _scriptHandler.ID = &quot;ScriptManager1&quot;;
                this.Controls.Add(_scriptHandler);
            }

            if (!string.IsNullOrEmpty(_xapUrl))
            {
                _silverlightControl = new System.Web.UI.SilverlightControls.Silverlight();
                _silverlightControl.ID = &quot;Xaml1&quot;;
                _silverlightControl.Source = _xapUrl;
                _silverlightControl.Version = &quot;2.0&quot;;
                this.Controls.Add(_silverlightControl);
            }
        }

    }
}
</pre>
<p>Basically what we are doing is adding a ScriptManager and a Silverlight controls to our class. The only things we have to take care of are to ensure that there is only one instance of a ScriptManager in our current page (we do that with the call <em>ScriptManager.GetCurrent(this.Page);</em>) and that we must create the controls in the <em>OnInit</em> event of our webpart instead of the usual <em>CreateChildControls</em> event if not, we will get an exception from <em>ScriptManager.RegisterScriptControl</em> telling &#8220;<strong>Script controls may not be registered before PreRender</strong>&#8220;</p>
<p>And that&#8217;s all, see how simple is now to host silverlight applications in our sharepoint server !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=16&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/03/31/sharepoint-webpart-for-silverlight-20/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Silverlight 2.0 beta 1 ListBox Databinding and possible bug ?</title>
		<link>http://oricode.wordpress.com/2008/03/12/silverlight-20-beta-1-listbox-databinding-and-possible-bug/</link>
		<comments>http://oricode.wordpress.com/2008/03/12/silverlight-20-beta-1-listbox-databinding-and-possible-bug/#comments</comments>
		<pubDate>Wed, 12 Mar 2008 12:14:34 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[RIA]]></category>

		<category><![CDATA[Silverlight]]></category>

		<category><![CDATA[Databinding]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=15</guid>
		<description><![CDATA[This week I&#8217;ve started playing with the new and longly waited Silverlight 2.0 beta 1 libraries. Finally we can develop real world bussiness applications with Silverlight using all the UI controls that this beta release includes.
After doing a couple of HelloWorld samples, I decided to try the DataBinding feature. In theory, it is really simple to [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This week I&#8217;ve started playing with the new and longly waited Silverlight 2.0 beta 1 libraries. Finally we can develop real world bussiness applications with Silverlight using all the UI controls that this beta release includes.</p>
<p>After doing a couple of HelloWorld samples, I decided to try the <em>DataBinding </em>feature. In theory, it is really simple to databind our controls to the bussiness classes by setting their <em>DataContext </em>property which is something I won&#8217;t cover in this post and you can follow this <a href="http://silverlight.net/learn/tutorials/databinding.aspx">link</a> if you are looking for a nice tutorial on this topic.</p>
<p>What I&#8217;ll cover here is a strange issue I found when trying to databind a <em>ListBox </em>control to a simple <em>List&lt;string&gt; </em>data source.</p>
<p>In my XAML code, I&#8217;ve simply added a <em>ListBox</em> control and set it&#8217;s <em>DataContext</em> property to the databinding I&#8217;ll be using:</p>
<p><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">ListBox</font><font size="2" color="#ff0000"> x</font><font size="2" color="#0000ff">:</font><font size="2" color="#ff0000">Name</font><font size="2" color="#0000ff">=&#8221;Items&#8221;</font><font size="2" color="#ff0000"> ItemsSource</font><font size="2" color="#0000ff">=&#8221;{</font><font size="2" color="#a31515">Binding</font><font size="2" color="#ff0000"> Items</font><font size="2" color="#0000ff">,</font><font size="2" color="#ff0000"> Mode</font><font size="2" color="#0000ff">=OneWay}&#8221; /&gt;</font></font></p>
<p>I also set the <em>DataContext</em> property of the list to the object I&#8217;ll be using to do the databinding at the codebehind of the control, there&#8217;s also a button that will call the <em>AddItem</em> function (see later) of my bussiness class:</p>
<pre name="code" class="csharp">

public partial class Page : UserControl
{
    private Invoice _invoice = new Invoice();    

    public Page()
    {
        Items.DataContext = _invoice;
        myButton.Click += new RoutedEventHandler(myButton_Click);
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        _invoice.AddItem(&quot;this is a new Item!&quot;);
    }
}
</pre>
<p>And here is my business class which I&#8217;ve reduced to the list property to keep things simple:</p>
<pre name="code" class="csharp">

public class Invoice : INotifyPropertyChanged
{
    private List _items = new List();

    public List Items
    {
        get { return _items; }
        set { _items = value; NotifyPropertyChanges(&quot;Items&quot;); }
    }

    public void AddItem(string newItem)
    {
        _items.Add(newItem);
        NotifyPropertyChanges(&quot;Items&quot;);
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanges(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}
</pre>
<p>The interesting part in the above code is the <em>AddItem</em> function. Since I wan&#8217;t to be able to add new items in the Items collection and automatically update the UI control responsible for displaying the list of items, I can&#8217;t simply call the <em>Items.Add</em> method because we must call <em>NotifyPropertyChanges</em> to get our databinding updated. We could also have created our custom list class that implemented <em>INotifyPropertyChanged</em> interface and took care of this (which is something I will surely do in my applications) but for this example is not necessary.What one would expect to happen with this code is that whenever the button click event is clicked, a new item is added in the &#8220;Items&#8221; list and the ListBox is updated. However, this is not working this way. What happens is that the item is added in the &#8220;Items&#8221; list but the ListBox control is not updated, the new item is not showing in the UI at all, futhermore, if we set up some breakpoints right after the <em>AddItem</em> method is called, we will see that the <em>ItemsSource</em> collection of the ListBox control is correctly updated and will contain a new item as it should, but the control is not updating it&#8217;s UI.</p>
<p>Finally, if I change the <em>AddItem</em> method of the bussiness class to the following implementation, everything works as expected and the list UI is correctly updated:</p>
<pre name="code" class="csharp">

public void AddItem(string newItem)
{
    List temp = new List(_items);
    temp.Add(newItem);
    _items = new List(temp);
    NotifyPropertyChanges(&quot;ITems&quot;);
}
</pre>
<p>I haven&#8217;t still found an explanation of this strange behaviour and would really appreciate if somebody could point me out if there is something I have done wrong or if it&#8217;s some kind of bug in the beta 1 library. So any comment regarding this will be appreciated !Thanks for your time and come back again for more interesting topics on the highly expected Silverlight 2.0 release !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=15&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/03/12/silverlight-20-beta-1-listbox-databinding-and-possible-bug/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>SPWebConfigModification: configure applicationSettings with a Feature</title>
		<link>http://oricode.wordpress.com/2008/03/05/spwebconfigmodification-configure-applicationsettings-with-a-feature/</link>
		<comments>http://oricode.wordpress.com/2008/03/05/spwebconfigmodification-configure-applicationsettings-with-a-feature/#comments</comments>
		<pubDate>Wed, 05 Mar 2008 14:51:53 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Coding]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Configuration]]></category>

		<category><![CDATA[Feature]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=14</guid>
		<description><![CDATA[Features are one of the coolest additions in WSS 3.0 if not the most. Not only they help us as software developers to encapsulate our code in redistributable packages but also simplify mainteinance tasks and deployment to server administrators. Ultimately, we&#8217;d like to be able to deploy our site definition with just a walk-through installer that [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Features are one of the coolest additions in WSS 3.0 if not the most. Not only they help us as software developers to encapsulate our code in redistributable packages but also simplify mainteinance tasks and deployment to server administrators. Ultimately, we&#8217;d like to be able to deploy our site definition with just a walk-through installer that would activate the required features.</p>
<p>Quite often I have to make some changes in the web.config files of the web applications where my solutions are to be deployed. <em>Manifest.xml </em>files of Sharepoint Solutions helps us with this task providing us with some easy ways to alter the web.config files, unfortunately, we are limited at registering safe controls and alter security policies which sometimes is not enough.</p>
<p>What I usually want to do, is to deploy a particular <em>applicationSettings</em> section for an assembly used in my solution, in this example, I have an assembly that uses an <em>httpHandler </em>to retrieve some Xml and I have configured the url of the handler in a settings file, this way, I&#8217;ll be able to change it if needed. This is the settings sections I need to include in the web.config file of the web application in order to do that:</p>
<p>&lt;configuration&gt;<br />
  &lt;configSections&gt;<br />
    &lt;sectionGroup name=&#8221;applicationSettings&#8221; type=&#8221;System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&#8243;&gt; &lt;section name=&#8221;MyAssembly.Properties.Settings&#8221; type=&#8221;System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&#8243; requirePermission=&#8221;false&#8221; /&gt;&lt;/sectionGroup&gt;<br />
  &lt;/configSections&gt;<br />
  &lt;applicationSettings&gt;<br />
    &lt;MyAssembly.Properties.Settings&gt;<br />
      &lt;setting name=&#8221;HttpHandlerUrl&#8221; serializeAs=&#8221;String&#8221;&gt;<br />
        &lt;value&gt;http://oricode.wordpress.com&lt;/value&gt;<br />
      &lt;/setting&gt;<br />
    &lt;/MyAssembly.Properties.Settings&gt;<br />
  &lt;/applicationSettings&gt;<br />
&lt;/configuration&gt;</p>
<p>There is no easy way to automate this process. The usual procedure would be to deploy the solution and then ask the administrators to change the web.config files of all the involved web applications manually but this is what I was trying to avoid. I decided to take a look at the new <em>SPWebConfigModification </em>objects in the <em>SPWebApplication </em>object and use them in a Feature Receiver that would modify the web.config file.</p>
<p>At first sight, it seems that this objects are specially suited for this task and that it would be an easy thing to do, but it is not. <em>SPWebConfigModification </em>class is usefull when adding and replacing sections in the configuration files but it&#8217;s not easy to modify existing ones by adding new child sections. Basically, what you do is to select a section by providing a xpath and provide the new xml value for the section, but what happens when we don&#8217;t want to replace the section but just append new child nodes to it ?</p>
<p>For example in my case, I had to consider the following scenarios:</p>
<p><strong>1.</strong> The webconfig file didn&#8217;t had the applicationSettings section defined (which is something very usual)<br />
<strong>2.</strong> The webconfig file already had the applicationSettings section defined (by another assembly) and I had to append the new section for my assembly in it</p>
<p>So I couldn&#8217;t just replace the whole section with the xml for my assembly because this might have an impact in any already configured assembly used in the web application that relied in the applicationSettings section.</p>
<p>So here is the code of my <em>FeatureActivated </em>event where I would handle those modifications:</p>
<p>Initialization:</p>
<pre name="code" class="csharp">

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite site = (SPSite)properties.Feature.Parent;
    SPWebApplication webApp = site.WebApplication;
</pre>
<p>Since there is no way to know if the applicationSettings section is already defined in the web.config file, my solution is to execute the modifications as if the section was defined and if that rises an exception, it would mean that it is not and then I could add it. I know it is not an elegant approach and I&#8217;d really appreciate it if anybody could come up with a better solution !</p>
<pre name="code" class="csharp">

try
{
    webApp.WebConfigModifications.Clear();

    SPWebConfigModification configMod = new SPWebConfigModification();
    configMod.Name = @&quot;section[@name=&#039;MyAssembly.Properties.Settings&#039;]&quot;;
    configMod.Path = &quot;configuration/configSections/sectionGroup[@name=&#039;applicationSettings&#039;]&quot;;
    configMod.Sequence = 0;
    configMod.Owner = properties.Feature.DefinitionId.ToString();
    configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    configMod.Value = &quot;&quot;;
    webApp.WebConfigModifications.Add(configMod);

    configMod = new SPWebConfigModification();
    configMod.Name = @&quot;MyAssembly.Properties.Settings&quot;;
    configMod.Path = &quot;configuration/applicationSettings&quot;;
    configMod.Sequence = 0;
    configMod.Owner = properties.Feature.DefinitionId.ToString();
    configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    configMod.Value = &quot;&quot; +
                            &quot;&quot; +
                                &quot;http://oricode.wordpress.com&quot; +
                            &quot;&quot; +
                       &quot;&quot;;
    webApp.WebConfigModifications.Add(configMod);

    webApp.Farm.Services.GetValue().WebConfigModifications.Clear();
    webApp.Update();
    webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
}
</pre>
<p>If the section was already defined, the previous code would launch a &lt;em&gt;SPException&lt;/em&gt;. Unfortunately, since the exception is not better typed, there is no way to ensure that the error is caused by the applicationSettings section not being configured (we could always read the exception message that will tell us if so). So if the exception is raised, we have to add the sections as new &lt;em&gt;SPWebConfigModification&lt;/em&gt; objects, the previous modifications were added to the &lt;em&gt;WebConfigModifications&lt;/em&gt; collection of the &lt;em&gt;SPWebApplication&lt;/em&gt; object so there&#8217;s no need to add them again.</p>
<pre name="code" class="csharp">

catch (SPException ex)
{
    SPWebConfigModification configMod = new SPWebConfigModification();
    configMod.Name = @&quot;sectionGroup[@name=&#039;applicationSettings&#039;]&quot;;
    configMod.Path = &quot;configuration/configSections&quot;;
    configMod.Sequence = 0;
    configMod.Owner = Guid.NewGuid().ToString();
    configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    configMod.Value = &quot; &quot; +
                      &quot;&quot;;
    webApp.WebConfigModifications.Insert(0, configMod);

    configMod = new SPWebConfigModification();
    configMod.Name = @&quot;applicationSettings&quot;;
    configMod.Path = &quot;configuration&quot;;
    configMod.Sequence = 0;
    configMod.Owner = Guid.NewGuid().ToString();
    configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    configMod.Value = &quot;&quot;;
    webApp.WebConfigModifications.Insert(0, configMod);

    webApp.Update();
    webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
}
</pre>
<p>Note that this two last configuration sections have their <em>Owner</em> property set to a random Guid string. This is because the owner property is used in the feature deactivating event for removing the web.config changes, however, I can&#8217;t remove the applicationSettings sections because after my feature is activated, some other application settings might be registered in those sections by the server administrator and If then my feature was deactivated, all of them would be deactivated as well.</p>
<p>There are also a lot of issues I&#8217;ve faced when using <em>SPWebConfigModification</em> objects, like modifications that are persisted in the WebConfigModifications collections of the webApplication object before any call to the update() method is made (this is why I&#8217;ve set the Clear() methods of the collection at the start of the code) and other similar issues. Feel free to comment any strange behaviour you might find and I&#8217;ll try to help you If possible.</p>
<p>And that&#8217;s it, activating this feature will modify the web.config file of the web application as desired. However, I hope in future releases of Sharepoint object model we will see a better way to achieve this.</p>
<p>To end, I&#8217;d like to point that this solution should be tested in a farm deployment where multiple servers are involved, use with caution in that scenarios !</p>
<p>That&#8217;s all for now <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> as always, comments are welcome !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=14&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/03/05/spwebconfigmodification-configure-applicationsettings-with-a-feature/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Sharepoint: publish a webservice with your solution</title>
		<link>http://oricode.wordpress.com/2008/02/29/sharepoint-publish-a-webservice-with-your-solution/</link>
		<comments>http://oricode.wordpress.com/2008/02/29/sharepoint-publish-a-webservice-with-your-solution/#comments</comments>
		<pubDate>Fri, 29 Feb 2008 07:15:07 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Coding]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[Solution]]></category>

		<category><![CDATA[Webservices]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=13</guid>
		<description><![CDATA[In this article I&#8217;ll cover how can you publish a WebService with your solution that will be accessible at every site in all the web applications where the solution is deployed. To keep thing simple, I&#8217;ve chosen a simple Helloworld webservice but with this approach we could publish any webservice or .aspx pages or a httpHandler [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article I&#8217;ll cover how can you publish a WebService with your solution that will be accessible at every site in all the web applications where the solution is deployed. To keep thing simple, I&#8217;ve chosen a simple Helloworld webservice but with this approach we could publish any webservice or .aspx pages or a <a href="http://oricode.wordpress.com/2008/02/07/3/" title="httpHandler">httpHandler </a></p>
<p>What we will do is to publish the service in the <em>_vti_bin </em>sharepoint folder of our site. To do this, we must first copy the .asmx file of the service in the <em>Common FilesMicrosoft Sharedweb server extensions12ISAPI </em>folder of our server.</p>
<p><font size="2">&lt;%<font size="2" color="#0000ff">@</font><font size="2"> </font><font size="2" color="#a31515">WebService</font><font size="2"> </font><font size="2" color="#ff0000">Language</font><font size="2" color="#0000ff">=&#8221;c#&#8221;</font><font size="2"> </font><font size="2" color="#ff0000">Class</font><font size="2" color="#0000ff">=&#8221;MyAssembly.Services.HelloWorldService,MyAssembly.Services&#8221;</font><font size="2">%&gt;</font></font></p>
<p>This was the .asmx file we want to distribute and following is the <em>.DDF</em> file from which we&#8217;ll generate the solution, I&#8217;d like to show that you could also publish a <em>web.config </em>file for the <em>_vti_bin/MyAssembly </em>folder, we would want to do so if, for example, were deploying an httpHandler instead of a webservice or if we need to configure some <em>AppSettings </em>parameters.</p>
<p><font size="2">; Solution.DDF<br />
FeaturesISAPIMyAssemblyweb.config ISAPIMyAssemblyweb.config<br />
FeaturesISAPIMyAssemblyHerramientas.asmx ISAPIMyAssemblyHelloWorldService.asmx<br />
ServicesbinDebugMyAssembly.Services.dll MyAssembly.Services.dll</font></p>
<p>Then we must define the <em>manifest.xml</em> file used in the solution deployment:</p>
<p><font size="2" color="#0000ff">&lt;</font><font size="2" color="#a31515">RootFiles</font><font size="2" color="#0000ff">&gt;</font><br />
<font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">RootFile</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Location</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">ISAPIMyAssemblyweb.config</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt;</font></font><br />
<font size="2" color="#0000ff"><font size="2" color="#0000ff">&lt;</font></font><font size="2" color="#0000ff"> </font><font size="2" color="#a31515">RootFile</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Location</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">ISAPIMyAssemblyHelloWorldService.asmx</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt;</font><br />
<font size="2" color="#0000ff">&lt;/<font size="2" color="#a31515">RootFiles</font><font size="2" color="#0000ff">&gt;</font></font></p>
<p><font size="2" color="#0000ff">&lt;</font><font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;</font><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">Assembly</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">DeploymentTarget</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">WebApplication</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Location</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">MyAssembly.Services.dll</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt;&lt;/<font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;</font></font></font></p>
<p>Remember to set the appropiate assembly permission at the <em>CodeAccessSecurity </em>section of the <em>manifest.xml </em>file if not running under Full Trust mode or not deploying the assembly in the GAC.</p>
<p>Finally, here is the easy code of our Helloworld service:</p>
<pre name="code" class="csharp">

namespace MyAssembly.Services
{
    [WebService(Namespace = &quot;http://MyAssembly.com/&quot;)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class HelloWorldService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return &quot;Greetings from this Service !&quot;;
        }

    }
}
</pre>
<p>Now, after deploying the solution we can access the webservice adding <em>_vti_bin/MyAssembly/HelloWorldService.asmx </em>at our site url (for those sites we have deployed the solution to !). However, If we have deployed the solution in the GAC, the service should be able to all the sites in the server.</p>
<p>That&#8217;s all for now ! As always, feel free to comment anything you might find interesting !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=13&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/29/sharepoint-publish-a-webservice-with-your-solution/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Deploy a XML file in your Sharepoint Solution to the Web Application Folder</title>
		<link>http://oricode.wordpress.com/2008/02/27/deploy-a-xml-file-in-your-sharepoint-solution-to-the-web-application-folder/</link>
		<comments>http://oricode.wordpress.com/2008/02/27/deploy-a-xml-file-in-your-sharepoint-solution-to-the-web-application-folder/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 16:58:27 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Solution]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=12</guid>
		<description><![CDATA[This is a small trick I&#8217;ve been using these days in a Sharepoint Solution in order to add a xml file with some data which some webpart will read later on a Sharepoint site and make use of it. There are many ways to accomplish this each one with it&#8217;s benefits and drawbacks.
The first approach [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is a small trick I&#8217;ve been using these days in a Sharepoint Solution in order to add a xml file with some data which some webpart will read later on a Sharepoint site and make use of it. There are many ways to accomplish this each one with it&#8217;s benefits and drawbacks.</p>
<p>The first approach I thought of was to deploy the xml file in the _layouts folder and then query the data using a <em>WebClient </em>request from my webpart, the problem I found is that if anonymous access wasn&#8217;t enabled for the site, the request failed with a <em>401 Unauthorized </em>exception because the ASP.Net credentials where the ones used by default to access the resource. One solution was to enable the impersonation at the web.config file of the application and then, the current user&#8217;s credentials would be used instead, but as I didn&#8217;t know where my solution would be deployed and didn&#8217;t have any control over the web.config file configuration, I rejected this approach.</p>
<p>Finally, I decided to deploy locally the xml file in the bin folder of the application and then accessing it with a simple <em>StreamReader</em>. The first problem was how to deploy the file ? Finally, I found the small trick I was talking about, you can deploy any file from a Sharepoint Solution in the <em>bin </em>folder of the web application just by doing the same as you do with a normal assembly .dll file, with the <font size="2" color="#0000ff">&lt;</font><font size="2" color="#a31515">Assembly</font><font size="2" color="#0000ff">&gt;</font> tag in the manifest.xml file:</p>
<p><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;&lt;</font><font size="2" color="#a31515">Assembly</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">DeploymentTarget</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">WebApplication</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Location</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">MyData.xml</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt;&lt;/</font><font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;</font></font></p>
<p>When the Solution is deployed, the xml file will be copied to all the <em>bin </em>folders of the selected web application. This raises the obvious drawback of this approach: There&#8217;s one xml file for each web application and there&#8217;s no easy way to globally manage them.<br />
Since we will be accessing the xml file from our webpart, and assuming we haven&#8217;t set our trust level to Full (because we know it&#8217;s a bad thing to do!), we must grant our assembly the<em> FileIOPermission  </em>in order to be able to read the file. We can do this in the manifest.xml with the following section:</p>
<p><font size="2" color="#0000ff"><font size="2" color="#0000ff"><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">CodeAccessSecurity</font><font size="2" color="#0000ff">&gt;</font></font><font size="2" color="#0000ff"><font size="2" color="#0000ff">&lt;</font><font size="2" color="#a31515">PolicyItem</font><font size="2" color="#0000ff">&gt;</font><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">PermissionSet</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">class</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">NamedPermissionSet</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">version</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">1</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Description</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">Permission set for OurAssembly</font><font size="2">&#8220;</font><font size="2" color="#0000ff">&gt;&lt;</font></font></font><font size="2" color="#0000ff"><font size="2" color="#a31515">IPermission</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">class</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">System.Security.Permissions.FileIOPermission</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">version</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">1</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Unrestricted</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">true</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt; </font><font size="2" color="#0000ff">&lt;/<font size="2" color="#a31515">PermissionSet</font><font size="2" color="#0000ff">&gt;&lt;</font></font><font size="2" color="#0000ff"><font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;</font><font size="2" color="#0000ff">&lt;<font size="2" color="#a31515">Assembly</font><font size="2" color="#0000ff"> </font><font size="2" color="#ff0000">Name</font><font size="2" color="#0000ff">=</font><font size="2">&#8220;</font><font size="2" color="#0000ff">OurAssembly</font><font size="2">&#8220;</font><font size="2" color="#0000ff"> /&gt;&lt;/</font></font></font></font></font><font size="2" color="#0000ff"> </font><font size="2" color="#0000ff"><font size="2" color="#a31515">Assemblies</font><font size="2" color="#0000ff">&gt;</font><font size="2" color="#0000ff">&lt;/<font size="2" color="#a31515">PolicyItem</font><font size="2" color="#0000ff">&gt;&lt;/<font size="2" color="#a31515">CodeAccessSecurity</font><font size="2" color="#0000ff">&gt;</font></font></font></font></font></p>
<p>Please note that I&#8217;ve set the <em>unrestricted=true </em>attribute just to keep it simple but you should set the Read attribute to the appropiate folder.Now, we can read the file from our webpart:</p>
<pre name="code" class="csharp">

string loc = HttpContext.Current.Server.MapPath(&quot;/&#038;quot <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> + &quot;bin\&quot;;
using (StreamReader reader = new StreamReader(loc + @&quot;MyData.xml&quot;))
{
    XDoc = XDocument.Load(reader, LoadOptions.None);
}
</pre>
<p>And that&#8217;s all, with this approach we can deploy all kinds of xml data and even .dll configuration files or any other localresource you might need. I hope it&#8217;s helpful and don&#8217;t forget to leave a comment if so !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=12&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/27/deploy-a-xml-file-in-your-sharepoint-solution-to-the-web-application-folder/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Ajax webpart: Register scripts on UpdatePanel postbacks</title>
		<link>http://oricode.wordpress.com/2008/02/25/ajax-webpart-register-scripts-on-updatepanel-postbacks/</link>
		<comments>http://oricode.wordpress.com/2008/02/25/ajax-webpart-register-scripts-on-updatepanel-postbacks/#comments</comments>
		<pubDate>Mon, 25 Feb 2008 10:06:00 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Accessibility]]></category>

		<category><![CDATA[Coding]]></category>

		<category><![CDATA[RIA]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[Javascript]]></category>

		<category><![CDATA[UpdatePanel]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=11</guid>
		<description><![CDATA[These days I&#8217;m developing custom ajax enabled webparts for a sharepoint solution. I&#8217;ve created a base webpart class named AjaxEnabledWebpart from which all the webparts inherit. This webpart has an updatepanel control where all the child webparts are supposed to create the controls they need so finally, everycontrol is rendered inside the updatepanel and the [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>These days I&#8217;m developing custom ajax enabled webparts for a sharepoint solution. I&#8217;ve created a base webpart class named <em>AjaxEnabledWebpart </em>from which all the webparts inherit. This webpart has an updatepanel control where all the child webparts are supposed to create the controls they need so finally, everycontrol is rendered inside the updatepanel and the webpart has the expected asp.net ajax behaviour of partial rendering the pages. Some of the webparts have to render content created dinamically by javascript code as you will see later in the code, in this case, content is rendered this way because we are supposed to give an accessible front end in our webpart (this is supporting non-script enabled browsers) so we are using the typical &lt;noscript&gt;&lt;script&gt; tag approach. However, the problem we faced is that the content rendering script code (or any script code at all) was not executed during Ajax postbacks of the webpart. The solution we found to this problem was to register the scripts with the <em>Sys.WebForms.PageRequestManager.getInstance().add_endRequest()</em> function. Following is the code we used. First, for reference only, I&#8217;ll post the main code of the <em>AjaxEnabledWebpart</em> which somebody might find useful</p>
<pre name="code" class="csharp">

protected override void CreateChildControls()
{
    base.CreateChildControls();

    EnsurePanelFix();

    _updatePanel = new UpdatePanel();

    _scriptHandler = ScriptManager.GetCurrent(this.Page);
    if (_scriptHandler == null)
    {
        //no script manager registered
        _scriptHandler = new ScriptManager();
        _scriptHandler.ID = &quot;scriptManager&quot;;
        this.Controls.Add(_scriptHandler);
    }

    _updatePanel.ID = &quot;updatePanel_&quot;;
    _updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
    _updatePanel.ChildrenAsTriggers = true;

    CreatePanelControls(_updatePanel.ContentTemplateContainer.Controls);

    this.Controls.Add(_updatePanel);
}

protected virtual void CreatePanelControls(ControlCollection PanelControls)
{
}
</pre>
<p>The only relevant code from the <em>AjaxEnabledWebpart</em> is the <em>CreateChildControls</em> method, which creates the <em>UpdatePanel</em> control and calls the virtual method <em>CreatePanelControls</em> passing as a parameter the control collection where child pages are supposed to add the controls. Also, you can find the <em>EnsurePanelFix</em> implementation on my previous post at <a target="_blank" href="http://oricode.wordpress.com/2008/02/20/ajax-enabled-webpart-not-working-on-second-postback/">this link</a>After that, here is the code of a custom <em>HtmlTable</em> used in some webparts which contents are rendered using javascript code (if scripting is enabled in the client browser). The posted code is a function which returns the html code to be inserted in a cell&#8217;s <em>InnerHtml</em> property of a table:</p>
<pre name="code" class="csharp">

private string _getSelectAllHtml(HtmlTableCell cell)
{
    string ret = &quot;&quot;;

    ret += &quot;&quot; +
                &quot;select all&quot; +
             &quot;&quot; +
             &quot;&quot; +
                &quot;// &quot; +
            &quot;&quot; +
           &quot;&quot;;

    string fn = &quot;&quot; +
                    &quot;//&lt;![CDATA[ n&quot; +
                        &quot;function _loadSelectAllHeader() { &quot; +
                            &quot;cab = &#039;&lt;a href=&quot;#&quot; title=&quot;CellTitle&quot;&gt;&quot; +
                            &quot;&lt;img src=&quot;_layouts/img/selectall.gif&quot; alt=&quot;select all&quot;&gt;&#039;;&quot; +
                            &quot;var capa = document.getElementById(&quot;&quot; + cell.Attributes[&quot;Id&quot;] + &quot;&quot;);&quot; +
                            &quot;capa.innerHTML = cab;n&quot; +
                        &quot; }&quot; +
                    &quot;//]]&gt; &quot; +
                &quot;&quot;;

    Page.ClientScript.RegisterClientScriptBlock(typeof(ResultsTableMod47),
                                &quot;_loadSelectAllHeader&quot;,
                                fn);

    Page.ClientScript.RegisterStartupScript(typeof(ResultsTableMod47),
                                &quot;initRequestScriptHandler_loadSelectAllHeader&quot;,
                                &quot;Sys.WebForms.PageRequestManager.getInstance().add_endRequest(_loadSelectAllHeader);&quot;);

    return ret;
}
</pre>
<p>The relevant lines of the code are the calls to <em>RegisterClientScriptBlock</em> and <em>RegisterStartupScript</em> methods. The first one register our content-rendering script while the second one adds this function to the end_request handler of the <em>PageRequestManager</em> instance. This will ensure that the script is called after each Ajax postback of the pages.Further scripts can be registered in the end_request handler by calling the <em>add_endRequest</em> method for each script we want to be executed after a postback. However, we have to considered that this script will be executed for all the postbacks and not only for the ones generated by this webpart&#8217;s updatepanel control, so if more than one updatepanel is present on the page, we might have to include some checking at the startup of our code to ensure that our script must be executed. In this case this was not necessary since the script could be executed again without any problem.</p>
<p>That&#8217;s all for now ! I hope it&#8217;s useful&#8230;. coments are welcome <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=11&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/25/ajax-webpart-register-scripts-on-updatepanel-postbacks/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>

		<media:content url="_layouts/img/selectall.gif" medium="image">
			<media:title type="html">select all</media:title>
		</media:content>
	</item>
		<item>
		<title>Ajax enabled webpart not working on second postback</title>
		<link>http://oricode.wordpress.com/2008/02/20/ajax-enabled-webpart-not-working-on-second-postback/</link>
		<comments>http://oricode.wordpress.com/2008/02/20/ajax-enabled-webpart-not-working-on-second-postback/#comments</comments>
		<pubDate>Wed, 20 Feb 2008 15:33:53 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Coding]]></category>

		<category><![CDATA[RIA]]></category>

		<category><![CDATA[Sharepoint]]></category>

		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=10</guid>
		<description><![CDATA[Trying to develope an Ajax webpart with aspx.net 2.0 I came up with this msdn example  which seemed to be exactly what I was looking for. I followed the steps suggested by the article but I ended up with some weird behaviour from the webpart when finally deployed in my Sharepoint server.
Apparently everything was working [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Trying to develope an Ajax webpart with aspx.net 2.0 I came up with this <a target="_blank" href="http://msdn2.microsoft.com/en-us/library/bb861877.aspx" title="msdn example">msdn example</a>  which seemed to be exactly what I was looking for. I followed the steps suggested by the article but I ended up with some weird behaviour from the webpart when finally deployed in my Sharepoint server.</p>
<p>Apparently everything was working as expected and when I clicked the webpart the first time, the ajax method was correctly executed and the &#8220;Hello! XXX&#8221; text succesfully displayed. However, clicking again the button didn&#8217;t seem to do anything, also, other page actions that should submit the form and do some action (like the &#8220;Edit Page&#8221; item from the &#8220;Site Actions&#8221; menu) stopped working.</p>
<p>I finally found that the problem was in the <em>EnsurePanelFix </em>function of the example which was not working as expected</p>
<pre name="code" class="csharp">

private void EnsurePanelFix()
{
   if (this.Page.Form != null)
   {
     String fixupScript = @&quot;
     _spBodyOnLoadFunctionNames.push(&quot;&quot;_initFormActionAjax&quot;&quot;);
     function _initFormActionAjax()
     {
       if (_spEscapedFormAction == document.forms[0].action)
       {
         document.forms[0]._initialAction =
         document.forms[0].action;
       }
     }
     var RestoreToOriginalFormActionCore =
       RestoreToOriginalFormAction;
     RestoreToOriginalFormAction = function()
     {
       if (_spOriginalFormAction != null)
       {
         RestoreToOriginalFormActionCore();
         document.forms[0]._initialAction =
         document.forms[0].action;
       }
     }&quot;;
   ScriptManager.RegisterStartupScript(this,
     typeof(SayHelloWebPart), &quot;UpdatePanelFixup&quot;,
     fixupScript, true);
   }
}
</pre>
<p>So what I did is to provide my own implementation of that function. What we needed is to invalidate the onSubmit wrapper that Sharepoint calls in order to ensure some callback scenarios, this can be done by setting to true the <em>_spSuppressFormOnSubmitWrapper</em> variable so I replaced the original function by the following implementation</p>
<pre name="code" class="csharp">

private void EnsurePanelFix()
        {
              ScriptManager.RegisterStartupScript
                (this,
                 typeof(AjaxEnabledWebpart),
                 &quot;UpdatePanelFixup&quot;,
                 &quot;_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;&quot;,
                 true);
}
</pre>
<p>And that&#8217;s it ! my Ajax webpart is working properly no matter how many times we click the Hello World ! button <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=10&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/20/ajax-enabled-webpart-not-working-on-second-postback/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Exchange Server Event Sink in c#</title>
		<link>http://oricode.wordpress.com/2008/02/15/exchange-server-event-sink-in-c/</link>
		<comments>http://oricode.wordpress.com/2008/02/15/exchange-server-event-sink-in-c/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 12:08:36 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[COM+]]></category>

		<category><![CDATA[Coding]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[Exchange]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=9</guid>
		<description><![CDATA[I&#8217;ve been asked to make some minor modifications to a component I developed some time ago. Reviewing the code, I thought it would be a nice topic to talk about it.
This component is an Event Sink which is supposed to be installed in an Exchange Server that parses all incoming email messages (depending on the rules [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;ve been asked to make some minor modifications to a component I developed some time ago. Reviewing the code, I thought it would be a nice topic to talk about it.</p>
<p>This component is an <em>Event Sink </em>which is supposed to be installed in an <em>Exchange Server </em>that parses all incoming email messages (depending on the rules defined on it&#8217;s registration, but this is a topic I&#8217;ll leave for another post!) and check if they contain some tag in it&#8217;s subject field. If so, it does some processing and changes their subject by adding a #OK or #ERROR tag depending on the process outcome. This tag is meant to be used by the Outlook to determinate on which folder should the message be placed (defined by some Outlook rule by the client)</p>
<p>What we need in order to create an Exchange event sink is a class that implements an interface defined in th COM+ component <em>cdoex.dll </em>which we can find in the <em>bin </em>folder of our exchange server. In order to do that we must build the <em>interop </em>.net assembly that will wraps us this library in managed code. We can do that with the following call to <em>tlbimp</em></p>
<p><em>sn –k sn.key <br />
tlbimp cdoex.dll /keyfile:sn.key /out:Interop.cdoex.dll /namespace:CDO </em></p>
<p>Then we add this reference to our assembly and creates a class that implements the <em>ISMTPOnArrival </em>interface. There are a lot of other interfaces in the <em>cdoex </em>library depending on when do we want our event sink to be executed, for this example I needed to be when a message arrived and this is why I choosed this particular interface. Here is the class declaration:</p>
<pre name="code" class="csharp">

[Guid(&quot;021079E3-6FCB-491b-A78F-81BC31A1EC9D&quot;)]
[ComVisible(true)]
public class MyEventSink : ISMTPOnArrival, IEventIsCacheable
</pre>
<p>So following is the implementation of the <em>ISMTPOnArrival </em>interface:</p>
<pre name="code" class="csharp">

void ISMTPOnArrival.OnArrival(IMessage Msg, ref CdoEventStatus EventStatus)
{
    try
    {
        //Do message processing
        //Here we can access all message&#039;s properies
        //for example the message body: Msg.TextBody

        //Change subject to OK
        Msg.Fields[&quot;urn:schemas:mailheader:subject&quot;].Value = &quot;#OK# &quot; + Msg.Subject;

    }
    catch (Exception)
    {
        //Change subject to ERROR
        Msg.Fields[&quot;urn:schemas:mailheader:subject&quot;].Value = &quot;#ERROR# &quot; + Msg.Subject;
    }
    finally
    {
        //Save message properties
        Msg.Fields.Update();
        Msg.DataSource.Save();
        EventStatus = CDO.CdoEventStatus.cdoRunNextSink;
    }
}
</pre>
<p>Then, all we need to do is register the .dll in the Exchange server but this is a topic I&#8217;ll cover in another post ! As always, feel free to leave any comment !</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=9&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/15/exchange-server-event-sink-in-c/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
		<item>
		<title>Active Directory Role Provider</title>
		<link>http://oricode.wordpress.com/2008/02/14/active-directory-role-provider/</link>
		<comments>http://oricode.wordpress.com/2008/02/14/active-directory-role-provider/#comments</comments>
		<pubDate>Thu, 14 Feb 2008 12:46:11 +0000</pubDate>
		<dc:creator>oricode</dc:creator>
		
		<category><![CDATA[Coding]]></category>

		<category><![CDATA[Security]]></category>

		<category><![CDATA[Active Directory]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[Role Provider]]></category>

		<guid isPermaLink="false">http://oricode.wordpress.com/?p=8</guid>
		<description><![CDATA[Having an asp.net application with forms authentication enabled authenticate users against an Active Directory is an easy thing. All you have to do is use an ActiveDirectoryMembershipProvider and configure it&#8217;s connectionString property in the web.config file.
Retrieving user&#8217;s role information is a different thing. One would expect an ActiveDirectoryRoleProvider to connect to the Active Directory and retrieve the current [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Having an asp.net application with forms authentication enabled authenticate users against an Active Directory is an easy thing. All you have to do is use an <em>ActiveDirectoryMembershipProvider </em>and configure it&#8217;s <em>connectionString </em>property in the web.config file.</p>
<p>Retrieving user&#8217;s role information is a different thing. One would expect an <em>ActiveDirectoryRoleProvider </em>to connect to the Active Directory and retrieve the current user&#8217;s group information, however such object doesn&#8217;t exist.</p>
<p>What follows is a custom implementation of this role provider that queries an Active Directory and retrieves user&#8217;s group information.</p>
<p>First you have to define a class that inherits from <em>System.Web.Security.RoleProvider </em>in order to use it as your application role provider</p>
<pre name="code" class="csharp">

public class CustomActiveDirectoryRoleProvider : System.Web.Security.RoleProvider
</pre>
<p>Next, you should retrieve the configuration information from the web.config file in the <em>Initialize </em>method</p>
<pre name="code" class="csharp">

private string _loginProperty = &quot;sAMAccountName&quot;;
private string _connectionString = string.Empty;
private string _applicationName = string.Empty;

public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
    _connectionString = config[&quot;connectionStringName&quot;];
    _applicationName = config[&quot;applicationName&quot;];
    if (!string.IsNullOrEmpty(config[&quot;attributeMapUsername&quot;]))
        _loginProperty = config[&quot;attributeMapUsername&quot;];
    base.Initialize(name, config);
}
</pre>
<p>At last, whe have to implement <em>GetRolesForUser </em>method where we will get all the groups where the current user belongs to (other methods such as <em>IsUserInRole </em>can be implemented later by querying the resultset from <em>GetRolesForUser</em>)</p>
<pre name="code" class="csharp">

public override string[] GetRolesForUser(string userName)
{
    List allRoles = new List();

    DirectoryEntry root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[_connectionString].ConnectionString);
    foreach (DirectoryEntry entry in root.Children)
    {
        if (entry.SchemaClassName.ToLower() == &quot;group&#038;quot <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
        {
            object members = entry.Invoke(&quot;Members&quot;, null);
            foreach (object member in (IEnumerable)members)
            {
                DirectoryEntry child = new DirectoryEntry(member);

                if (_getProperty(child, _loginProperty) == userName)
                {
                    string name = _getProperty(entry, &quot;name&quot;);
                    allRoles.Add(name != &quot;&quot; ? name : entry.Name);
                }
            }

        }
    }

    return allRoles.ToArray();
}
</pre>
<p>Finally I provide the <em>_getProperty </em>function source code</p>
<pre name="code" class="csharp">

private string _getProperty(DirectoryEntry entry, string propertyName)
{
    if ((entry.Properties[propertyName] != null) &amp;&amp;
        (entry.Properties[propertyName].Value != null))
    {
        return entry.Properties[propertyName].Value.ToString();
    }

    return &quot;&quot;;
}
</pre>
<p>And that&#8217;s it ! hope it&#8217;s useful and don&#8217;t forget to leave a comment if you think so <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/oricode.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/oricode.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/oricode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/oricode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/oricode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/oricode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/oricode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/oricode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/oricode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/oricode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/oricode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/oricode.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=oricode.wordpress.com&blog=2786525&post=8&subd=oricode&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://oricode.wordpress.com/2008/02/14/active-directory-role-provider/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/oricode-128.jpg" medium="image">
			<media:title type="html">oricode</media:title>
		</media:content>
	</item>
	</channel>
</rss>