Я обнаружил, что MOSS (он же SharePoint 2007) не имеет механизма доступа к SPUser разрешению клиента.Следовательно, элементы управления SilverLight не имеют прямых средств для получения этой информации.Мое решение состояло в том, чтобы изменить WebPart, в котором размещен элемент управления SilverLight, для включения свойства, которое передавало бы эту информацию в элемент управления SilverLight в качестве одного из InitParams.
В настоящее время существует множество веб-частей для размещения элемента управления SilverLight, доступных наWeb.Вот несколько примеров.
CodePlex http://silverlightwebpart.codeplex.com/
Блог Кирка Эванса http://blogs.msdn.com/b/kaevans/archive/2008/10/08/hosting-silverlight-in-a-sharepoint-webpart.aspx
Есть заметные сходства с моим WebPart и тем, что есть в этой статье.http://blogs.msdn.com/b/andreww/archive/2009/03/12/silverlight-web-part-in-sharepoint.aspx
Я решил сделать настраиваемую саму WebPart
public class SecureSilverLightWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
private int _controlWidth;
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
WebDisplayName("Silverlight Control Width")]
public int ControlWidth
{
get { return _controlWidth; }
set { _controlWidth = value; }
}
private int _controlHeight;
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Silverlight Control Height")]
public int ControlHeight
{
get { return _controlHeight; }
set { _controlHeight = value; }
}
string _silverLightXapPath = string.Empty;
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("SilverLight Xap file path"),
WebDescription("Enter the SilverLight Xap File Name which will be downloaded at Runtime")]
public string SilverLightXapPath
{
get { return _silverLightXapPath; }
set { _silverLightXapPath = value; }
}
string _controlParameters = "";
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Parameters to SilverLight Application"),
WebDescription("Enter Key Value Pair Parameters That Needs to be sent to SilverLight Application")]
public string ControlParameters
{
get { return _controlParameters; }
set { _controlParameters = value; }
}
private string _fullAccessGroup = "";
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
WebDisplayName("Group membership required to enable Silverlight Application"),
WebDescription("Enter the Sharepoint group required to enable this component.")]
public string FullAccessGroup
{
get { return _fullAccessGroup; }
set { _fullAccessGroup = value; }
}
// This method member checks whether the current
// SharePoint user is a member of the group, groupName
private bool IsMember(string groupName)
{
bool isMember;
SPSite site = SPContext.Current.Web.Site;
SPWeb web = site.OpenWeb();
try
{
isMember = web.IsCurrentUserMemberOfGroup(web.Groups[groupName].ID);
}
catch (SPException ex)
{
isMember = false;
}
finally
{
web.Close();
site.Close();
}
return isMember;
}
protected override void CreateChildControls()
{
base.CreateChildControls();
if (_controlHeight != 0 && _controlWidth != 0 && _silverLightXapPath != string.Empty)
{
Silverlight sl = new Silverlight();
sl.ID = "SlCoffee";
if (ConfigurationSettings.AppSettings != null)
{
//In the Web.config for the Sharepoint site I have a key in the AppSettings
//pointing to the where the Xap files are saved. Something
//like <add key="SITEURL" value="http://MyServer:43746/XapFiles/" />
if (ConfigurationSettings.AppSettings["SITEURL"] != string.Empty)
{
string url = ConfigurationSettings.AppSettings["SITEURL"];
sl.Source = url + _silverLightXapPath;
}
}
sl.Width = new Unit(_controlWidth);
sl.Windowless = true;
sl.Height = new Unit(_controlHeight);
int SettingCount = ConfigurationSettings.AppSettings.Count;
StringBuilder SB = new StringBuilder();
//Optional
for (int index = 0; index < SettingCount; index++)
{
//Most of the InitParams are kept in the AppSettings. You probably
//wouldn't send all of your AppSettings to the control like this.
if (ConfigurationSettings.AppSettings.GetKey(index).StartsWith("client"))
{
SB.Append(ConfigurationSettings.AppSettings.GetKey(index));
SB.Append("=");
SB.Append(ConfigurationSettings.AppSettings[index]);
SB.Append(",");
}
}
//This is the place in the code where SPUser and Group information is
//sent to the SilverLight control hosted by this WebPart.
SB.Append("UserId=" + SPContext.Current.Web.CurrentUser + ",");
SB.Append(_controlParameters);
//Security portion
SB.Append("FullControl=" + IsMember(FullAccessGroup));
sl.InitParameters = SB.ToString();
Controls.Add(sl);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ScriptManager sm = ScriptManager.GetCurrent(Page);
if (sm == null)
{
sm = new ScriptManager();
Controls.AddAt(0, sm);
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
if (_controlHeight == 0 || _controlWidth == 0 || _silverLightXapPath == string.Empty)
{
writer.Write("<h3>Please Configure Web Part Properties<h3>");
}
}
}
Далее в элементе управления SilverLight я использую Initparameters
/// <summary>
/// Handles the Loaded event of the MainPage control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if(UserMayEdit() )
{
// User is a member of the group set up in configuration of the WebPart.
// enable any controls accordingly.
TabItem_Backlog.IsEnabled = true;
}
else
{
// User is not a member - disable.
TabItem_Backlog.IsEnabled = false;
TabItem_Approved.IsSelected = true;
}
//...
}
/// <summary>
/// Checks input parameters to determine whether
/// users the may edit
/// </summary>
/// <returns></returns>
private bool UserMayEdit()
{
bool bCardEditor = false;
try
{
if (application.AppConfiguration["FullControl"].ToUpper() == "TRUE")
{
bCardEditor = true;
}
}
catch (KeyNotFoundException)
{
MessageBox.Show("Please configure the component's security settings to enable the Active tab.", "PMDG Cards", MessageBoxButton.OK);
}
return bCardEditor;
}
Словарь вSilverLight UserControl существует в файле App.xaml.cs, как показано здесь
public partial class App : Application
{
public static string UserID = string.Empty;
public IDictionary<string, string> AppConfiguration;
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
AppConfiguration = e.InitParams;
UserID = e.InitParams["UserId"];
this.RootVisual = new MainPage();
}
//...
}
Что я могу сказать?Это работает.