Webパーツ開発用コードリファレンス
■[WSS3.0(MOSS2007)] Webパーツ開発用コードリファレンス
Webパーツ開発の際に便利なコードを紹介します。
※なお、ログインユーザに対してアクセス権限のないコードは実行できませんのでご注意ください。(それを防ぐためには、ユーザ偽装等を行う必要があります。)
●現在開いているサイトコレクションを取得する(SPSite)
SPWebクラスのDoesUserHavePermissionsメソッドを使用することで、権限チェックを実装することができます。
なお、DoesUserHavePermissionsメソッドは、SPListクラスやSPListItemクラス等にも存在します。
カスタムプロパティの型は、原則として基本型のみ。WSSで入力する各種コントロールは、カスタムプロパティの型に応じて自動的に作成されます。(プロパティを作成する際は、「Visual Studio 2005」のスニペットを使用すると便利です。)
Web.Configの<appSettings>タグ以下に記述した設定情報を取得する方法。
SPListItemクラスのUpdateメソッドを使用することで、作成者や更新者等が自動的に追加したリストアイテムに反映されます。
また、コード上で作成者や更新者等を設定したときには、コード上で設定した内容によって上書きされます。
なお、リストアイテムの更新には、UpdateメソッドとSystemUpdateメソッドがあります。
通常はUpdateメソッドを使用するべきですが、更新対象のリストアイテムにロックがかかっている場合、Updateメソッドを使用するとエラーとなります。その際は、SystemUpdateメソッドを使用することによってリストアイテムの更新ができます。
しかし、SystemUpdateメソッドを使用した場合は更新者等が自動的に反映されないため、特に問題がない限りはUpdateメソッドを使用されることを推奨します。
Webパーツ開発の際に便利なコードを紹介します。
※なお、ログインユーザに対してアクセス権限のないコードは実行できませんのでご注意ください。(それを防ぐためには、ユーザ偽装等を行う必要があります。)
●現在開いているサイトコレクションを取得する(SPSite)
SPSite siteCollection;●現在開いているサイトを取得する(SPWeb)
siteCollection = SPControl.GetContextSite(Context);
SPWeb site;●サイトコレクションのトップサイト(一番上のページ)を取得する(SPWeb)
site = SPControl.GetContextWeb(Context);
SPSite siteCollection;●サイトコレクション以下の全てのサイトを順にみる
SPWeb topSite;
siteCollection = SPControl.GetContextSite(Context);
topSite = site.RootWeb;
private bool CheckSPWeb()●IISの設定情報を取得する(SPIisSettings)
{
SPSite siteCollection = SPControl.GetContextSite(Context);
return CheckSPWeb(siteCollection.AllWebs);
}
private bool CheckSPWeb(SPWebCollection webs)
{
if (webs == null) return true;
foreach (SPWeb web in webs)
{
bool result = CheckSPWeb(web.Webs);
}
return true;
}
SPSite siteCollection = SPControl.GetContextSite(Context);●アプリケーションプールのユーザ名とパスワードを取得する
SPWebApplication apl = siteCollection.WebApplication;
Dictionary<SPUrlZone, SPIisSettings> dict = apl.IisSettings;
SPIisSettings iisSettings;
dict.TryGetValue(siteCollection.Zone, out iisSettings);
SPSite site = SPControl.GetContextSite(Context);●ログインユーザ情報を取得する(SPUser、string)
SPWebApplication apl = site.WebApplication;
SPApplicationPool pool = apl.ApplicationPool;
string poolName = pool.Name;
string displayName = pool.DisplayName;
string userName = pool.Username;
string password = pool.Password;
(方法1)●システムアカウント情報を取得する(SPUser)
SPWeb site = SPControl.GetContextWeb(Context);
SPUser user = site.CurrentUser;
(方法2)
SPUser user = SPContext.Current.Web.CurrentUser;
(方法3)
string loginName = Context.User.Identity.Name;
SPSite siteCollection = SPControl.GetContextSite(Context);●ログインユーザがサイト管理権限を持っているかどうかをチェックする
SPUser systemAccount = siteCollection.SystemAccount;
SPWebクラスのDoesUserHavePermissionsメソッドを使用することで、権限チェックを実装することができます。
なお、DoesUserHavePermissionsメソッドは、SPListクラスやSPListItemクラス等にも存在します。
SPWeb Web;●カスタムプロパティを定義する
SPWeb newWeb;
newWeb.DoesUserHavePermissions(Web.CurrentUser.LoginName, SPBasePermissions.ManageSubwebs)
カスタムプロパティの型は、原則として基本型のみ。WSSで入力する各種コントロールは、カスタムプロパティの型に応じて自動的に作成されます。(プロパティを作成する際は、「Visual Studio 2005」のスニペットを使用すると便利です。)
#region ページング件数●カスタムプロパティを、プロパティ編集画面の一番上に表示する
/// <summary>
/// ページング表示件数
/// </summary>
private uint _PagingCount = 20;
/// <summary>
/// ページング表示件数
/// </summary>
[Description(@"一度に表示するサブサイトの件数を設定します。「0」を設定した場合は、ページングを行いません。"),
Category(@"設定"),
FriendlyName(@"一度に表示するサブサイトの件数")]
[WebPartStorage(Storage.Personal)]
public uint PagingCount
{
get
{
return _PagingCount;
}
set
{
try
{
_PagingCount = value;
ToolBarPagingVisible();
}
catch (Exception)
{
// 何もしない
}
}
}
#endregion
public override ToolPart[] GetToolParts()●Web.Configより設定情報を取得する(AppSettingsReader)
{
ToolPart[] toolparts = new ToolPart[2];
CustomPropertyToolPart cp = new CustomPropertyToolPart();
cp.Expand(0);
toolparts[0] = cp;
toolparts[1] = new WebPartToolPart();
return toolparts;
}
Web.Configの<appSettings>タグ以下に記述した設定情報を取得する方法。
AppSettingsReader reader = new AppSettingsReader();●Web.Configより設定情報を取得する(KeyValueConfigurationCollection)
object keyValue = reader.GetValue("appKey", typeof(string));
(方法1)●SPListから、リストアイテムのDataTableを取得する
KeyValueConfigurationCollection settings = null;
Configuration configration = null;
SPSite siteCollection = SPControl.GetContextSite(Context);
SPWebApplication apl = siteCollection.WebApplication;
Dictionary<SPUrlZone, SPIisSettings> dict = apl.IisSettings;
if (dict != null)
{
// 実行元のSPSiteと対応するIISの情報を取得する
SPIisSettings iisSettings;
string serverComment = null;
if (dict.TryGetValue(properties.Zone, out iisSettings))
{
serverComment = iisSettings.ServerComment;
}
if (!string.IsNullOrEmpty(serverComment))
{
// 実行元のSPSiteと対応するIISのWeb.Config情報を取得する
IntPtr userToken = WindowsIdentity.GetCurrent().Token;
configPath = iisSettings.Path.FullName;
configration = WebConfigurationManager.OpenWebConfiguration(
tmpSite.ServerRelativeUrl, serverComment, null, tmpSite.HostName, userToken);
}
}
if (configration != null)
{
settings = settings = configration.AppSettings.Settings;
}
string keyValue = settings["appKey"].Value;
(方法2)
KeyValueConfigurationCollection settings = null;
Configuration configration = null;
SPSite siteCollection = SPControl.GetContextSite(Context);
SPWebApplication apl = siteCollection.WebApplication;
Dictionary<SPUrlZone, SPIisSettings> dict = apl.IisSettings;
if (dict != null)
{
// 実行元のSPSiteと対応するIISの情報を取得する
SPIisSettings iisSettings;
string serverComment = null;
if (dict.TryGetValue(properties.Zone, out iisSettings))
{
serverComment = iisSettings.ServerComment;
}
if (!string.IsNullOrEmpty(serverComment))
{
// 実行元のSPSiteと対応するIISのWeb.Config情報を取得する
IntPtr userToken = WindowsIdentity.GetCurrent().Token;
configPath = iisSettings.Path.FullName;
configPath += @"web.config";
configration = ConfigurationManager.OpenExeConfiguration(configPath);
if (configration != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(configPath);
XmlNodeList nodeList = doc.GetElementsByTagName(@"appSettings");
settings = new KeyValueConfigurationCollection();
foreach (XmlNode node in nodeList[0].ChildNodes)
{
if (node is XmlElement)
{
settings.Add(
ToString(node.Attributes[@"key"].Value),
ToString(node.Attributes[@"value"].Value));
}
}
}
}
}
string keyValue = settings["appKey"].Value;
SPWeb site = SPControl.GetContextWeb(Context);●画面遷移
SPList list = site.Lists[@"お知らせ"];
DataTable dt = list.Items.GetDataTable();
string url = @"http://n-001:8080/od/default.aspx";●指定されたSPViewの内容を、HTMLとして描画する
Response.Redirect(url);
SPViewクラスのRenderAsHtmlメソッドを使用することにより、SPViewの内容をHTMLとして描画できます。 protected HtmlGenericControl divList = new HtmlGenericControl("DIV");●リストアイテム追加処理
public WebPart1() // コンストラクタ
{
this.Controls.Add(this.divList);
}
protected override void CreateChildControls()
{
}
protected override void RenderWebPart(HtmlTextWriter output)
{
SPWeb site = SPControl.GetContextWeb(Context);
SPList list = site.Lists[@"お知らせ"];
SPView view = list.Views[@"すべてのアイテム"];
string strHtml = view.RenderAsHtml();
divList.InnerHtml = strHtml;
base.RenderWebPart(output);
}
SPListItemクラスのUpdateメソッドを使用することで、作成者や更新者等が自動的に追加したリストアイテムに反映されます。
また、コード上で作成者や更新者等を設定したときには、コード上で設定した内容によって上書きされます。
なお、リストアイテムの更新には、UpdateメソッドとSystemUpdateメソッドがあります。
通常はUpdateメソッドを使用するべきですが、更新対象のリストアイテムにロックがかかっている場合、Updateメソッドを使用するとエラーとなります。その際は、SystemUpdateメソッドを使用することによってリストアイテムの更新ができます。
しかし、SystemUpdateメソッドを使用した場合は更新者等が自動的に反映されないため、特に問題がない限りはUpdateメソッドを使用されることを推奨します。
SPSite siteCollection = SPControl.GetContextSite(Context);
SPWeb site = SPControl.GetContextWeb(Context);
SPListItemCollection listItems = site.Lists[@"お知らせ"].Items;
//SPUser user = site.CurrentUser;
//int userId = user.ID;
// リストアイテム追加処理
SPListItem item = listItems.Add();
//item[@"作成者"] = userId;
//item[@"更新者"] = userId;
item.Update();
コメント(2) |
2007年05月09日(水) 21:37:06 Modified by sharepoint