分享
 
 
 

以增加收藏夹功能为实例,解析asp.net forums2结构流程及组件设计

王朝asp·作者佚名  2006-01-31
窄屏简体版  字體: |||超大  

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(…)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有