Thursday, September 27, 2007

Creating Media and Flash Controls in MOSS

Media Control

Please note that this code is taken directly from Microsoft's website: http://msdn2.microsoft.com/en-us/library/aa981226.aspx I modified the render output for streaming and cross-browser compatibility


 

The Media Class File should look something like this:

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.Publishing.WebControls;

using Microsoft.SharePoint.Publishing.Fields;

namespace VZ.Controls.CustomFieldControls

/// A Field control that binds to fields of type LinkField and is

/// specialized to select and render embedded media files.

/// The RenderFieldForDisplay function generates the HTML markup to

/// display the media file. The MediaSelector control is

/// used at edit time to allow authors to select a media file in

/// the Asset Picker dialog box.

{

public
class
MediaPlayerFieldControl : BaseFieldControl

{

private
MediaSelector mediaSelector = new
MediaSelector();

public MediaPlayerFieldControl()

{

}

/// Gets and sets the value in the edit controls

public
override
object Value

{

get

{

LinkFieldValue mediaUrlValue = new
LinkFieldValue();

mediaUrlValue.NavigateUrl =

this.mediaSelector.MediaUrl;

mediaUrlValue.Text =

LinkFieldValue.GetDefaultDisplayText(mediaUrlValue.NavigateUrl);

return mediaUrlValue;

}

set

{

LinkFieldValue mediaLinkFieldValue =

value
as
LinkFieldValue;

if (null != mediaLinkFieldValue)

{

this.mediaSelector.MediaUrl =

mediaLinkFieldValue.NavigateUrl;

}

else

{

this.mediaSelector.MediaUrl = String.Empty;

}

}

}

/// Get the default name used to find the template and

/// control for the MediaPlayerSelector in the control

/// template ASCX files.

protected
override
string DefaultTemplateName

{

get { return
"MediaPlayerFieldControl"; }

}

private
const
string AllowExternalUrlsViewStateKey = "AllowExternalUrls";

/// A flag that determines whether to allow saving of external

/// media URLs.

public
bool AllowExternalUrls

{

get

{

// Return true by default if not already in view state.

if (ViewState[AllowExternalUrlsViewStateKey] == null)

{

return
true;

}

return (bool)ViewState[AllowExternalUrlsViewStateKey];

}

set

{

ViewState[AllowExternalUrlsViewStateKey] = value;

}

}

/// Creates the edit control when not in display mode.

protected
override
void CreateChildControls()

{

base.CreateChildControls();

if (this.ControlMode != SPControlMode.Display)

{

MediaSelector mediaSelectorInTemplate =

this.TemplateContainer.FindControl(this.TemplateName)

as
MediaSelector;

if (null == mediaSelectorInTemplate)

{

// No media selector was found in the control

// template ASCX files. Add the default selector.

this.Controls.Add(this.mediaSelector);

}

else

{

// Get the media selector from the control

// template ASCX file.

mediaSelectorInTemplate.MediaUrl =

this.mediaSelector.MediaUrl;

this.mediaSelector = mediaSelectorInTemplate;

}

}

}

/// Gets the current value for the media URL as stored

/// in the list item.

private
string itemFieldValueMediaUrl

{

get

{

LinkFieldValue currentLinkValue =

this.ItemFieldValue as
LinkFieldValue;

if (null != currentLinkValue)

{

return currentLinkValue.NavigateUrl;

}

else

{

return
String.Empty;

}

}

}

/// Renders the current list item value for the media URL

/// with embedded media player markup.

///
<param name="output"></param>

protected
override
void

RenderFieldForDisplay(System.Web.UI.HtmlTextWriter output)

{

if (!String.IsNullOrEmpty(this.itemFieldValueMediaUrl))

{

output.Write(MediaRenderingUtilities.GetMediaPlayerHtmlMarkup(this.itemFieldValueMediaUrl));

}

}

/// Verifies that the MediaUrl is valid.

public
override
void Validate()

{

base.Validate();

if (this.IsValid)

{

LinkFieldValue currentMediaUrlValue =

this.Value as
LinkFieldValue;

if (currentMediaUrlValue ==

null || String.IsNullOrEmpty(currentMediaUrlValue.NavigateUrl))

{

// Ensure the field is not required.

if (this.Field != null && this.Field.Required)

{

this.IsValid = false;

this.ErrorMessage =

"This field is required and must contain a media file URL.";

return;

}

else

{

// The field is empty and not required.

// The data is valid.

return;

}

}

// Perform validation on the media file URL.

HtmlValidationContext validationContext =

new
HtmlValidationContext();

if (!this.AllowExternalUrls)

{

// Restrict URLs to be either from the current site

// collection or server-relative.

validationContext.RestrictUrlsToSiteCollection = true;

validationContext.GuidOfThisSiteCollection =

SPContext.Current.Site.ID;

}

bool droppedTags;

bool droppedUrls;

LinkFieldValue validatedValue =

validationContext.ValidateLinkValue(

currentMediaUrlValue,

out droppedTags,

out droppedUrls);

if (droppedUrls || String.IsNullOrEmpty(validatedValue.NavigateUrl))

{

// The media file URL in the link field value was

// not valid so report the error message.

// Setting IsValid to false stops saving the page.

this.IsValid = false;

this.ErrorMessage =

"The URL for the media file was invalid.";

if (!this.AllowExternalUrls)

{

this.ErrorMessage +=

" You must select a URL within the current site collection.";

}

}

}

}

}

/// This edit control for the MediaPlayerFieldControl has

/// a toolbar and text box for selecting a media file URL.

/// This example intentionally uses a separate toolbar button

/// and text box for the AssetUrlSelctor to show a more complex

/// example. You can use an AssetUrlSelector control instead of

/// a TextBox child control, which displays its own browse button.

public
class
MediaSelector : WebControl

{

private
TextBox mediaUrlTextBox = new
TextBox();

public MediaSelector()

{

}

/// This is the media URL value that you can edit in the text

/// box or Asset Picker dialog box.

public
string MediaUrl

{

get { return
this.mediaUrlTextBox.Text; }

set { this.mediaUrlTextBox.Text = value; }

}

protected
override
void OnInit(EventArgs e)

{

base.OnInit(e);

// This ensures that the TextBox child control receives

// its postback.

EnsureChildControls();

}

/// Gets JavaScript required to launch an Asset Picker dialog

/// box for choosing a media file URL.

private
string GetAssetPickerButtonScript()

{

AssetUrlSelector mediaAssetSelector =

new
AssetUrlSelector();

// When the AssetUrlSelector control is not added to the

// page control tree, the Page and ID properties are

// required because

// AssetUrlSelector.GetClientLaunchPickerReference()

// needs register script in the page.

mediaAssetSelector.Page = this.Page;

mediaAssetSelector.ID = "MediaUrlAssetSelector";

// Uses the TextBox client ID to connect the Asset Picker

// dialog box to the text box.

mediaAssetSelector.AssetUrlClientID =

this.mediaUrlTextBox.ClientID;

// Autopostback to see the new media file rendered after

// clicking OK on the Asset Picker dialog box.

mediaAssetSelector.AutoPostBack = true;

mediaAssetSelector.OverrideDialogTitle = "Select a media file";

mediaAssetSelector.OverrideDialogDescription =

"Select a media file to embed in this page";

mediaAssetSelector.UseImageAssetPicker = false;

return mediaAssetSelector.GetClientLaunchPickerReference();

}

private
Literal mediaPlayerOutput = new
Literal();

protected
override
void CreateChildControls()

{

SimpleToolbar mediaSelectorToolbar = new
SimpleToolbar();

mediaSelectorToolbar.ID = "ToolBar";

this.Controls.Add(mediaSelectorToolbar);

Label mediaUrlLabel = new
Label();

mediaUrlLabel.Text = "Selected media file URL: ";

mediaUrlLabel.AssociatedControlID = "MediaUrlTextBox";

this.Controls.Add(mediaUrlLabel);

this.mediaUrlTextBox.ID = "MediaUrlTextBox";

this.mediaUrlTextBox.CssClass =

"ms-input ms-lactiontable sample-mediaselector-urltextbox";

this.Controls.Add(this.mediaUrlTextBox);

// Add the button after the rest so that the text box

// ClientID is already determined and can be connected

// in the Asset Picker dialog box client script.

mediaSelectorToolbar.AddToolbarButton(

"SelectMediaFile",

"Select a media file",

this.GetAssetPickerButtonScript(),

"Open a picker to select a media file URL");

// Add a refresh button to perform a basic postback to

// to update the MediaUrl rendering.

mediaSelectorToolbar.AddToolbarButton(

"RefreshMediaFile",

"Refresh",

this.Page.ClientScript.GetPostBackEventReference(this,

String.Empty),

"Refresh the page to reload the current media file URL",

"/_layouts/IMAGES/refresh.gif");

// If there is a media file URL, this code creates

// the media player markup.

this.Controls.Add(this.mediaPlayerOutput);

}

protected
override
void OnPreRender(EventArgs e)

{

string mediaFileOutputHtml =

MediaRenderingUtilities.GetMediaPlayerHtmlMarkup(this.MediaUrl);

if (String.IsNullOrEmpty(mediaFileOutputHtml))

{

this.mediaPlayerOutput.Text =

"<BR>{There is no valid media file URL to display}<BR>";

}

else

{

this.mediaPlayerOutput.Text =

"<BR>" + mediaFileOutputHtml + "<BR>";

}

base.OnPreRender(e);

}

}

/// A simple toolbar class that matches the styles of the

/// publishing field control toolbars.

public
class
SimpleToolbar : RepeatedControls

{

public SimpleToolbar()

{

this.HeaderHtml =

"<div class=\"ms-toolbarContainer\" width=\"100%\">";

this.FooterHtml = "</div>";

this.SeparatorHtml = "";

}

public
void AddToolbarButton(

string buttonId,

string buttonText,

string clientOnClick,

string tooltipText)

{

Literal buttonMarkupLiteral = new
Literal();

buttonMarkupLiteral.Text = String.Format(

SimpleToolbarButtonHtmlFormat,

SPHttpUtility.HtmlEncode(buttonText),

SPHttpUtility.HtmlEncode(clientOnClick),

SPHttpUtility.HtmlEncode(tooltipText));

buttonMarkupLiteral.ID = buttonId;

this.Controls.Add(buttonMarkupLiteral);

}

public
void AddToolbarButton(

string buttonId,

string buttonText,

string clientOnClick,

string tooltipText,

string buttonImageSrc)

{

Literal buttonMarkupLiteral = new
Literal();

buttonMarkupLiteral.Text = String.Format(

SimpleToolbarButtonImageHtmlFormat,

SPHttpUtility.HtmlEncode(buttonText),

SPHttpUtility.HtmlEncode(clientOnClick),

SPHttpUtility.HtmlEncode(tooltipText),

SPHttpUtility.HtmlUrlAttributeEncode(buttonImageSrc));

buttonMarkupLiteral.ID = buttonId;

this.Controls.Add(buttonMarkupLiteral);

}

// {0} = Button text

// {1} = onclick script

// {2} = Tooltip text

private
const
string SimpleToolbarButtonHtmlFormat = @"

<DIV class=""ms-toolbarItem ms-selectorlink"">

<A href=""#"" onclick=""{1}"" title=""{2}"">&nbsp;{0}</A>

</DIV>";

// {0} = Button text

// {1} = onclick script

// {2} = Tooltip text

// {3} = Button image markup

private
const
string SimpleToolbarButtonImageHtmlFormat = @"

<DIV class=""ms-toolbarItem ms-selectorlink"">

<A href=""#"" onclick=""{1}"" title=""{2}"">

<IMG alt=""{2}"" src=""{3}"" border=""0"">{0}</A>

</DIV>";

}

public
static
class
MediaRenderingUtilities

{

/// Take a media file URL and generate HTML markup

/// for playing the file.

///
<param name="mediaUrl"></param>

public
static
string GetMediaPlayerHtmlMarkup(string mediaUrl)

{

// HtmlUrlAttributeEncode returns an empty string if the

// URL protocol is not allowed (e.g., JavaScript:)

string encodedUrl =

SPHttpUtility.HtmlUrlAttributeEncode(mediaUrl);

if (String.IsNullOrEmpty(encodedUrl))

{

return
String.Empty;

}

else

{

return
String.Format(MediaPlayerHtmlMarkupFormat, encodedUrl);

}

}

// Currently, this code includes only a parameter for the media

// file URL, but it could also include parameters for the

// width, height, and other rendering properties from field

// control properties or authored data value properties.

private
const
string MediaPlayerHtmlMarkupFormat = @"

@"<object id=""MediaPlayer""

width=400 height=300

classid=""CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95""

standby=""Loading Windows Media Player components...""

type=""application/x-oleobject""

codebase=""http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112"">

<param name=""filename"" value=""{0}"">

<param name=""Showcontrols"" value=""True"">

<param name=""autoStart"" value=""True"">

<embed type=""application/x-mplayer2""

src=""{0}"" name=""MediaPlayer""

width=400 height=300></embed>

</object>";}

}


 

Flash Control

I took the liberty to slightly modify the Media Control "mainly HTML markup" to Support Flash

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Publishing.WebControls;
using Microsoft.SharePoint.Publishing.Fields;

namespace VZ.Controls.CustomFieldControls

/// A Field control that binds to fields of type LinkField and is
/// specialized to select and render embedded flash files.
/// The RenderFieldForDisplay function generates the HTML markup to
/// display the flash file.  The FlashSelector control is
/// used at edit time to allow authors to select a flash file in
/// the Asset Picker dialog box.
{
    public class FlashFieldControl : BaseFieldControl
    {
        private FlashSelector flashSelector = new FlashSelector();

        public FlashFieldControl()
        {
        }

        /// Gets and sets the value in the edit controls
        public override object Value
        {
            get
            {
                LinkFieldValue flashUrlValue = new LinkFieldValue();
                flashUrlValue.NavigateUrl =
                  this.flashSelector.FlashUrl;
                flashUrlValue.Text =
                  LinkFieldValue.GetDefaultDisplayText(flashUrlValue.NavigateUrl);

                return flashUrlValue;
            }
            set
            {
                LinkFieldValue flashLinkFieldValue =
                  value as LinkFieldValue;
                if (null != flashLinkFieldValue)
                {
                    this.flashSelector.FlashUrl =
                      flashLinkFieldValue.NavigateUrl;
                }
                else
                {
                    this.flashSelector.FlashUrl = String.Empty;
                }
            }
        }

        /// Get the default name used to find the template and
        /// control for the FlashSelector in the control
        /// template ASCX files.
        protected override string DefaultTemplateName
        {
            get { return "FlashFieldControl"; }
        }

        private const string AllowExternalUrlsViewStateKey = "AllowExternalUrls";
        /// A flag that determines whether to allow saving of external
        /// flash URLs.
        public bool AllowExternalUrls
        {
            get
            {
                // Return true by default if not already in view state.
                if (ViewState[AllowExternalUrlsViewStateKey] == null)
                {
                    return true;
                }
                return (bool)ViewState[AllowExternalUrlsViewStateKey];
            }
            set
            {
                ViewState[AllowExternalUrlsViewStateKey] = value;
            }
        }

        /// Creates the edit control when not in display mode.
        protected override void CreateChildControls()
        {

            base.CreateChildControls();

            if (this.ControlMode != SPControlMode.Display)
            {
                FlashSelector flashSelectorInTemplate =
                  this.TemplateContainer.FindControl(this.TemplateName)
                  as FlashSelector;

                if (null == flashSelectorInTemplate)
                {
                    // No flash selector was found in the control
                    // template ASCX files. Add the default selector.
                    this.Controls.Add(this.flashSelector);
                }
                else
                {
                    // Get the flash selector from the control
                    // template ASCX file.
                    flashSelectorInTemplate.FlashUrl =
                      this.flashSelector.FlashUrl;
                    this.flashSelector = flashSelectorInTemplate;
                }
            }
        }

        /// Gets the current value for the flash URL as stored
        /// in the list item.
        private string itemFieldValueFlashUrl
        {
            get
            {
                LinkFieldValue currentLinkValue =
                  this.ItemFieldValue as LinkFieldValue;
                if (null != currentLinkValue)
                {
                    return currentLinkValue.NavigateUrl;
                }
                else
                {
                    return String.Empty;
                }
            }
        }

        /// Renders the current list item value for the flash URL
        /// with embedded flash player markup.
        /// <param name="output"></param>
        protected override void
          RenderFieldForDisplay(System.Web.UI.HtmlTextWriter output)
        {
            if (!String.IsNullOrEmpty(this.itemFieldValueFlashUrl))
            {
                output.Write(FlashRenderingUtilities.GetFlashHtmlMarkup(this.itemFieldValueFlashUrl));
            }
        }

        /// Verifies that the FlashUrl is valid.
        public override void Validate()
        {
            base.Validate();
            if (this.IsValid)
            {
                LinkFieldValue currentFlashUrlValue =
                  this.Value as LinkFieldValue;

                if (currentFlashUrlValue ==
                  null || String.IsNullOrEmpty(currentFlashUrlValue.NavigateUrl))
                {
                    // Ensure the field is not required.
                    if (this.Field != null && this.Field.Required)
                    {
                        this.IsValid = false;
                        this.ErrorMessage =
                          "This field is required and must contain a flash file URL.";
                        return;
                    }
                    else
                    {
                        // The field is empty and not required.
                        // The data is valid.
                        return;
                    }
                }

                // Perform validation on the flash file URL.
                HtmlValidationContext validationContext =
                  new HtmlValidationContext();

                if (!this.AllowExternalUrls)
                {
                    // Restrict URLs to be either from the current site
                    // collection or server-relative.
                    validationContext.RestrictUrlsToSiteCollection = true;
                    validationContext.GuidOfThisSiteCollection =
                      SPContext.Current.Site.ID;
                }

                bool droppedTags;
                bool droppedUrls;
                LinkFieldValue validatedValue =
                    validationContext.ValidateLinkValue(
                        currentFlashUrlValue,
                        out droppedTags,
                        out droppedUrls);

                if (droppedUrls || String.IsNullOrEmpty(validatedValue.NavigateUrl))
                {
                    // The flash file URL in the link field value was
                    // not valid so report the error message.
                    // Setting IsValid to false stops saving the page.
                    this.IsValid = false;
                    this.ErrorMessage =
                      "The URL for the flash file was invalid.";
                    if (!this.AllowExternalUrls)
                    {
                        this.ErrorMessage +=
                          "  You must select a URL within the current site collection.";
                    }
                }
            }
        }
    }

    /// This edit control for the FlashFieldControl has
    /// a toolbar and text box for selecting a flash file URL.
    /// This example intentionally uses a separate toolbar button
    /// and text box for the AssetUrlSelctor to show a more complex
    /// example. You can use an AssetUrlSelector control instead of
    /// a TextBox child control, which displays its own browse button.
    public class FlashSelector : WebControl
    {
        private TextBox flashUrlTextBox = new TextBox();

        public FlashSelector()
        {
        }

        /// This is the flash URL value that you can edit in the text
        /// box or Asset Picker dialog box.
        public string FlashUrl
        {
            get { return this.flashUrlTextBox.Text; }
            set { this.flashUrlTextBox.Text = value; }
        }

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

            // This ensures that the TextBox child control receives
            // its postback.
            EnsureChildControls();
        }

        /// Gets JavaScript required to launch an Asset Picker dialog
        /// box for choosing a flash file URL.
        private string GetAssetPickerButtonScript()
        {
            AssetUrlSelector flashAssetSelector =
              new AssetUrlSelector();

            // When the AssetUrlSelector control is not added to the
            // page control tree, the Page and ID properties are
            // required because
            // AssetUrlSelector.GetClientLaunchPickerReference()
            // needs register script in the page.
            flashAssetSelector.Page = this.Page;
            flashAssetSelector.ID = "FlashUrlAssetSelector";

            // Uses the TextBox client ID to connect the Asset Picker
            // dialog box to the text box.
            flashAssetSelector.AssetUrlClientID =
              this.flashUrlTextBox.ClientID;

            // Autopostback to see the new flash file rendered after
            // clicking OK on the Asset Picker dialog box.
            flashAssetSelector.AutoPostBack = true;

            flashAssetSelector.OverrideDialogTitle = "Select a flash file";
            flashAssetSelector.OverrideDialogDescription =
              "Select a flash file to embed in this page";
            flashAssetSelector.UseImageAssetPicker = false;

            return flashAssetSelector.GetClientLaunchPickerReference();
        }

        private Literal flashOutput = new Literal();
        protected override void CreateChildControls()
        {
            SimpleToolbar flashSelectorToolbar = new SimpleToolbar();
            flashSelectorToolbar.ID = "ToolBar";

            this.Controls.Add(flashSelectorToolbar);

            Label flashUrlLabel = new Label();
            flashUrlLabel.Text = "Selected flash file URL: ";
            flashUrlLabel.AssociatedControlID = "FlashUrlTextBox";
            this.Controls.Add(flashUrlLabel);

            this.flashUrlTextBox.ID = "FlashUrlTextBox";
            this.flashUrlTextBox.CssClass =
              "ms-input ms-lactiontable sample-flashselector-urltextbox";
            this.Controls.Add(this.flashUrlTextBox);

            // Add the button after the rest so that the text box
            // ClientID is already determined and can be connected
            // in the Asset Picker dialog box client script.
            flashSelectorToolbar.AddToolbarButton(
                "SelectFlashFile",
                "Select a flash file",
                this.GetAssetPickerButtonScript(),
                "Open a picker to select a flash file URL");

            // Add a refresh button to perform a basic postback to
            // to update the FlashUrl rendering.
            flashSelectorToolbar.AddToolbarButton(
                "RefreshFlashFile",
                "Refresh",
                this.Page.ClientScript.GetPostBackEventReference(this,
                  String.Empty),
                  "Refresh the page to reload the current flash file URL",
                  "/_layouts/IMAGES/refresh.gif");

            // If there is a flash file URL, this code creates
            // the flash player markup.
            this.Controls.Add(this.flashOutput);
        }

        protected override void OnPreRender(EventArgs e)
        {
            string flashFileOutputHtml =
              FlashRenderingUtilities.GetFlashHtmlMarkup(this.FlashUrl);
            if (String.IsNullOrEmpty(flashFileOutputHtml))
            {
                this.flashOutput.Text =
                  "<BR>{There is no valid flash file URL to display}<BR>";
            }
            else
            {
                this.flashOutput.Text =
                  "<BR>" + flashFileOutputHtml + "<BR>";
            }

            base.OnPreRender(e);
        }
    }

    public static class FlashRenderingUtilities
    {
        /// Take a flash file URL and generate HTML markup
        /// for playing the file.
        /// <param name="flashUrl"></param>
        public static string GetFlashHtmlMarkup(string flashUrl)
        {
            // HtmlUrlAttributeEncode returns an empty string if the
            // URL protocol is not allowed (e.g., JavaScript:)
            string encodedUrl =
                SPHttpUtility.HtmlUrlAttributeEncode(flashUrl);

            if (String.IsNullOrEmpty(encodedUrl))
            {
                return String.Empty;
            }
            else
            {
                return String.Format(FlashHtmlMarkupFormat, encodedUrl);
            }
        }

        // Currently, this code includes only a parameter for the flash
        // file URL, but it could also include parameters for the
        // width, height, and other rendering properties from field
        // control properties or authored data value properties.
        private const string FlashHtmlMarkupFormat = @"
<object classid=""clsid:d27cdb6e-ae6d-11cf-96b8-444553540000""
    codebase=""http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0""
    width=""300"" height=""450"">
    <param name=""movie"" value=""{0}"" /> 
    <param name=""quality"" value=""high"" />
    <param name=""bgcolor"" value=""#ffffff"" />
    <embed src=""{0}"" quality=""high""
        bgcolor=""#ffffff"" width=""468"" height=""60""
        name=""mymoviename"" align="" type=""application/x-shockwave-flash""
        pluginspage=""http://www.macromedia.com/go/getflashplayer"">
    </embed>
</object>";
    }
}

 
 

 
 

