td id="1" class="ControlPanelTabInactive" align="center" nowrap>
<a href="<%=Globals.GetSiteUrls().MyFavorites%>"><%=ResourceManager.GetString("MyFavorites_Title")%></a>
</td>
修改: <td colspan=11 class="ControlPanelTabLine"><img width="1" height=1 alt=""></td>跨跃列数
五.增加相应文件
表现层1,收藏夹主视图
在web/user/目录增加MyFavorites.aspx,最终用户页面
在Controls/Views目录增加MyFavoritesView.cs,页面视图服务器控件(主要表现为页面处理逻辑)
界面视图:在Web/Themes/default/Skins中增加View-MyFavorites.ascx 收藏夹视图(主要表现为页面UI)
组件
在Components目录增加Favorites.cs(相当于业务逻辑层,加s表业务处理),此例中未在子目录Components/Components中增加Favorite.cs(相当于业务实体层,未加s表实体),因并不需要,完整的Asp.net forums模式应该还有这一层。
表现层2,用户点击收藏按钮后呈现的UI
(这个比较简单)
在web目录增加MyFavoritesAdd.aspx文件
处理加入收藏时服务器控件, 在Controls目录增加MyFavoritesAdd.cs(页面处理逻辑)
在Web/Themes/default/Skins中增加Skin-MyFavoritesAdd.ascx将主题加入收藏时的视图(UI)
六.数据库
增加表forums_Favorites
UserID int 4 0
ThreadID int 4 0
FavoriteDate datetime 8 0
创建存储过程forums_Favorites_CreateDelete
CREATE procedure forums_Favorites_CreateDelete
(
@UserID int,
@ThreadID int,
@Action int
)
AS
BEGIN
IF @Action = 0
BEGIN
-- Does the user already have the ability to see this thread?
IF EXISTS (SELECT UserID FROM forums_Favorites WHERE UserID = @UserID and ThreadID = @ThreadID)
return
INSERT INTO
forums_Favorites
VALUES
(
@UserID,
@ThreadID,
getdate()
)
RETURN
END
IF @Action = 2
BEGIN
DELETE
forums_Favorites
WHERE
UserID = @UserID AND
ThreadID = @ThreadID
RETURN
END
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
七.数据处理
1.Components/Provider/ForumsDataProvider.cs增加
#region 收藏夹
public abstract void CreateFavorites(ArrayList users, int threadID);
public abstract void DeleteFavorites(int userID, ArrayList deleteList);
#endregion
2. Data Providers/SqlDataProvider/SqlDataProvider.cs增加实现方法
#region #### 收藏夹 #### by venjiang 0912
/// <summary>
/// 追加主题到收藏夹
/// </summary>
/// <param name="userID">用户ID</param>
/// <param name="threadID">主题ID</param>
public override void CreateFavorites(int userID,int threadID)
{
using( SqlConnection myConnection = GetSqlConnection() )
{
SqlCommand myCommand = new SqlCommand(databaseOwner + ".forums_Favorites_CreateDelete", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@Action", SqlDbType.Bit).Value = DataProviderAction.Create;
myCommand.Parameters.Add("@UserID", SqlDbType.Int);
myCommand.Parameters.Add("@ThreadID", SqlDbType.Int);
myConnection.Open();
myCommand.Parameters["@UserID"].Value = userID;
myCommand.Parameters["@ThreadID"].Value = threadID;
myCommand.ExecuteNonQuery();
}
}
/// <summary>
/// 从收藏夹中删除主题
/// </summary>
/// <param name="userID">用户ID</param>
/// <param name="deleteList">删除列表</param>
public override void DeleteFavorites(int userID, ArrayList deleteList)
{
// Create Instance of Connection and Command Object
using( SqlConnection myConnection = GetSqlConnection() )
{
SqlCommand myCommand = new SqlCommand(databaseOwner + ".forums_Favorites_CreateDelete", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@Action", SqlDbType.Int).Value = DataProviderAction.Delete;
myCommand.Parameters.Add("@UserID", SqlDbType.Int).Value = userID;
myCommand.Parameters.Add("@ThreadID", SqlDbType.Int);
// Open the connection
myConnection.Open();
// Add multiple times
//
foreach (int threadID in deleteList)
{
myCommand.Parameters["@ThreadID"].Value = threadID;
myCommand.ExecuteNonQuery();
}
}
}
#endregion
3.在Data Providers/SqlDataProvider/SqlDataProvider.cs修改GetThreads方法,以支持收藏功能
#region #### Threads ####
// 增加贴子收藏 by venjiang 0911
public override ThreadSet GetThreads(
int forumID,
int pageIndex,
int pageSize,
int userID,
DateTime threadsNewerThan,
SortThreadsBy sortBy,
SortOrder sortOrder,
ThreadStatus threadStatus,
ThreadUsersFilter userFilter,
bool activeTopics,
bool unreadOnly,
bool unansweredOnly,
bool returnRecordCount,
// 增加新参数,是否仅显示收藏的主题
bool favoriteOnly
)
{
// Create Instance of Connection and Command Object
//
using( SqlConnection connection = GetSqlConnection() ) {
SqlCommand command = new SqlCommand(databaseOwner + ".forums_Threads_GetThreadSet", connection);
command.CommandType = CommandType.StoredProcedure;
ThreadSet threadSet = new ThreadSet();
StringBuilder sqlCountSelect = new StringBuilder("SELECT count(T.ThreadID) ");
StringBuilder sqlPopulateSelect = new StringBuilder("SELECT T.ThreadID, HasRead = ");
StringBuilder fromClause = new StringBuilder(" FROM " + this.databaseOwner + ".forums_Threads T ");
StringBuilder whereClause = new StringBuilder(" WHERE ");
StringBuilder orderClause = new StringBuilder(" ORDER BY ");
// 增加收藏判断 by venjiang 0911
if (favoriteOnly == true)
{
fromClause.Append("," + this.databaseOwner + ".forums_Favorites Fav ");
}
// Ensure DateTime is min value for SQL
//
threadsNewerThan = SqlDataProvider.GetSafeSqlDateTime(threadsNewerThan);
// Construct the clauses
#region Constrain Forums
// Contrain the selectivness to a set of specified forums. The ForumID is our
// clustered index so we want this to be first
if (forumID > 0) {
whereClause.Append("T.ForumID = ");
whereClause.Append(forumID);
} else if (forumID < 0) {
whereClause.Append("(T.ForumID = ");
// Get a list of all the forums the user has access to
//
ArrayList forumList = Forums.GetForums(userID, false, true);
for (int i = 0; i < forumList.Count; i++) {
if ( ((Forum) forumList[i]).ForumID > 0 ) {
if ( (i + 1) < forumList.Count) {
whereClause.Append( ((Forum) forumList[i]).ForumID + " OR T.ForumID = ");
} else {
whereClause.Append( ((Forum) forumList[i]).ForumID );
whereClause.Append(")");
}
}
}
} else {
whereClause.Append("T.ForumID = 0 AND P.UserID = ");
whereClause.Append(userID);
whereClause.Append(" AND P.ThreadID = T.ThreadID ");
fromClause.Append(", " + this.databaseOwner + ".forums_PrivateMessages P ");
}
#endregion
#region Constrain Date
whereClause.Append(" AND StickyDate >= '");
whereClause.Append( threadsNewerThan.ToString( System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern ));
whereClause.Append(" '");
#endregion
#region Constain Approval
whereClause.Append(" AND IsApproved = 1");
#endregion
#region Constrain Read/Unread
if (userID > 0) {
sqlPopulateSelect.Append("(SELECT " + this.databaseOwner + ".HasReadPost(");
sqlPopulateSelect.Append(userID);
sqlPopulateSelect.Append(", T.ThreadID, T.ForumID)) ");
if (unreadOnly) {
whereClause.Append(" AND " + this.databaseOwner + ".HasReadPost(");
whereClause.Append(userID);
whereClause.Append(", T.ThreadID, T.ForumID) = 0");
}
} else {
sqlPopulateSelect.Append("0");
}
#endregion
#region Unanswered topics
if (unansweredOnly) {
whereClause.Append(" AND TotalReplies = 0 AND IsLocked = 0");
}
#endregion
#region Active topics
// 热门贴子
if (activeTopics) {
whereClause.Append(" AND TotalReplies > 2 AND IsLocked = 0 AND TotalViews > 50");
}
#endregion
#region 收藏
// 尽显示收藏的主题
if (favoriteOnly)
{
whereClause.Append(" AND T.ThreadID = Fav.ThreadID AND Fav.UserID = ");
whereClause.Append(userID);
}
#endregion
#region Users filter
if (userFilter != ThreadUsersFilter.All)
{
if ((userFilter == ThreadUsersFilter.HideTopicsParticipatedIn) || (userFilter == ThreadUsersFilter.HideTopicsNotParticipatedIn)) {
whereClause.Append(" AND ");
whereClause.Append(userID);
if (userFilter == ThreadUsersFilter.HideTopicsNotParticipatedIn)
whereClause.Append(" NOT");
whereClause.Append(" IN (SELECT UserID FROM " + this.databaseOwner + ".forums_Posts P WHERE P.ThreadID = T.ThreadID)");
} else {
if (userFilter == ThreadUsersFilter.HideTopicsByNonAnonymousUsers)
whereClause.Append(" AND 0 NOT");
else
whereClause.Append(" AND 0");
whereClause.Append("IN (SELECT UserID FROM " + this.databaseOwner + ".forums_Posts P WHERE ThreadID = T.ThreadID AND P.UserID = 0)");
}
}
#endregion
#region Thread Status
if (threadStatus != ThreadStatus.NotSet) {
switch (threadStatus) {
case ThreadStatus.Open:
whereClause.Append(" AND ThreadStatus = 0");
break;
case ThreadStatus.Closed:
whereClause.Append(" AND ThreadStatus = 0");
break;
case ThreadStatus.Resolved:
whereClause.Append(" AND ThreadStatus = 0");
break;
default:
break;
}
}
#endregion
#region Order By
switch (sortBy) {
case SortThreadsBy.LastPost:
if (sortOrder == SortOrder.Ascending) {
if (activeTopics || unansweredOnly)
orderClause.Append("ThreadDate");
else
orderClause.Append("IsSticky, StickyDate");
} else {
if (activeTopics || unansweredOnly)
orderClause.Append("ThreadDate DESC");
else
orderClause.Append("IsSticky DESC, StickyDate DESC");
}
break;
case SortThreadsBy.TotalRatings:
if (sortOrder == SortOrder.Ascending)
orderClause.Append("TotalRatings");
else
orderClause.Append("TotalRatings DESC");
break;
case SortThreadsBy.TotalReplies:
if (sortOrder == SortOrder.Ascending)
orderClause.Append("TotalReplies");
else
orderClause.Append("TotalReplies DESC");
break;
case SortThreadsBy.ThreadAuthor:
if (sortOrder == SortOrder.Ascending)
orderClause.Append("PostAuthor DESC");
else
orderClause.Append("PostAuthor");
break;
case SortThreadsBy.TotalViews:
if (sortOrder == SortOrder.Ascending)
orderClause.Append("TotalViews");
else
orderClause.Append("TotalViews DESC");
break;
}
#endregion
// Build the SQL statements
sqlCountSelect.Append(fromClause.ToString());
sqlCountSelect.Append(whereClause.ToString());
sqlPopulateSelect.Append(fromClause.ToString());
sqlPopulateSelect.Append(whereClause.ToString());
sqlPopulateSelect.Append(orderClause.ToString());
// Add Parameters to SPROC
//
command.Parameters.Add("@ForumID", SqlDbType.Int).Value = forumID;
command.Parameters.Add("@PageIndex", SqlDbType.Int, 4).Value = pageIndex;
command.Parameters.Add("@PageSize", SqlDbType.Int, 4).Value = pageSize;
command.Parameters.Add("@sqlCount", SqlDbType.NVarChar, 4000).Value = sqlCountSelect.ToString();
command.Parameters.Add("@sqlPopulate", SqlDbType.NVarChar, 4000).Value = sqlPopulateSelect.ToString();
command.Parameters.Add("@UserID", SqlDbType.Int).Value = userID;
command.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = returnRecordCount;
// Execute the command
connection.Open();
SqlDataReader dr = command.ExecuteReader();
// Populate the ThreadSet
//
while (dr.Read()) {
// Add threads
//
if (forumID == 0)
threadSet.Threads.Add( ForumsDataProvider.PopulatePrivateMessageFromIDataReader (dr) );
else
threadSet.Threads.Add( ForumsDataProvider.PopulateThreadFromIDataReader(dr) );
}
// Do we need to return record count?
//
if (returnRecordCount) {
dr.NextResult();
dr.Read();
// Read the total records
//
threadSet.TotalRecords = (int) dr[0];
}
// Get the recipients if this is a request for
// the private message list
if ((forumID == 0) && (dr.NextResult()) ) {
Hashtable recipientsLookupTable = new Hashtable();
while(dr.Read()) {
int threadID = (int) dr["ThreadID"];
if (recipientsLookupTable[threadID] == null) {
recipientsLookupTable[threadID] = new ArrayList();
}
((ArrayList) recipientsLookupTable[threadID]).Add(ForumsDataProvider.PopulateUserFromIDataReader(dr) );
}
// Map recipients to the threads
//
foreach (PrivateMessage thread in threadSet.Threads) {
thread.Recipients = (ArrayList) recipientsLookupTable[thread.ThreadID];
}
}
dr.Close();
connection.Close();
return threadSet;
}
}
#endregion
八.增加新方法
在Components/Threads.cs增加新的重载方法,以不必修改原来的方法调用.
// 为了不影响以前的程序,单独加一个重载方法,以获得收藏夹主题
public static ThreadSet GetThreads(int forumID, int pageIndex, int pageSize, int userID, DateTime threadsNewerThan, SortThreadsBy sortBy, SortOrder sortOrder, ThreadStatus threadStatus, ThreadUsersFilter userFilter, bool activeTopics, bool unreadOnly, bool unansweredOnly, bool returnRecordCount,bool favoriteOnly) // 多了一个参数favoriteOnly
{
ForumContext forumContext = ForumContext.Current;
string anonymousKey = "Thread-" + forumID + pageSize.ToString() + pageIndex.ToString() + threadsNewerThan.DayOfYear.ToString() + sortBy + sortOrder + activeTopics.ToString() + unansweredOnly.ToString() + favoriteOnly.ToString();
ThreadSet threadSet;
// If the user is anonymous take some load off the db
//
if (userID == 0)
{
if (forumContext.Context.Cache[anonymousKey] != null)
return (ThreadSet) forumContext.Context.Cache[anonymousKey];
}
// Create Instance of the IDataProvider
//
ForumsDataProvider dp = ForumsDataProvider.Instance();
// Get the threads
//
threadSet = dp.GetThreads(forumID, pageIndex, pageSize, userID, threadsNewerThan, sortBy, sortOrder, threadStatus, userFilter, activeTopics, unreadOnly, unansweredOnly, returnRecordCount,favoriteOnly);
if (userID == 0)
forumContext.Context.Cache.Insert(anonymousKey, threadSet, null, DateTime.Now.AddMinutes(2), TimeSpan.Zero, CacheItemPriority.Low, null);
return threadSet;
}
九.业务逻辑层
Components目录中增加Favorites.cs,实现主题的增加删除方法
public static void AddFavoritesPost (int userID,int threadID) {
ForumsDataProvider dp = ForumsDataProvider.Instance();
dp.CreateFavorites(userID, threadID);
}
/// <summary>
/// 删除收藏
/// </summary>
/// <param name="userID">用户ID</param>
/// <param name="deleteList">删除列表</param>
public static void DeleteFavorites (int userID, ArrayList deleteList) {
//
ForumsDataProvider dp = ForumsDataProvider.Instance();
dp.DeleteFavorites(userID, deleteList);
}
十.表现层调用
1.收藏夹主视图加载收藏主题列表
threadSet = Threads.GetThreads(forumID, pager.PageIndex, pager.PageSize, Users.GetUser().UserID, dateFilterValue, threadSortddl.SelectedValue, sortOrderddl.SelectedValue, ThreadStatus.NotSet, ThreadUsersFilter.All, false, hideReadPosts.SelectedValue, false, true,true);
注意最后一个参数是true,即返回收藏夹的数据集。
2.增加主题到收藏夹
Favorites.AddFavoritesPost(user.UserID,post.ThreadID);
HttpContext.Current.Response.Redirect(Globals.ApplicationPath+"/MyFavoritesAdd.aspx",true);
3.删除收藏的主题
Favorites.DeleteFavorites(…)
以增加收藏夹功能为实例,解析asp.net forums2结构流程及组件设计
最新推荐文章于 2018-07-20 18:38:12 发布