Wiki内検索
最近更新したページ
最新コメント
メニューバー
タグ

Webパーツ開発用コードリファレンス

■[WSS3.0(MOSS2007)] Webパーツ開発用コードリファレンス

Webパーツ開発の際に便利なコードを紹介します。

※なお、ログインユーザに対してアクセス権限のないコードは実行できませんのでご注意ください。(それを防ぐためには、ユーザ偽装等を行う必要があります。)


●現在開いているサイトコレクションを取得する(SPSite)
SPSite siteCollection;
siteCollection = SPControl.GetContextSite(Context);
●現在開いているサイトを取得する(SPWeb)
SPWeb site;
site = SPControl.GetContextWeb(Context);
●サイトコレクションのトップサイト(一番上のページ)を取得する(SPWeb)
SPSite siteCollection;
SPWeb topSite;
siteCollection = SPControl.GetContextSite(Context);
topSite = site.RootWeb;
●サイトコレクション以下の全てのサイトを順にみる
private bool CheckSPWeb()
{
    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;
}
●IISの設定情報を取得する(SPIisSettings)
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);
SPWebApplication apl = site.WebApplication;
SPApplicationPool pool = apl.ApplicationPool;

string poolName = pool.Name;
string displayName = pool.DisplayName;
string userName = pool.Username;
string password = pool.Password;
●ログインユーザ情報を取得する(SPUser、string)
(方法1)
SPWeb site = SPControl.GetContextWeb(Context);
SPUser user = site.CurrentUser;

(方法2)
SPUser user = SPContext.Current.Web.CurrentUser;

(方法3)
string loginName = Context.User.Identity.Name;
●システムアカウント情報を取得する(SPUser)
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()
{
    ToolPart[] toolparts = new ToolPart[2];
    CustomPropertyToolPart cp = new CustomPropertyToolPart();
    cp.Expand(0);
    toolparts[0] = cp;
    toolparts[1] = new WebPartToolPart();
    return toolparts;
}
●Web.Configより設定情報を取得する(AppSettingsReader)
Web.Configの<appSettings>タグ以下に記述した設定情報を取得する方法。
AppSettingsReader reader = new AppSettingsReader();
object keyValue = reader.GetValue("appKey", typeof(string));
●Web.Configより設定情報を取得する(KeyValueConfigurationCollection)
(方法1)
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;
●SPListから、リストアイテムのDataTableを取得する
SPWeb site = SPControl.GetContextWeb(Context);
SPList list = site.Lists[@"お知らせ"];
DataTable dt = list.Items.GetDataTable();
●画面遷移
string url = @"http://n-001:8080/od/default.aspx";
Response.Redirect(url);
●指定されたSPViewの内容を、HTMLとして描画する
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();
2007年05月09日(水) 21:37:06 Modified by sharepoint




スマートフォン版で見る