Monday, June 4, 2007

MOSS 2007 Development 101 – Part 2

Building a Rotating Banner for Images


The first thing you should do is have your environment configured and have the web extensions for MOSS. Please see the article located here: blogspot article.

Open Visual Studio and create a new project of type "web part"


Photo Sharing and Video Hosting at Photobucket

I then am going to create a sharepoint picture library and upload some pictures into it. Now, because I am going to create a rotating banner, and I am concerned about real estate, I will make sure that all the pictures are the same size. In this case I took some button images.

Photo Sharing and Video Hosting at Photobucket


The goal at the end will be to have a random image from this selection appear on a web part on a web page within my portal.

What we are going to do next is create the *.webpart file. This file will expose and set certain properties that will be used for the webpart. Please keep in mind that many of these properties are required.

We are going to add a file of XML type to the project and call it RotatingImage.webpart.

Photo Sharing and Video Hosting at Photobucket

It will look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<webParts>

<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">;
<metaData>
<type name="CI.CustomWebParts.Randomize.RotatingImage,CI.CustomWebParts.Randomize, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3d0e3c375c2b1907" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">RotatingImage</property>

<property name="Description" type="string">Rotates Pictures from a Picture Library.</property>
<property name="AllowClose" type="bool">FALSE</property>
<property name="PictureLibraryURL" type="string">http://moss-test/RotatingBanner</property>
</properties>
</data>
</webPart>
</webParts>



