看到这篇文章 moss文档浏览次数统计 ,忍不住想到了这篇文章: WSS列表访问统计的实现 --编写一个custom field,在render的时候读取字段值并判断加1写回,当然如果需要你也可以做成针对每个用户的统计以及防刷新等。

但里面的代码有bug--权限提升有问题,对ListItem没修改权限的用户访问会出错。
修改后的完整代码如下:
ItemViewCounterField.cs

public class ItemViewCounterField : SPField
    
{
       
public ItemViewCounterField(SPFieldCollection fields, string fieldName)
            : 
base( fields , fieldName )
        
{
            Init();
        }


        
public ItemViewCounterField(SPFieldCollection fields, string typeName, string displayName)
            : 
base(fields, typeName, displayName)
        
{
            Init();
        }


        
void Init()
        
{
            
//this.ReadOnlyField
            this.ShowInDisplayForm = true;
            
this.ShowInEditForm = false;
            
this.ShowInNewForm = false;            
        }


        
public override BaseFieldControl FieldRenderingControl
        
{
            
get
            
{
                BaseFieldControl ctl 
= new ItemViewCounterFieldControl();
                ctl.FieldName 
= this.InternalName;
                
return ctl ;
            }

        }

    }

ItemViewCounterFieldControl.cs
class ItemViewCounterFieldControl : BaseFieldControl
    
{
        
/// <summary>
        
/// 更新字段
        
/// </summary>

        void UpdateWithElevatedPrivileges()
        
{
             SPSecurity.RunWithElevatedPrivileges(
delegate()
                
{
                    
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    
{
                        
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                        
{
                            web.AllowUnsafeUpdates 
= true;

                            SPList list 
= web.Lists[ this.ListId ];

                            SPListItem item 
= list.GetItemById(this.ItemId);

                            
if (item == nullreturn;

                            item[
this.FieldName] = this.ItemFieldValue;

                            item.SystemUpdate();
                        }

                    }

                }

                );
        }


        
protected override void Render(HtmlTextWriter output)
        
{
            
int cCounter;

            
if (this.ItemFieldValue == null)
            
{
                cCounter 
= 1;
            }

            
else
            
{
                cCounter 
= Convert.ToInt32(this.ItemFieldValue);
                cCounter
++;
            }


            
this.ItemFieldValue = cCounter.ToString();

            
this.UpdateWithElevatedPrivileges();

            
if (this.ItemFieldValue == null)
                output.Write(
"0");
            
else
                output.Write(
this.ItemFieldValue.ToString());

        }

 
    }

fldtypes_itemViewCounter.xml


posted on 2008-01-08 10:11  jianyi  阅读(1737)  评论(13编辑  收藏  举报