Obviously you would replace your public key token with the one generated from the sn command. For details on this please see my post on Code Access Security.



Next you will need to add the following to the assembly.cs file:

[assembly: AllowPartiallyTrustedCallers()]


Before adding your web part make sure to add it to the safe controls section of the website you are going to add it to if it is not already there. If you do a deploy from visual studio and you have chosen the Sharepoint WebPart project, this should automatically be done. It would look something like this:

<SafeControl
Assembly="CI.CustomWebParts.Randomize, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3d0e3c375c2b1907" Namespace="CI.CustomWebParts.Randomize" TypeName="RotatingImage" Safe="True" />



Finally, the code. I recommend to deploy as is and add to a page first because at this point you have generated the "plumbing" of the part if you will. This will at least ensure that all is deployed correctly and you only have to worry about your custom code if it doesn't quite go as planned ;)

As I alluded to earlier in the post we are just going to pull the pictures out of a picture library and add a random one to the page. The way I did this in this example was instead of overriding the Render method that came out of the box, I deleted it and added the following code in the *.cs file:

using System;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;

namespace CI.CustomWebParts.Randomize
{
[Guid("0b1a09b8-98d1-4349-acce-fe4b715751a9")]
public class RotatingImage : System.Web.UI.WebControls.WebParts.WebPart {
// Fields
public string strPath = "";
public string strUrlPath;

// Constructor
public RotatingImage()

{
this.ExportMode = WebPartExportMode.All;
}

//protected override void Render(HtmlTextWriter writer)
//{
// // TODO: add custom rendering code here.
// // writer.Write("Output HTML");
// writer.Write(DateTime.Now.ToLongTimeString());
//}
protected override void CreateChildControls()
{
base.CreateChildControls();

// Declarations
Image img = null;

// Determine the location of the class resources using
// the SPWebPartManager on the Web page
SPSite site = new SPSite("http://moss-test");
SPWeb web = site.OpenWeb();

//Gets Picture Items from Library
SPList list = web.Lists["RotatingBanner"]; SPListItem item;
SPListItemCollection items = list.Items;

int iCount = 0;

Random r = new
Random();
iCount = r.Next(0, list.ItemCount - 1);
item = items[iCount];

string imageUrl = "http://Moss-Test/RotatingBanner/" + item.Name;

// Instantiate, Initialize, and Insert the image
img = new
Image();
img.ImageUrl = imageUrl;

this.Controls.Add(img);

//Close
site.Close();
site.Dispose();
web.Close();
web.Dispose();
}
}
}



Essentially what we have done here is override the child controls method and added our own image to the controls collection. You could essentially add any control you wished to this collection and it would render.



Go ahead and add your new web part to a page if you have not already done so and poof! You now have a randomized picture from your picture library. I know it probably didn't work the first time but if it did great!