Move uPowers and adjust uPowers namespaces to be correct

This commit is contained in:
Sebastiaan Janssen
2015-07-26 12:13:28 +02:00
parent 03ac890dd8
commit d8a80003e4
24 changed files with 1294 additions and 1321 deletions
-4
View File
@@ -4734,10 +4734,6 @@
<Project>{547c2d0d-1b55-493b-ae0b-e031a5b8ee77}</Project>
<Name>uForum</Name>
</ProjectReference>
<ProjectReference Include="..\uPowers\uPowers.csproj">
<Project>{00f050b9-e3ed-49a7-ab97-e8bec2513553}</Project>
<Name>uPowers</Name>
</ProjectReference>
<ProjectReference Include="..\uRelease\uRelease.csproj">
<Project>{c5b74e6a-abce-4a9a-896d-89c33fdafcd8}</Project>
<Name>uRelease</Name>
@@ -1,4 +1,5 @@
@inherits Umbraco.Web.Mvc.UmbracoViewPage<uForum.Models.ReadOnlyComment>
@using OurUmbraco.Powers.Library
@using uForum.Extensions
@{
@@ -45,7 +46,7 @@
<div class="highfive-count">
@Model.Score
</div>
@if (Members.IsLoggedIn() && !uPowers.Library.Utils.HasVoted(currentMember.Id, Model.Id, "powersComment"))
@if (Members.IsLoggedIn() && !Utils.HasVoted(currentMember.Id, Model.Id, "powersComment"))
{
if (currentMember.Id != Model.MemberId)
{
@@ -1,4 +1,5 @@
@inherits Umbraco.Web.Mvc.UmbracoViewPage<uForum.Models.Topic>
@using OurUmbraco.Powers.Library
@using uForum.Extensions
@{
@@ -42,7 +43,7 @@
<div class="highfive-count">
@Model.Score
</div>
@if (Members.IsLoggedIn() && !uPowers.Library.Utils.HasVoted(currentMember.Id, Model.Id, "powersTopic"))
@if (Members.IsLoggedIn() && !Utils.HasVoted(currentMember.Id, Model.Id, "powersTopic"))
{
if (currentMember.Id != Model.MemberId)
{
@@ -2,6 +2,7 @@
@using Marketplace.Providers
@using System.Xml;
@using System.Xml.XPath;
@using OurUmbraco.Powers.Library
@using Umbraco.Core
@{
@@ -43,7 +44,7 @@
var memId = umbraco.cms.businesslogic.member.Member.GetCurrentMember().Id;
var iterator = uPowers.Library.Xslt.ItemsVotedFor(memId, "powersproject").Current.Select("//id");
var iterator = Xslt.ItemsVotedFor(memId, "powersproject").Current.Select("//id");
while (iterator.MoveNext() && iterator.CurrentPosition < 20)
{
var node = (IHasXmlNode)iterator.Current;
+10
View File
@@ -249,6 +249,15 @@
<Compile Include="Events\Models\Event.cs" />
<Compile Include="Events\Relations\Event.cs" />
<Compile Include="Events\Relations\EventRelation.cs" />
<Compile Include="Powers\Api\PowersController.cs" />
<Compile Include="Powers\Buddha\Buddha.cs" />
<Compile Include="Powers\BusinessLogic\Action.cs" />
<Compile Include="Powers\BusinessLogic\Data.cs" />
<Compile Include="Powers\BusinessLogic\Events.cs" />
<Compile Include="Powers\BusinessLogic\Reputation.cs" />
<Compile Include="Powers\config.cs" />
<Compile Include="Powers\Library\Utils.cs" />
<Compile Include="Powers\Library\xslt.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository\Project.cs" />
<Compile Include="Repository\Projects.cs" />
@@ -283,6 +292,7 @@
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
<Content Include="Powers\uPowers.config" />
</ItemGroup>
<ItemGroup>
<Content Include="Repository\webservices\repository.asmx" />
@@ -1,9 +1,8 @@
using System.Linq;
using System.Web;
using System.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
namespace uPowers.Api
namespace OurUmbraco.Powers.Api
{
public class PowersController : UmbracoApiController
{
@@ -1,270 +1,270 @@
using System;
using System.IO;
using System.Xml;
using umbraco.DataLayer;
namespace uPowers.Buddha
{
public class Buddha : IDisposable
{
public string ConnectionString { get; set; }
public string WebRoot { get; set; }
private XmlDocument _config;
private ISqlHelper _sqlhelper;
private Char sep = System.IO.Path.DirectorySeparatorChar;
//settings
private int _top = 25;
public bool UseThreading { get; set; }
private string karmaDir = "upowers";
public Buddha(string connection, string root)
{
ConnectionString = connection;
WebRoot = root;
if (!Directory.Exists(WebRoot + sep + karmaDir))
Directory.CreateDirectory(WebRoot + sep + karmaDir);
_sqlhelper = DataLayerHelper.CreateSqlHelper(ConnectionString);
_config = new XmlDocument();
_config.Load(WebRoot + sep + "config" + sep + "uPowers.config");
}
//here we will calculate the /upowers/karma.xml file for all the overviews
public void CalculateKarma()
{
string file = WebRoot + sep + karmaDir + sep + "karma.xml";
XmlDocument doc = new XmlDocument();
string xml = BusinessLogic.Data.GetDataSetAsNode(ConnectionString, TotalKarmaSQL(365, 25), "karma").OuterXml;
doc.LoadXml(xml);
if (File.Exists(file))
File.Delete(file);
doc.Save(file);
doc = null;
}
//here we do all the detail, and dig into each individual member
public void CalculateKarmaHistory()
{
string memberSql = "SELECT nodeId from cmsMember";
IRecordsReader rr = _sqlhelper.ExecuteReader(memberSql);
while (rr.Read())
{
ProcessMember( rr.GetInt("nodeId") );
}
}
//here we process the individual member
public void ProcessMember(int memberId)
{
string karmaRoot = Path.Combine(WebRoot, karmaDir);
string memberKarmaFile = Path.Combine(karmaRoot, memberId.ToString() + ".xml");
XmlDocument doc = new XmlDocument();
string xml = "<karma>" + BusinessLogic.Data.GetDataSetAsNode(ConnectionString, MemberKarmaSummarySQL(memberId), "summary").OuterXml;
xml += BusinessLogic.Data.GetDataSetAsNode(ConnectionString, MemberKarmaHistorySQL(memberId), "history").OuterXml + "</karma>";
doc.LoadXml(xml);
string forumTopics = "SELECT count(id) from forumTopics WHERE memberID = " + memberId.ToString();
string forumComments = "SELECT count(id) from forumComments WHERE memberID = " + memberId.ToString();
int topicCount = _sqlhelper.ExecuteScalar<int>(forumTopics);
int commentCount = _sqlhelper.ExecuteScalar<int>(forumComments);
XmlNode karma = doc.SelectSingleNode("//karma");
XmlNode forum = umbraco.xmlHelper.addTextNode(doc, "forum","");
forum.AppendChild( umbraco.xmlHelper.addTextNode(doc, "topics", topicCount.ToString()));
forum.AppendChild(umbraco.xmlHelper.addTextNode(doc, "comments", commentCount.ToString()));
karma.AppendChild(forum);
if (File.Exists(memberKarmaFile))
File.Delete(memberKarmaFile);
doc.Save(memberKarmaFile);
doc = null;
}
//for each type the member has karmapoints in, we will process the points
public void ProcessType(string alias)
{
}
public static string TotalKarmaSQL(int days, int topCount)
{
string where = string.Format("where DATEDIFF(DAY, date, GETDATE()) < {0}", days);
string top = string.Format("TOP {0}", topCount);
if (days <= 0)
where = "";
if (topCount <= 0)
top = "";
return string.Format(@"with score as(
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints) as received
FROM [powersTopic]
{0}
group by receiverId
UNION ALL
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersProject]
{0}
GROUP BY receiverId
UNION ALL
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersComment]
{0}
GROUP BY receiverId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM [powersComment]
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersProject
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersTopic
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersWiki
{0}
GROUP BY memberId
)
select {1} text as memberName, memberId, sum(performed) as performed, SUM(received) as received, (sum(received) + sum(performed)) as totalPoints from score
inner join umbracoNode ON memberId = id
where memberId IS NOT NULL and memberId > 0
group by text, memberId order by totalPoints DESC", where, top);
}
public static string MemberKarmaSummarySQL(int memberId)
{
return string.Format(@"SELECT 'topic' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints) as received
FROM [powersTopic]
where receiverId = {0}
group by receiverId
UNION ALL
SELECT 'project' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersProject]
where receiverId = {0}
GROUP BY receiverId
UNION ALL
SELECT 'comment' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersComment]
where receiverId = {0}
GROUP BY receiverId
UNION ALL
SELECT 'comment' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM [powersComment]
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'project' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersProject
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'topic' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersTopic
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'wiki' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersWiki
where receiverId = {0}
GROUP BY memberId", memberId);
}
public static string MemberKarmaHistorySQL(int memberId)
{
return string.Format( @"
SELECT id, 'topic' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersTopic]
where receiverId = {0}
UNION ALL
SELECT id, 'project' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersProject]
where receiverId = {0}
UNION ALL
SELECT id, 'comment' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersComment]
where receiverId = {0}
UNION ALL
SELECT id, 'comment' as alias, memberId, performerPoints as performed, 0 as received
FROM [powersComment]
where memberId = {0}
UNION ALL
SELECT id, 'project' as alias, memberId, performerPoints as performed, 0 as received
FROM powersProject
where memberId = {0}
UNION ALL
SELECT id, 'topic' as alias, memberId, performerPoints as performed, 0 as received
FROM powersTopic
where memberId = {0}
UNION ALL
SELECT id, 'wiki' as alias, memberId, performerPoints as performed, 0 as received
FROM powersWiki
where receiverId = {0}
", memberId);
}
#region IDisposable Members
public void Dispose()
{
_config = null;
_sqlhelper.Dispose();
_sqlhelper = null;
}
#endregion
}
}
using System;
using System.IO;
using System.Xml;
using umbraco.DataLayer;
namespace OurUmbraco.Powers.Buddha
{
public class Buddha : IDisposable
{
public string ConnectionString { get; set; }
public string WebRoot { get; set; }
private XmlDocument _config;
private ISqlHelper _sqlhelper;
private Char sep = System.IO.Path.DirectorySeparatorChar;
//settings
private int _top = 25;
public bool UseThreading { get; set; }
private string karmaDir = "upowers";
public Buddha(string connection, string root)
{
ConnectionString = connection;
WebRoot = root;
if (!Directory.Exists(WebRoot + sep + karmaDir))
Directory.CreateDirectory(WebRoot + sep + karmaDir);
_sqlhelper = DataLayerHelper.CreateSqlHelper(ConnectionString);
_config = new XmlDocument();
_config.Load(WebRoot + sep + "config" + sep + "uPowers.config");
}
//here we will calculate the /upowers/karma.xml file for all the overviews
public void CalculateKarma()
{
string file = WebRoot + sep + karmaDir + sep + "karma.xml";
XmlDocument doc = new XmlDocument();
string xml = BusinessLogic.Data.GetDataSetAsNode(ConnectionString, TotalKarmaSQL(365, 25), "karma").OuterXml;
doc.LoadXml(xml);
if (File.Exists(file))
File.Delete(file);
doc.Save(file);
doc = null;
}
//here we do all the detail, and dig into each individual member
public void CalculateKarmaHistory()
{
string memberSql = "SELECT nodeId from cmsMember";
IRecordsReader rr = _sqlhelper.ExecuteReader(memberSql);
while (rr.Read())
{
ProcessMember( rr.GetInt("nodeId") );
}
}
//here we process the individual member
public void ProcessMember(int memberId)
{
string karmaRoot = Path.Combine(WebRoot, karmaDir);
string memberKarmaFile = Path.Combine(karmaRoot, memberId.ToString() + ".xml");
XmlDocument doc = new XmlDocument();
string xml = "<karma>" + BusinessLogic.Data.GetDataSetAsNode(ConnectionString, MemberKarmaSummarySQL(memberId), "summary").OuterXml;
xml += BusinessLogic.Data.GetDataSetAsNode(ConnectionString, MemberKarmaHistorySQL(memberId), "history").OuterXml + "</karma>";
doc.LoadXml(xml);
string forumTopics = "SELECT count(id) from forumTopics WHERE memberID = " + memberId.ToString();
string forumComments = "SELECT count(id) from forumComments WHERE memberID = " + memberId.ToString();
int topicCount = _sqlhelper.ExecuteScalar<int>(forumTopics);
int commentCount = _sqlhelper.ExecuteScalar<int>(forumComments);
XmlNode karma = doc.SelectSingleNode("//karma");
XmlNode forum = umbraco.xmlHelper.addTextNode(doc, "forum","");
forum.AppendChild( umbraco.xmlHelper.addTextNode(doc, "topics", topicCount.ToString()));
forum.AppendChild(umbraco.xmlHelper.addTextNode(doc, "comments", commentCount.ToString()));
karma.AppendChild(forum);
if (File.Exists(memberKarmaFile))
File.Delete(memberKarmaFile);
doc.Save(memberKarmaFile);
doc = null;
}
//for each type the member has karmapoints in, we will process the points
public void ProcessType(string alias)
{
}
public static string TotalKarmaSQL(int days, int topCount)
{
string where = string.Format("where DATEDIFF(DAY, date, GETDATE()) < {0}", days);
string top = string.Format("TOP {0}", topCount);
if (days <= 0)
where = "";
if (topCount <= 0)
top = "";
return string.Format(@"with score as(
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints) as received
FROM [powersTopic]
{0}
group by receiverId
UNION ALL
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersProject]
{0}
GROUP BY receiverId
UNION ALL
SELECT receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersComment]
{0}
GROUP BY receiverId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM [powersComment]
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersProject
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersTopic
{0}
GROUP BY memberId
UNION ALL
SELECT memberId, SUM(performerPoints)as performed, 0 as received
FROM powersWiki
{0}
GROUP BY memberId
)
select {1} text as memberName, memberId, sum(performed) as performed, SUM(received) as received, (sum(received) + sum(performed)) as totalPoints from score
inner join umbracoNode ON memberId = id
where memberId IS NOT NULL and memberId > 0
group by text, memberId order by totalPoints DESC", where, top);
}
public static string MemberKarmaSummarySQL(int memberId)
{
return string.Format(@"SELECT 'topic' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints) as received
FROM [powersTopic]
where receiverId = {0}
group by receiverId
UNION ALL
SELECT 'project' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersProject]
where receiverId = {0}
GROUP BY receiverId
UNION ALL
SELECT 'comment' as alias, receiverId AS memberId, 0 as performed, SUM(receiverPoints)as received
FROM [powersComment]
where receiverId = {0}
GROUP BY receiverId
UNION ALL
SELECT 'comment' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM [powersComment]
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'project' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersProject
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'topic' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersTopic
where memberId = {0}
GROUP BY memberId
UNION ALL
SELECT 'wiki' as alias, memberId, SUM(performerPoints)as performed, 0 as received
FROM powersWiki
where receiverId = {0}
GROUP BY memberId", memberId);
}
public static string MemberKarmaHistorySQL(int memberId)
{
return string.Format( @"
SELECT id, 'topic' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersTopic]
where receiverId = {0}
UNION ALL
SELECT id, 'project' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersProject]
where receiverId = {0}
UNION ALL
SELECT id, 'comment' as alias, receiverId AS memberId, 0 as performed, receiverPoints as received
FROM [powersComment]
where receiverId = {0}
UNION ALL
SELECT id, 'comment' as alias, memberId, performerPoints as performed, 0 as received
FROM [powersComment]
where memberId = {0}
UNION ALL
SELECT id, 'project' as alias, memberId, performerPoints as performed, 0 as received
FROM powersProject
where memberId = {0}
UNION ALL
SELECT id, 'topic' as alias, memberId, performerPoints as performed, 0 as received
FROM powersTopic
where memberId = {0}
UNION ALL
SELECT id, 'wiki' as alias, memberId, performerPoints as performed, 0 as received
FROM powersWiki
where receiverId = {0}
", memberId);
}
#region IDisposable Members
public void Dispose()
{
_config = null;
_sqlhelper.Dispose();
_sqlhelper = null;
}
#endregion
}
}
@@ -1,206 +1,204 @@
using System;
using System.Collections.Generic;
using System.Xml;
using System.Web;
using umbraco.cms.businesslogic.member;
namespace uPowers.BusinessLogic {
public class Action {
public string Alias { get; set; }
public string TypeAlias { get; set; }
public int PerformerReward { get; set; }
public int ReceiverReward { get; set; }
public int Weight { get; set; }
public bool MandatoryComment { get; set; }
public int MinimumReputation { get; set; }
public bool Exists { get; private set; }
private static int _minCommentLenght = 50;
public string[] AllowedGroups { get; set; }
public string DataBaseTable {
get{
return "powers" + TypeAlias;
}
}
private Events _e = new Events();
public bool Perform(int performer, int itemId, string comment) {
return Perform(performer, itemId, 0, comment);
}
public void ClearVotes(int performer, int itemId) {
Data.SqlHelper.ExecuteNonQuery("Delete FROM " + DataBaseTable + " WHERE memberId = @memberId AND id = @id",
Data.SqlHelper.CreateParameter("@memberId", performer),
Data.SqlHelper.CreateParameter("@id", itemId));
}
public bool Perform(int performer, int itemId, int receiver, string comment) {
ActionEventArgs e = new ActionEventArgs();
e.PerformerId = performer;
e.ItemId = itemId;
e.ReceiverId = receiver;
e.ActionType = TypeAlias;
FireBeforePerform(e);
if (!e.Cancel) {
bool allowed = Allowed(performer, itemId, receiver, comment);
if (allowed)
{
Data.SqlHelper.ExecuteNonQuery("INSERT INTO " + DataBaseTable + "(id, memberId, points, receiverId, receiverPoints, performerPoints, comment) VALUES(@id, @memberId, @points, @receiverId, @receiverPoints, @performerPoints, @comment)",
Data.SqlHelper.CreateParameter("@id", e.ItemId),
Data.SqlHelper.CreateParameter("@table", DataBaseTable),
Data.SqlHelper.CreateParameter("@memberId", e.PerformerId),
Data.SqlHelper.CreateParameter("@points", Weight),
Data.SqlHelper.CreateParameter("@receiverid", e.ReceiverId),
Data.SqlHelper.CreateParameter("@receiverPoints", ReceiverReward),
Data.SqlHelper.CreateParameter("@performerPoints", PerformerReward),
Data.SqlHelper.CreateParameter("@comment", comment + " ")
);
//the performer gets his share
if(PerformerReward != 0){
Reputation r = new Reputation(e.PerformerId);
r.Current = (r.Current + (PerformerReward) );
r.Total = (r.Total + (PerformerReward) );
r.Save();
}
//And maybe the author of the item gets a cut as well..
if (e.ReceiverId > 0 && ReceiverReward != 0) {
Reputation pr = new Reputation(e.ReceiverId);
pr.Current = (pr.Current + (ReceiverReward) );
pr.Total = (pr.Total + (ReceiverReward));
pr.Save();
}
//And maybe there are some additional receivers
if (e.ExtraReceivers != null)
{
foreach (int r in e.ExtraReceivers)
{
if (allowed)
{
//make sure the extra receivers also get inserted (but no points for item and performer)
Data.SqlHelper.ExecuteNonQuery("INSERT INTO " + DataBaseTable + "(id, memberId, points, receiverId, receiverPoints, performerPoints, comment) VALUES(@id, @memberId, @points, @receiverId, @receiverPoints, @performerPoints, @comment)",
Data.SqlHelper.CreateParameter("@id", e.ItemId),
Data.SqlHelper.CreateParameter("@table", DataBaseTable),
Data.SqlHelper.CreateParameter("@memberId", e.PerformerId),
Data.SqlHelper.CreateParameter("@points", 0),
Data.SqlHelper.CreateParameter("@receiverid", r),
Data.SqlHelper.CreateParameter("@receiverPoints", ReceiverReward),
Data.SqlHelper.CreateParameter("@performerPoints", 0),
Data.SqlHelper.CreateParameter("@comment", comment + " "));
}
Reputation pr = new Reputation(r);
pr.Current = (pr.Current + (ReceiverReward));
pr.Total = (pr.Total + (ReceiverReward));
pr.Save();
}
}
FireAfterPerform(e);
return true;
}
}
return false;
}
public bool Allowed(int performer, int id, int receiver, string comment) {
if (performer > 0 && (!MandatoryComment || (MandatoryComment && comment.Length >= _minCommentLenght) )) {
if (AllowedGroups != null && AllowedGroups.Length > 0)
{
bool allowed = false;
foreach(string group in AllowedGroups)
if(Library.Utils.IsMemberInGroup(group, performer)){
allowed = true;
break;
}
if(!allowed)
return false;
}
Reputation r = new Reputation(performer);
bool doneBefore = Data.SqlHelper.ExecuteScalar<int>("SELECT count(id) from " + DataBaseTable + " WHERE id = @id and memberId = @memberId",
Data.SqlHelper.CreateParameter("@id", id),
Data.SqlHelper.CreateParameter("@memberId", performer)
) > 0;
return ( (MinimumReputation <= r.Current) && !doneBefore && performer != receiver);
} else
return false;
}
public Action(string alias) {
XmlNode x = config.GetKeyAsNode("/configuration/actions/action [@alias = '" + alias + "']");
if (x != null) {
Weight = int.Parse( x.Attributes.GetNamedItem("weight" ).Value);
ReceiverReward = int.Parse(x.Attributes.GetNamedItem("receiverReward").Value);
PerformerReward = int.Parse(x.Attributes.GetNamedItem("performerReward").Value);
MinimumReputation = int.Parse(x.Attributes.GetNamedItem("minReputation").Value);
Alias = x.Attributes.GetNamedItem("alias").Value;
TypeAlias = x.Attributes.GetNamedItem("type").Value;
bool _mandatoryComment = false;
if (x.Attributes.GetNamedItem("mandatoryComment") != null)
bool.TryParse(x.Attributes.GetNamedItem("mandatoryComment").Value, out _mandatoryComment);
if (x.Attributes.GetNamedItem("allowedGroups") != null)
AllowedGroups = x.Attributes.GetNamedItem("allowedGroups").Value.Split(',');
MandatoryComment = _mandatoryComment;
Exists = true;
} else
Exists = false;
}
public static List<Action> GetAllActions() {
XmlNode x = config.GetKeyAsNode("/configuration/actions");
List<Action> l = new List<Action>();
foreach (XmlNode cx in x.ChildNodes) {
if (cx.Attributes.GetNamedItem("alias") != null)
l.Add( new Action( cx.Attributes.GetNamedItem("alias").Value ));
}
return l;
}
/* EVENTS */
public static event EventHandler<ActionEventArgs> BeforePerform;
protected virtual void FireBeforePerform(ActionEventArgs e) {
_e.FireCancelableEvent(BeforePerform, this, e);
}
public static event EventHandler<ActionEventArgs> AfterPerform;
protected virtual void FireAfterPerform(ActionEventArgs e) {
if (AfterPerform != null)
AfterPerform(this, e);
}
}
using System;
using System.Collections.Generic;
using System.Xml;
namespace OurUmbraco.Powers.BusinessLogic {
public class Action {
public string Alias { get; set; }
public string TypeAlias { get; set; }
public int PerformerReward { get; set; }
public int ReceiverReward { get; set; }
public int Weight { get; set; }
public bool MandatoryComment { get; set; }
public int MinimumReputation { get; set; }
public bool Exists { get; private set; }
private static int _minCommentLenght = 50;
public string[] AllowedGroups { get; set; }
public string DataBaseTable {
get{
return "powers" + TypeAlias;
}
}
private Events _e = new Events();
public bool Perform(int performer, int itemId, string comment) {
return Perform(performer, itemId, 0, comment);
}
public void ClearVotes(int performer, int itemId) {
Data.SqlHelper.ExecuteNonQuery("Delete FROM " + DataBaseTable + " WHERE memberId = @memberId AND id = @id",
Data.SqlHelper.CreateParameter("@memberId", performer),
Data.SqlHelper.CreateParameter("@id", itemId));
}
public bool Perform(int performer, int itemId, int receiver, string comment) {
ActionEventArgs e = new ActionEventArgs();
e.PerformerId = performer;
e.ItemId = itemId;
e.ReceiverId = receiver;
e.ActionType = TypeAlias;
FireBeforePerform(e);
if (!e.Cancel) {
bool allowed = Allowed(performer, itemId, receiver, comment);
if (allowed)
{
Data.SqlHelper.ExecuteNonQuery("INSERT INTO " + DataBaseTable + "(id, memberId, points, receiverId, receiverPoints, performerPoints, comment) VALUES(@id, @memberId, @points, @receiverId, @receiverPoints, @performerPoints, @comment)",
Data.SqlHelper.CreateParameter("@id", e.ItemId),
Data.SqlHelper.CreateParameter("@table", DataBaseTable),
Data.SqlHelper.CreateParameter("@memberId", e.PerformerId),
Data.SqlHelper.CreateParameter("@points", Weight),
Data.SqlHelper.CreateParameter("@receiverid", e.ReceiverId),
Data.SqlHelper.CreateParameter("@receiverPoints", ReceiverReward),
Data.SqlHelper.CreateParameter("@performerPoints", PerformerReward),
Data.SqlHelper.CreateParameter("@comment", comment + " ")
);
//the performer gets his share
if(PerformerReward != 0){
Reputation r = new Reputation(e.PerformerId);
r.Current = (r.Current + (PerformerReward) );
r.Total = (r.Total + (PerformerReward) );
r.Save();
}
//And maybe the author of the item gets a cut as well..
if (e.ReceiverId > 0 && ReceiverReward != 0) {
Reputation pr = new Reputation(e.ReceiverId);
pr.Current = (pr.Current + (ReceiverReward) );
pr.Total = (pr.Total + (ReceiverReward));
pr.Save();
}
//And maybe there are some additional receivers
if (e.ExtraReceivers != null)
{
foreach (int r in e.ExtraReceivers)
{
if (allowed)
{
//make sure the extra receivers also get inserted (but no points for item and performer)
Data.SqlHelper.ExecuteNonQuery("INSERT INTO " + DataBaseTable + "(id, memberId, points, receiverId, receiverPoints, performerPoints, comment) VALUES(@id, @memberId, @points, @receiverId, @receiverPoints, @performerPoints, @comment)",
Data.SqlHelper.CreateParameter("@id", e.ItemId),
Data.SqlHelper.CreateParameter("@table", DataBaseTable),
Data.SqlHelper.CreateParameter("@memberId", e.PerformerId),
Data.SqlHelper.CreateParameter("@points", 0),
Data.SqlHelper.CreateParameter("@receiverid", r),
Data.SqlHelper.CreateParameter("@receiverPoints", ReceiverReward),
Data.SqlHelper.CreateParameter("@performerPoints", 0),
Data.SqlHelper.CreateParameter("@comment", comment + " "));
}
Reputation pr = new Reputation(r);
pr.Current = (pr.Current + (ReceiverReward));
pr.Total = (pr.Total + (ReceiverReward));
pr.Save();
}
}
FireAfterPerform(e);
return true;
}
}
return false;
}
public bool Allowed(int performer, int id, int receiver, string comment) {
if (performer > 0 && (!MandatoryComment || (MandatoryComment && comment.Length >= _minCommentLenght) )) {
if (AllowedGroups != null && AllowedGroups.Length > 0)
{
bool allowed = false;
foreach(string group in AllowedGroups)
if(Library.Utils.IsMemberInGroup(group, performer)){
allowed = true;
break;
}
if(!allowed)
return false;
}
Reputation r = new Reputation(performer);
bool doneBefore = Data.SqlHelper.ExecuteScalar<int>("SELECT count(id) from " + DataBaseTable + " WHERE id = @id and memberId = @memberId",
Data.SqlHelper.CreateParameter("@id", id),
Data.SqlHelper.CreateParameter("@memberId", performer)
) > 0;
return ( (MinimumReputation <= r.Current) && !doneBefore && performer != receiver);
} else
return false;
}
public Action(string alias) {
XmlNode x = config.GetKeyAsNode("/configuration/actions/action [@alias = '" + alias + "']");
if (x != null) {
Weight = int.Parse( x.Attributes.GetNamedItem("weight" ).Value);
ReceiverReward = int.Parse(x.Attributes.GetNamedItem("receiverReward").Value);
PerformerReward = int.Parse(x.Attributes.GetNamedItem("performerReward").Value);
MinimumReputation = int.Parse(x.Attributes.GetNamedItem("minReputation").Value);
Alias = x.Attributes.GetNamedItem("alias").Value;
TypeAlias = x.Attributes.GetNamedItem("type").Value;
bool _mandatoryComment = false;
if (x.Attributes.GetNamedItem("mandatoryComment") != null)
bool.TryParse(x.Attributes.GetNamedItem("mandatoryComment").Value, out _mandatoryComment);
if (x.Attributes.GetNamedItem("allowedGroups") != null)
AllowedGroups = x.Attributes.GetNamedItem("allowedGroups").Value.Split(',');
MandatoryComment = _mandatoryComment;
Exists = true;
} else
Exists = false;
}
public static List<Action> GetAllActions() {
XmlNode x = config.GetKeyAsNode("/configuration/actions");
List<Action> l = new List<Action>();
foreach (XmlNode cx in x.ChildNodes) {
if (cx.Attributes.GetNamedItem("alias") != null)
l.Add( new Action( cx.Attributes.GetNamedItem("alias").Value ));
}
return l;
}
/* EVENTS */
public static event EventHandler<ActionEventArgs> BeforePerform;
protected virtual void FireBeforePerform(ActionEventArgs e) {
_e.FireCancelableEvent(BeforePerform, this, e);
}
public static event EventHandler<ActionEventArgs> AfterPerform;
protected virtual void FireAfterPerform(ActionEventArgs e) {
if (AfterPerform != null)
AfterPerform(this, e);
}
}
}
@@ -1,445 +1,442 @@
using System;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.XPath;
using umbraco.DataLayer;
namespace uPowers.BusinessLogic {
public class Data {
private static string _ConnString = umbraco.GlobalSettings.DbDSN;
private static ISqlHelper _sqlHelper;
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
public static ISqlHelper SqlHelper {
get {
if (_sqlHelper == null) {
try {
_sqlHelper = DataLayerHelper.CreateSqlHelper(_ConnString);
} catch { }
}
return _sqlHelper;
}
}
public static XmlNode GetDataSetAsNode(string connectionstring, string sql, string elementName)
{
try
{
DataSet ds = getDataSetFromSql(connectionstring, sql, elementName);
XmlDataDocument dataDoc = new XmlDataDocument(ds);
return (XmlNode)dataDoc;
}
catch (Exception e)
{
// If there's an exception we'll output an error element instead
XmlDocument errorDoc = new XmlDocument();
return umbraco.xmlHelper.addTextNode(errorDoc, "error", System.Web.HttpUtility.HtmlEncode(e.ToString()));
}
}
public static XmlNode GetDataSetAsNode(string sql, string elementName) {
return GetDataSetAsNode(_ConnString, sql, elementName);
}
public static XPathNodeIterator GetDataSet(string sql, string elementName) {
return GetDataSetAsNode(sql, elementName).CreateNavigator().Select(".");
}
/// <summary>
/// Gets the dataset from SQL using ADO.NET.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="sql">The SQL.</param>
/// <param name="setName">Name of the set.</param>
/// <returns></returns>
private static DataSet getDataSetFromSql(string connection, string sql, string tableName) {
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(Pluralizer.ToPlural(tableName));
try {
con.Open();
adapter.Fill(ds, tableName);
} finally {
con.Close();
}
return ds;
}
/* **********************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This source code is subject to terms and conditions of the Microsoft Permissive
* License (MS-PL). A copy of the license can be found in the license.htm file
* included in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* **********************************************************************************/
public static class Pluralizer {
#region public APIs
public static string ToPlural(string noun) {
return AdjustCase(ToPluralInternal(noun), noun);
}
public static string ToSingular(string noun) {
return AdjustCase(ToSingularInternal(noun), noun);
}
public static bool IsNounPluralOfNoun(string plural, string singular) {
return String.Compare(ToSingularInternal(plural), singular, StringComparison.OrdinalIgnoreCase) == 0;
}
#endregion
#region Special Words Table
static string[] _specialWordsStringTable = new string[] {
"agendum", "agenda", "",
"albino", "albinos", "",
"alga", "algae", "",
"alumna", "alumnae", "",
"apex", "apices", "apexes",
"archipelago", "archipelagos", "",
"bacterium", "bacteria", "",
"beef", "beefs", "beeves",
"bison", "", "",
"brother", "brothers", "brethren",
"candelabrum", "candelabra", "",
"carp", "", "",
"casino", "casinos", "",
"child", "children", "",
"chassis", "", "",
"chinese", "", "",
"clippers", "", "",
"cod", "", "",
"codex", "codices", "",
"commando", "commandos", "",
"corps", "", "",
"cortex", "cortices", "cortexes",
"cow", "cows", "kine",
"criterion", "criteria", "",
"datum", "data", "",
"debris", "", "",
"diabetes", "", "",
"ditto", "dittos", "",
"djinn", "", "",
"dynamo", "", "",
"elk", "", "",
"embryo", "embryos", "",
"ephemeris", "ephemeris", "ephemerides",
"erratum", "errata", "",
"extremum", "extrema", "",
"fiasco", "fiascos", "",
"fish", "fishes", "fish",
"flounder", "", "",
"focus", "focuses", "foci",
"fungus", "fungi", "funguses",
"gallows", "", "",
"genie", "genies", "genii",
"ghetto", "ghettos", "",
"graffiti", "", "",
"headquarters", "", "",
"herpes", "", "",
"homework", "", "",
"index", "indices", "indexes",
"inferno", "infernos", "",
"japanese", "", "",
"jumbo", "jumbos", "",
"latex", "latices", "latexes",
"lingo", "lingos", "",
"mackerel", "", "",
"macro", "macros", "",
"manifesto", "manifestos", "",
"measles", "", "",
"money", "moneys", "monies",
"mongoose", "mongooses", "mongoose",
"mumps", "", "",
"murex", "murecis", "",
"mythos", "mythos", "mythoi",
"news", "", "",
"octopus", "octopuses", "octopodes",
"ovum", "ova", "",
"ox", "ox", "oxen",
"photo", "photos", "",
"pincers", "", "",
"pliers", "", "",
"pro", "pros", "",
"rabies", "", "",
"radius", "radiuses", "radii",
"rhino", "rhinos", "",
"salmon", "", "",
"scissors", "", "",
"series", "", "",
"shears", "", "",
"silex", "silices", "",
"simplex", "simplices", "simplexes",
"soliloquy", "soliloquies", "soliloquy",
"species", "", "",
"stratum", "strata", "",
"swine", "", "",
"trout", "", "",
"tuna", "", "",
"vertebra", "vertebrae", "",
"vertex", "vertices", "vertexes",
"vortex", "vortices", "vortexes",
};
#endregion
#region Suffix Rules Table
static string[] _suffixRulesStringTable = new string[] {
"ch", "ches",
"sh", "shes",
"ss", "sses",
"ay", "ays",
"ey", "eys",
"iy", "iys",
"oy", "oys",
"uy", "uys",
"y", "ies",
"ao", "aos",
"eo", "eos",
"io", "ios",
"oo", "oos",
"uo", "uos",
"o", "oes",
"cis", "ces",
"sis", "ses",
"xis", "xes",
"louse", "lice",
"mouse", "mice",
"zoon", "zoa",
"man", "men",
"deer", "deer",
"fish", "fish",
"sheep", "sheep",
"itis", "itis",
"ois", "ois",
"pox", "pox",
"ox", "oxes",
"foot", "feet",
"goose", "geese",
"tooth", "teeth",
"alf", "alves",
"elf", "elves",
"olf", "olves",
"arf", "arves",
"leaf", "leaves",
"nife", "nives",
"life", "lives",
"wife", "wives",
};
#endregion
#region Implementation Details
class Word {
public readonly string Singular;
public readonly string Plural;
public readonly string Plural2;
public Word(string singular, string plural, string plural2) {
Singular = singular;
Plural = plural;
Plural2 = plural2;
}
}
class SuffixRule {
string _singularSuffix;
string _pluralSuffix;
public SuffixRule(string singular, string plural) {
_singularSuffix = singular;
_pluralSuffix = plural;
}
public bool TryToPlural(string word, out string plural) {
if (word.EndsWith(_singularSuffix, StringComparison.OrdinalIgnoreCase)) {
plural = word.Substring(0, word.Length - _singularSuffix.Length) + _pluralSuffix;
return true;
} else {
plural = null;
return false;
}
}
public bool TryToSingular(string word, out string singular) {
if (word.EndsWith(_pluralSuffix, StringComparison.OrdinalIgnoreCase)) {
singular = word.Substring(0, word.Length - _pluralSuffix.Length) + _singularSuffix;
return true;
} else {
singular = null;
return false;
}
}
}
static Dictionary<string, Word> _specialSingulars;
static Dictionary<string, Word> _specialPlurals;
static List<SuffixRule> _suffixRules;
static Pluralizer() {
// populate lookup tables for special words
_specialSingulars = new Dictionary<string, Word>(StringComparer.OrdinalIgnoreCase);
_specialPlurals = new Dictionary<string, Word>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < _specialWordsStringTable.Length; i += 3) {
string s = _specialWordsStringTable[i];
string p = _specialWordsStringTable[i + 1];
string p2 = _specialWordsStringTable[i + 2];
if (string.IsNullOrEmpty(p)) {
p = s;
}
Word w = new Word(s, p, p2);
_specialSingulars.Add(s, w);
_specialPlurals.Add(p, w);
if (!string.IsNullOrEmpty(p2)) {
_specialPlurals.Add(p2, w);
}
}
// populate suffix rules list
_suffixRules = new List<SuffixRule>();
for (int i = 0; i < _suffixRulesStringTable.Length; i += 2) {
string singular = _suffixRulesStringTable[i];
string plural = _suffixRulesStringTable[i + 1];
_suffixRules.Add(new SuffixRule(singular, plural));
}
}
static string ToPluralInternal(string s) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// lookup special words
Word word;
if (_specialSingulars.TryGetValue(s, out word)) {
return word.Plural;
}
// apply suffix rules
string plural;
foreach (SuffixRule rule in _suffixRules) {
if (rule.TryToPlural(s, out plural)) {
return plural;
}
}
// apply the default rule
return s + "s";
}
static string ToSingularInternal(string s) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// lookup special words
Word word;
if (_specialPlurals.TryGetValue(s, out word)) {
return word.Singular;
}
// apply suffix rules
string singular;
foreach (SuffixRule rule in _suffixRules) {
if (rule.TryToSingular(s, out singular)) {
return singular;
}
}
// apply the default rule
if (s.EndsWith("s", StringComparison.OrdinalIgnoreCase)) {
return s.Substring(0, s.Length - 1);
}
return s;
}
static string AdjustCase(string s, string template) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// determine the type of casing of the template string
bool foundUpperOrLower = false;
bool allLower = true;
bool allUpper = true;
bool firstUpper = false;
for (int i = 0; i < template.Length; i++) {
if (Char.IsUpper(template[i])) {
if (i == 0) firstUpper = true;
allLower = false;
foundUpperOrLower = true;
} else if (Char.IsLower(template[i])) {
allUpper = false;
foundUpperOrLower = true;
}
}
// change the case according to template
if (foundUpperOrLower) {
if (allLower) {
s = s.ToLowerInvariant();
} else if (allUpper) {
s = s.ToUpperInvariant();
} else if (firstUpper) {
if (!Char.IsUpper(s[0])) {
s = s.Substring(0, 1).ToUpperInvariant() + s.Substring(1);
}
}
}
return s;
}
#endregion
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.XPath;
using umbraco.DataLayer;
namespace OurUmbraco.Powers.BusinessLogic {
public class Data {
private static string _ConnString = umbraco.GlobalSettings.DbDSN;
private static ISqlHelper _sqlHelper;
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
public static ISqlHelper SqlHelper {
get {
if (_sqlHelper == null) {
try {
_sqlHelper = DataLayerHelper.CreateSqlHelper(_ConnString);
} catch { }
}
return _sqlHelper;
}
}
public static XmlNode GetDataSetAsNode(string connectionstring, string sql, string elementName)
{
try
{
DataSet ds = getDataSetFromSql(connectionstring, sql, elementName);
XmlDataDocument dataDoc = new XmlDataDocument(ds);
return (XmlNode)dataDoc;
}
catch (Exception e)
{
// If there's an exception we'll output an error element instead
XmlDocument errorDoc = new XmlDocument();
return umbraco.xmlHelper.addTextNode(errorDoc, "error", System.Web.HttpUtility.HtmlEncode(e.ToString()));
}
}
public static XmlNode GetDataSetAsNode(string sql, string elementName) {
return GetDataSetAsNode(_ConnString, sql, elementName);
}
public static XPathNodeIterator GetDataSet(string sql, string elementName) {
return GetDataSetAsNode(sql, elementName).CreateNavigator().Select(".");
}
/// <summary>
/// Gets the dataset from SQL using ADO.NET.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="sql">The SQL.</param>
/// <param name="setName">Name of the set.</param>
/// <returns></returns>
private static DataSet getDataSetFromSql(string connection, string sql, string tableName) {
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(Pluralizer.ToPlural(tableName));
try {
con.Open();
adapter.Fill(ds, tableName);
} finally {
con.Close();
}
return ds;
}
/* **********************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This source code is subject to terms and conditions of the Microsoft Permissive
* License (MS-PL). A copy of the license can be found in the license.htm file
* included in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* **********************************************************************************/
public static class Pluralizer {
#region public APIs
public static string ToPlural(string noun) {
return AdjustCase(ToPluralInternal(noun), noun);
}
public static string ToSingular(string noun) {
return AdjustCase(ToSingularInternal(noun), noun);
}
public static bool IsNounPluralOfNoun(string plural, string singular) {
return String.Compare(ToSingularInternal(plural), singular, StringComparison.OrdinalIgnoreCase) == 0;
}
#endregion
#region Special Words Table
static string[] _specialWordsStringTable = new string[] {
"agendum", "agenda", "",
"albino", "albinos", "",
"alga", "algae", "",
"alumna", "alumnae", "",
"apex", "apices", "apexes",
"archipelago", "archipelagos", "",
"bacterium", "bacteria", "",
"beef", "beefs", "beeves",
"bison", "", "",
"brother", "brothers", "brethren",
"candelabrum", "candelabra", "",
"carp", "", "",
"casino", "casinos", "",
"child", "children", "",
"chassis", "", "",
"chinese", "", "",
"clippers", "", "",
"cod", "", "",
"codex", "codices", "",
"commando", "commandos", "",
"corps", "", "",
"cortex", "cortices", "cortexes",
"cow", "cows", "kine",
"criterion", "criteria", "",
"datum", "data", "",
"debris", "", "",
"diabetes", "", "",
"ditto", "dittos", "",
"djinn", "", "",
"dynamo", "", "",
"elk", "", "",
"embryo", "embryos", "",
"ephemeris", "ephemeris", "ephemerides",
"erratum", "errata", "",
"extremum", "extrema", "",
"fiasco", "fiascos", "",
"fish", "fishes", "fish",
"flounder", "", "",
"focus", "focuses", "foci",
"fungus", "fungi", "funguses",
"gallows", "", "",
"genie", "genies", "genii",
"ghetto", "ghettos", "",
"graffiti", "", "",
"headquarters", "", "",
"herpes", "", "",
"homework", "", "",
"index", "indices", "indexes",
"inferno", "infernos", "",
"japanese", "", "",
"jumbo", "jumbos", "",
"latex", "latices", "latexes",
"lingo", "lingos", "",
"mackerel", "", "",
"macro", "macros", "",
"manifesto", "manifestos", "",
"measles", "", "",
"money", "moneys", "monies",
"mongoose", "mongooses", "mongoose",
"mumps", "", "",
"murex", "murecis", "",
"mythos", "mythos", "mythoi",
"news", "", "",
"octopus", "octopuses", "octopodes",
"ovum", "ova", "",
"ox", "ox", "oxen",
"photo", "photos", "",
"pincers", "", "",
"pliers", "", "",
"pro", "pros", "",
"rabies", "", "",
"radius", "radiuses", "radii",
"rhino", "rhinos", "",
"salmon", "", "",
"scissors", "", "",
"series", "", "",
"shears", "", "",
"silex", "silices", "",
"simplex", "simplices", "simplexes",
"soliloquy", "soliloquies", "soliloquy",
"species", "", "",
"stratum", "strata", "",
"swine", "", "",
"trout", "", "",
"tuna", "", "",
"vertebra", "vertebrae", "",
"vertex", "vertices", "vertexes",
"vortex", "vortices", "vortexes",
};
#endregion
#region Suffix Rules Table
static string[] _suffixRulesStringTable = new string[] {
"ch", "ches",
"sh", "shes",
"ss", "sses",
"ay", "ays",
"ey", "eys",
"iy", "iys",
"oy", "oys",
"uy", "uys",
"y", "ies",
"ao", "aos",
"eo", "eos",
"io", "ios",
"oo", "oos",
"uo", "uos",
"o", "oes",
"cis", "ces",
"sis", "ses",
"xis", "xes",
"louse", "lice",
"mouse", "mice",
"zoon", "zoa",
"man", "men",
"deer", "deer",
"fish", "fish",
"sheep", "sheep",
"itis", "itis",
"ois", "ois",
"pox", "pox",
"ox", "oxes",
"foot", "feet",
"goose", "geese",
"tooth", "teeth",
"alf", "alves",
"elf", "elves",
"olf", "olves",
"arf", "arves",
"leaf", "leaves",
"nife", "nives",
"life", "lives",
"wife", "wives",
};
#endregion
#region Implementation Details
class Word {
public readonly string Singular;
public readonly string Plural;
public readonly string Plural2;
public Word(string singular, string plural, string plural2) {
Singular = singular;
Plural = plural;
Plural2 = plural2;
}
}
class SuffixRule {
string _singularSuffix;
string _pluralSuffix;
public SuffixRule(string singular, string plural) {
_singularSuffix = singular;
_pluralSuffix = plural;
}
public bool TryToPlural(string word, out string plural) {
if (word.EndsWith(_singularSuffix, StringComparison.OrdinalIgnoreCase)) {
plural = word.Substring(0, word.Length - _singularSuffix.Length) + _pluralSuffix;
return true;
} else {
plural = null;
return false;
}
}
public bool TryToSingular(string word, out string singular) {
if (word.EndsWith(_pluralSuffix, StringComparison.OrdinalIgnoreCase)) {
singular = word.Substring(0, word.Length - _pluralSuffix.Length) + _singularSuffix;
return true;
} else {
singular = null;
return false;
}
}
}
static Dictionary<string, Word> _specialSingulars;
static Dictionary<string, Word> _specialPlurals;
static List<SuffixRule> _suffixRules;
static Pluralizer() {
// populate lookup tables for special words
_specialSingulars = new Dictionary<string, Word>(StringComparer.OrdinalIgnoreCase);
_specialPlurals = new Dictionary<string, Word>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < _specialWordsStringTable.Length; i += 3) {
string s = _specialWordsStringTable[i];
string p = _specialWordsStringTable[i + 1];
string p2 = _specialWordsStringTable[i + 2];
if (string.IsNullOrEmpty(p)) {
p = s;
}
Word w = new Word(s, p, p2);
_specialSingulars.Add(s, w);
_specialPlurals.Add(p, w);
if (!string.IsNullOrEmpty(p2)) {
_specialPlurals.Add(p2, w);
}
}
// populate suffix rules list
_suffixRules = new List<SuffixRule>();
for (int i = 0; i < _suffixRulesStringTable.Length; i += 2) {
string singular = _suffixRulesStringTable[i];
string plural = _suffixRulesStringTable[i + 1];
_suffixRules.Add(new SuffixRule(singular, plural));
}
}
static string ToPluralInternal(string s) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// lookup special words
Word word;
if (_specialSingulars.TryGetValue(s, out word)) {
return word.Plural;
}
// apply suffix rules
string plural;
foreach (SuffixRule rule in _suffixRules) {
if (rule.TryToPlural(s, out plural)) {
return plural;
}
}
// apply the default rule
return s + "s";
}
static string ToSingularInternal(string s) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// lookup special words
Word word;
if (_specialPlurals.TryGetValue(s, out word)) {
return word.Singular;
}
// apply suffix rules
string singular;
foreach (SuffixRule rule in _suffixRules) {
if (rule.TryToSingular(s, out singular)) {
return singular;
}
}
// apply the default rule
if (s.EndsWith("s", StringComparison.OrdinalIgnoreCase)) {
return s.Substring(0, s.Length - 1);
}
return s;
}
static string AdjustCase(string s, string template) {
if (string.IsNullOrEmpty(s)) {
return s;
}
// determine the type of casing of the template string
bool foundUpperOrLower = false;
bool allLower = true;
bool allUpper = true;
bool firstUpper = false;
for (int i = 0; i < template.Length; i++) {
if (Char.IsUpper(template[i])) {
if (i == 0) firstUpper = true;
allLower = false;
foundUpperOrLower = true;
} else if (Char.IsLower(template[i])) {
allUpper = false;
foundUpperOrLower = true;
}
}
// change the case according to template
if (foundUpperOrLower) {
if (allLower) {
s = s.ToLowerInvariant();
} else if (allUpper) {
s = s.ToUpperInvariant();
} else if (firstUpper) {
if (!Char.IsUpper(s[0])) {
s = s.Substring(0, 1).ToUpperInvariant() + s.Substring(1);
}
}
}
return s;
}
#endregion
}
}
}
@@ -1,40 +1,39 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel;
namespace uPowers.BusinessLogic{
//Forum Event args
public class VoteEventArgs : System.ComponentModel.CancelEventArgs { }
public class TagEventArgs : System.ComponentModel.CancelEventArgs { }
public class ActionEventArgs : System.ComponentModel.CancelEventArgs {
public int PerformerId { get; set; }
public int ItemId { get; set; }
public int ReceiverId { get; set; }
public List<int> ExtraReceivers { get; set; }
public string ActionType { get; set; }
}
public class Events {
/// <summary>
/// Calls the subscribers of a cancelable event handler,
/// stopping at the event handler which cancels the event (if any).
/// </summary>
/// <typeparam name="T">Type of the event arguments.</typeparam>
/// <param name="cancelableEvent">The event to fire.</param>
/// <param name="sender">Sender of the event.</param>
/// <param name="eventArgs">Event arguments.</param>
public virtual void FireCancelableEvent<T>(EventHandler<T> cancelableEvent, object sender, T eventArgs) where T : CancelEventArgs {
if (cancelableEvent != null) {
foreach (Delegate invocation in cancelableEvent.GetInvocationList()) {
invocation.DynamicInvoke(sender, eventArgs);
if (eventArgs.Cancel)
break;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace OurUmbraco.Powers.BusinessLogic{
//Forum Event args
public class VoteEventArgs : System.ComponentModel.CancelEventArgs { }
public class TagEventArgs : System.ComponentModel.CancelEventArgs { }
public class ActionEventArgs : System.ComponentModel.CancelEventArgs {
public int PerformerId { get; set; }
public int ItemId { get; set; }
public int ReceiverId { get; set; }
public List<int> ExtraReceivers { get; set; }
public string ActionType { get; set; }
}
public class Events {
/// <summary>
/// Calls the subscribers of a cancelable event handler,
/// stopping at the event handler which cancels the event (if any).
/// </summary>
/// <typeparam name="T">Type of the event arguments.</typeparam>
/// <param name="cancelableEvent">The event to fire.</param>
/// <param name="sender">Sender of the event.</param>
/// <param name="eventArgs">Event arguments.</param>
public virtual void FireCancelableEvent<T>(EventHandler<T> cancelableEvent, object sender, T eventArgs) where T : CancelEventArgs {
if (cancelableEvent != null) {
foreach (Delegate invocation in cancelableEvent.GetInvocationList()) {
invocation.DynamicInvoke(sender, eventArgs);
if (eventArgs.Cancel)
break;
}
}
}
}
}
@@ -1,61 +1,58 @@
using System;
using System.Collections.Generic;
using System.Web;
using umbraco.cms.businesslogic.member;
using System.Xml;
using System.Collections;
namespace uPowers.BusinessLogic {
public class Reputation {
public int Current { get; set; }
public int Total { get; set; }
public int MemberId { get; set; }
public void Save() {
if (MemberId > 0) {
Member m = Library.Utils.GetMember(MemberId);
m.getProperty(config.GetKey("/configuration/reputation/currentPointsAlias")).Value = Current;
m.getProperty(config.GetKey("/configuration/reputation/totalPointsAlias")).Value = Total;
m.XmlGenerate(new XmlDocument());
m.Save();
//make sure a cached member gets updated.
Hashtable mems = Member.CachedMembers();
if (mems.ContainsKey(m.Id)) {
mems.Remove(m.Id);
mems.Add(m.Id, m);
}
}
}
public Reputation(int memberId){
Member m = Library.Utils.GetMember(memberId);
if (m != null) {
Current = obToInt( m.getProperty(config.GetKey("/configuration/reputation/currentPointsAlias")).Value );
Total = obToInt( m.getProperty(config.GetKey("/configuration/reputation/totalPointsAlias")).Value );
MemberId = m.Id;
}
}
private int obToInt(object val) {
int retval = 0;
int.TryParse(val.ToString(), out retval);
return retval;
}
public XmlNode ToXml(XmlDocument d) {
XmlNode tx = d.CreateElement("reputation");
tx.AppendChild(umbraco.xmlHelper.addTextNode(d, "current", Total.ToString()));
tx.AppendChild(umbraco.xmlHelper.addCDataNode(d, "total", Current.ToString()));
return tx;
}
}
}
using System.Collections;
using System.Xml;
using umbraco.cms.businesslogic.member;
namespace OurUmbraco.Powers.BusinessLogic {
public class Reputation {
public int Current { get; set; }
public int Total { get; set; }
public int MemberId { get; set; }
public void Save() {
if (MemberId > 0) {
Member m = Library.Utils.GetMember(MemberId);
m.getProperty(config.GetKey("/configuration/reputation/currentPointsAlias")).Value = Current;
m.getProperty(config.GetKey("/configuration/reputation/totalPointsAlias")).Value = Total;
m.XmlGenerate(new XmlDocument());
m.Save();
//make sure a cached member gets updated.
Hashtable mems = Member.CachedMembers();
if (mems.ContainsKey(m.Id)) {
mems.Remove(m.Id);
mems.Add(m.Id, m);
}
}
}
public Reputation(int memberId){
Member m = Library.Utils.GetMember(memberId);
if (m != null) {
Current = obToInt( m.getProperty(config.GetKey("/configuration/reputation/currentPointsAlias")).Value );
Total = obToInt( m.getProperty(config.GetKey("/configuration/reputation/totalPointsAlias")).Value );
MemberId = m.Id;
}
}
private int obToInt(object val) {
int retval = 0;
int.TryParse(val.ToString(), out retval);
return retval;
}
public XmlNode ToXml(XmlDocument d) {
XmlNode tx = d.CreateElement("reputation");
tx.AppendChild(umbraco.xmlHelper.addTextNode(d, "current", Total.ToString()));
tx.AppendChild(umbraco.xmlHelper.addCDataNode(d, "total", Current.ToString()));
return tx;
}
}
}
@@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Web;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.member;
namespace uPowers.Library
namespace OurUmbraco.Powers.Library
{
public class Utils
{
@@ -1,91 +1,88 @@
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.Web;
using System.Data;
namespace uPowers.Library {
[Umbraco.Core.Macros.XsltExtension("uPowers")]
public class Xslt {
//this will be changed to something abit less static before Upowers are released, if it ever is...
public static XPathNodeIterator MemberKarma(int InLastNumberOfDays, int maxItems) {
string SQL = Buddha.Buddha.TotalKarmaSQL(InLastNumberOfDays, maxItems);
return uPowers.BusinessLogic.Data.GetDataSet(SQL, "score");
}
public static XPathNodeIterator Reputation(int memberId) {
XmlDocument xd = new XmlDocument();
return new BusinessLogic.Reputation(memberId).ToXml(xd).CreateNavigator().Select(".");
}
public static XPathNodeIterator ItemsVotedFor(int memberId, string dataBaseTable)
{
XmlDocument xd = new XmlDocument();
string sql = string.Format(@"SELECT TOP 1000 [id]
,sum([points]) as points
,sum([receiverPoints]) as receiverPoints
FROM {0}
where memberId = {1}
group by id
ORDER by receiverPoints DESC", dataBaseTable, memberId);
return uPowers.BusinessLogic.Data.GetDataSet(sql, "item");
}
public static XPathNodeIterator PopularItems(string dataBaseTable) {
XmlDocument xd = new XmlDocument();
return uPowers.BusinessLogic.Data.GetDataSet("SELECT id, count(points) as count, AVG(points) as average, SUM(points) as score from " + dataBaseTable + " GROUP BY id ", "item");
}
public static XPathNodeIterator History(int itemKey, string dataBaseTable) {
XmlDocument xd = new XmlDocument();
string db = dataBaseTable.Split(' ')[0];
return uPowers.BusinessLogic.Data.GetDataSet("SELECT * from " + db + " where id = " + itemKey.ToString(), "vote");
}
public static int Score(int id, string dataBaseTable) {
return BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT SUM(points) AS count FROM " + dataBaseTable + " WHERE (id = @id)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id));
}
public static bool HasVoted(int memberId, int id, string dataBaseTable) {
return (BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT count(points) FROM " + dataBaseTable + " WHERE (id = @id) AND (memberId = @memberId)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId)) > 0);
}
public static int YourVote(int memberId, int id, string dataBaseTable) {
return BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT sum(points) FROM " + dataBaseTable + " WHERE (id = @id) AND (memberId = @memberId)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId));
}
public static int GetExternalUrlData(int memberId, string url)
{
// get the Item Id of the Url
var id = BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT id FROM externalUrls WHERE (@url = url)", BusinessLogic.Data.SqlHelper.CreateParameter("@url", url));
// doesn't exist ... then create a new entry
if (id == 0)
id = BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("INSERT INTO externalUrls (memberId, url) VALUES (@memberId, @url); SELECT SCOPE_IDENTITY()", BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId), BusinessLogic.Data.SqlHelper.CreateParameter("@url", url));
return id;
}
public static bool ExternalHasVoted(int receiverId, int itemId)
{
// get the current member's Id
var memberId = umbraco.cms.businesslogic.member.Member.CurrentMemberId();
// if the member is the same as the receiver - return false
if (memberId == receiverId)
return true;
// check if member has already voted for the Url
return (BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT count(points) FROM powersExternal WHERE (id = @id) AND (memberId = @memberId)", BusinessLogic.Data.SqlHelper.CreateParameter("@id", itemId), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId)) > 0);
}
}
}
using System.Xml;
using System.Xml.XPath;
using OurUmbraco.Powers.BusinessLogic;
namespace OurUmbraco.Powers.Library {
[Umbraco.Core.Macros.XsltExtension("uPowers")]
public class Xslt {
//this will be changed to something abit less static before Upowers are released, if it ever is...
public static XPathNodeIterator MemberKarma(int InLastNumberOfDays, int maxItems) {
string SQL = Buddha.Buddha.TotalKarmaSQL(InLastNumberOfDays, maxItems);
return Data.GetDataSet(SQL, "score");
}
public static XPathNodeIterator Reputation(int memberId) {
XmlDocument xd = new XmlDocument();
return new BusinessLogic.Reputation(memberId).ToXml(xd).CreateNavigator().Select(".");
}
public static XPathNodeIterator ItemsVotedFor(int memberId, string dataBaseTable)
{
XmlDocument xd = new XmlDocument();
string sql = string.Format(@"SELECT TOP 1000 [id]
,sum([points]) as points
,sum([receiverPoints]) as receiverPoints
FROM {0}
where memberId = {1}
group by id
ORDER by receiverPoints DESC", dataBaseTable, memberId);
return Data.GetDataSet(sql, "item");
}
public static XPathNodeIterator PopularItems(string dataBaseTable) {
XmlDocument xd = new XmlDocument();
return Data.GetDataSet("SELECT id, count(points) as count, AVG(points) as average, SUM(points) as score from " + dataBaseTable + " GROUP BY id ", "item");
}
public static XPathNodeIterator History(int itemKey, string dataBaseTable) {
XmlDocument xd = new XmlDocument();
string db = dataBaseTable.Split(' ')[0];
return Data.GetDataSet("SELECT * from " + db + " where id = " + itemKey.ToString(), "vote");
}
public static int Score(int id, string dataBaseTable) {
return BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT SUM(points) AS count FROM " + dataBaseTable + " WHERE (id = @id)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id));
}
public static bool HasVoted(int memberId, int id, string dataBaseTable) {
return (BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT count(points) FROM " + dataBaseTable + " WHERE (id = @id) AND (memberId = @memberId)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId)) > 0);
}
public static int YourVote(int memberId, int id, string dataBaseTable) {
return BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT sum(points) FROM " + dataBaseTable + " WHERE (id = @id) AND (memberId = @memberId)",
BusinessLogic.Data.SqlHelper.CreateParameter("@id", id), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId));
}
public static int GetExternalUrlData(int memberId, string url)
{
// get the Item Id of the Url
var id = BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT id FROM externalUrls WHERE (@url = url)", BusinessLogic.Data.SqlHelper.CreateParameter("@url", url));
// doesn't exist ... then create a new entry
if (id == 0)
id = BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("INSERT INTO externalUrls (memberId, url) VALUES (@memberId, @url); SELECT SCOPE_IDENTITY()", BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId), BusinessLogic.Data.SqlHelper.CreateParameter("@url", url));
return id;
}
public static bool ExternalHasVoted(int receiverId, int itemId)
{
// get the current member's Id
var memberId = umbraco.cms.businesslogic.member.Member.CurrentMemberId();
// if the member is the same as the receiver - return false
if (memberId == receiverId)
return true;
// check if member has already voted for the Url
return (BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT count(points) FROM powersExternal WHERE (id = @id) AND (memberId = @memberId)", BusinessLogic.Data.SqlHelper.CreateParameter("@id", itemId), BusinessLogic.Data.SqlHelper.CreateParameter("@memberId", memberId)) > 0);
}
}
}
@@ -1,77 +1,76 @@
using System;
using System.Collections.Generic;
using System.Xml;
using System.Web;
using System.IO;
using System.Web.Caching;
using umbraco.BusinessLogic;
namespace uPowers {
public class config {
public static XmlDocument _Settings {
get {
XmlDocument us = (XmlDocument)HttpRuntime.Cache["uPowersSettingsFile"];
if (us == null)
us = ensureSettingsDocument();
return us;
}
}
private static string _path = umbraco.GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar;
private static string _filename = "uPowers.config";
private static XmlDocument ensureSettingsDocument() {
object settingsFile = HttpRuntime.Cache["uPowersSettingsFile"];
// Check for language file in cache
if (settingsFile == null) {
XmlDocument temp = new XmlDocument();
XmlTextReader settingsReader = new XmlTextReader(_path + _filename);
try {
temp.Load(settingsReader);
HttpRuntime.Cache.Insert("uPowersSettingsFile", temp, new CacheDependency(_path + _filename));
} catch (Exception e) {
Log.Add(LogTypes.Error, new User(0), -1, "Error reading uPowers setting file: " + e.ToString());
}
settingsReader.Close();
return temp;
} else
return (XmlDocument)settingsFile;
}
private static void save() {
_Settings.Save(_path + _filename);
}
/// <summary>
/// Selects a xml node in the umbraco settings config file.
/// </summary>
/// <param name="Key">The xpath query to the specific node.</param>
/// <returns>If found, it returns the specific configuration xml node.</returns>
public static XmlNode GetKeyAsNode(string Key) {
if (Key == null)
throw new ArgumentException("Key cannot be null");
ensureSettingsDocument();
if (_Settings == null || _Settings.DocumentElement == null)
return null;
return _Settings.DocumentElement.SelectSingleNode(Key);
}
/// <summary>
/// Gets the value of configuration xml node with the specified key.
/// </summary>
/// <param name="Key">The key.</param>
/// <returns></returns>
public static string GetKey(string Key) {
ensureSettingsDocument();
XmlNode node = _Settings.DocumentElement.SelectSingleNode(Key);
if (node == null || node.FirstChild == null || node.FirstChild.Value == null)
return string.Empty;
return node.FirstChild.Value;
}
}
}
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml;
using umbraco.BusinessLogic;
namespace OurUmbraco.Powers {
public class config {
public static XmlDocument _Settings {
get {
XmlDocument us = (XmlDocument)HttpRuntime.Cache["uPowersSettingsFile"];
if (us == null)
us = ensureSettingsDocument();
return us;
}
}
private static string _path = umbraco.GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar;
private static string _filename = "uPowers.config";
private static XmlDocument ensureSettingsDocument() {
object settingsFile = HttpRuntime.Cache["uPowersSettingsFile"];
// Check for language file in cache
if (settingsFile == null) {
XmlDocument temp = new XmlDocument();
XmlTextReader settingsReader = new XmlTextReader(_path + _filename);
try {
temp.Load(settingsReader);
HttpRuntime.Cache.Insert("uPowersSettingsFile", temp, new CacheDependency(_path + _filename));
} catch (Exception e) {
Log.Add(LogTypes.Error, new User(0), -1, "Error reading uPowers setting file: " + e.ToString());
}
settingsReader.Close();
return temp;
} else
return (XmlDocument)settingsFile;
}
private static void save() {
_Settings.Save(_path + _filename);
}
/// <summary>
/// Selects a xml node in the umbraco settings config file.
/// </summary>
/// <param name="Key">The xpath query to the specific node.</param>
/// <returns>If found, it returns the specific configuration xml node.</returns>
public static XmlNode GetKeyAsNode(string Key) {
if (Key == null)
throw new ArgumentException("Key cannot be null");
ensureSettingsDocument();
if (_Settings == null || _Settings.DocumentElement == null)
return null;
return _Settings.DocumentElement.SelectSingleNode(Key);
}
/// <summary>
/// Gets the value of configuration xml node with the specified key.
/// </summary>
/// <param name="Key">The key.</param>
/// <returns></returns>
public static string GetKey(string Key) {
ensureSettingsDocument();
XmlNode node = _Settings.DocumentElement.SelectSingleNode(Key);
if (node == null || node.FirstChild == null || node.FirstChild.Value == null)
return string.Empty;
return node.FirstChild.Value;
}
}
}
@@ -1,62 +1,62 @@
<configuration>
<!-- This section configures on what property reputation points are found -->
<reputation>
<!-- How Many points the member have earned in total-->
<totalPointsAlias>reputationTotal</totalPointsAlias>
<!-- How many points the member have currently (points could have been lost due to spam) -->
<currentPointsAlias>reputationCurrent</currentPointsAlias>
</reputation>
<!-- Configures the different types of actions and how much they "cost/make" to perform
and a minimum current reputation level to perform them -->
<!-- Voting and tagging relies on these actions, so if a vote uses the same alias, it will use the logic of the actions cost/minimum-reputation score -->
<!-- Cost: the rep points it costs to perform action, if negative, the user will actually be rewarded fore performing action -->
<!-- Reward: the points award to the authors rep account (owner of wiki page f.ex.), if negative, the user will loose rep points -->
<!-- Weight: the weight of the action for the item itself, so actions can both be negative and positive for the rating of an item..
Usually it's just 1, but admins could perform actions that has a higher weight like a -10000 could kill a page's score.. -->
<!-- Type is the alias of the location the score will be stored, topic= powersTopic table -->
<actions>
<action type="topic" alias="NewTopic" performerReward="1" receiverReward="0" weight="0" minReputation="0" />
<action type="topic" alias="LikeTopic" performerReward="1" receiverReward="1" weight="1" minReputation="70" />
<action type="topic" alias="DisLikeTopic" mandatoryComment="true" performerReward="0" receiverReward="-1" weight="-1" minReputation="70" />
<action type="comment" alias="NewComment" performerReward="1" receiverReward="0" weight="0" minReputation="0" />
<action type="comment" alias="LikeComment" performerReward="1" receiverReward="1" weight="1" minReputation="70" />
<action type="comment" alias="DisLikeComment" mandatoryComment="true" performerReward="1" receiverReward="-1" weight="-1" minReputation="70" />
<action type="comment" alias="TopicSolved" performerReward="10" receiverReward="20" weight="100" minReputation="0" />
<action type="wiki" alias="WikiUp" performerReward="1" receiverReward="0" weight="1" minReputation="70" />
<action type="wiki" alias="WikiDown" performerReward="0" mandatoryComment="true" receiverReward="0" weight="-1" minReputation="70" />
<action type="project" alias="ProjectUp" performerReward="1" receiverReward="5" weight="1" minReputation="70" />
<action type="project" alias="ProjectDown" mandatoryComment="true" performerReward="0" receiverReward="0" weight="-1" minReputation="70" />
<action type="projectVersion" alias="ProjectVersionVote" performerReward="1" recieverReward="0" weight="1" minReputation="0"/>
</actions>
<buddha>
<folder>/upowers</folder>
<types>topic,comment,wiki,project</types>
<timespans>
<timespan>28</timespan>
<timespan>365</timespan>
</timespans>
</buddha>
<karma total="32323" days28="232323" days365="232323">
<action type="topic">
<received total="2626" days28="232" days365="2323" >
<entry id="4699" points="5" datetime="2388273" />
<entry id="23443" points="-1" datetime="2388273" />
</received>
<performed total="32232">
</performed>
</action>
</karma>
<configuration>
<!-- This section configures on what property reputation points are found -->
<reputation>
<!-- How Many points the member have earned in total-->
<totalPointsAlias>reputationTotal</totalPointsAlias>
<!-- How many points the member have currently (points could have been lost due to spam) -->
<currentPointsAlias>reputationCurrent</currentPointsAlias>
</reputation>
<!-- Configures the different types of actions and how much they "cost/make" to perform
and a minimum current reputation level to perform them -->
<!-- Voting and tagging relies on these actions, so if a vote uses the same alias, it will use the logic of the actions cost/minimum-reputation score -->
<!-- Cost: the rep points it costs to perform action, if negative, the user will actually be rewarded fore performing action -->
<!-- Reward: the points award to the authors rep account (owner of wiki page f.ex.), if negative, the user will loose rep points -->
<!-- Weight: the weight of the action for the item itself, so actions can both be negative and positive for the rating of an item..
Usually it's just 1, but admins could perform actions that has a higher weight like a -10000 could kill a page's score.. -->
<!-- Type is the alias of the location the score will be stored, topic= powersTopic table -->
<actions>
<action type="topic" alias="NewTopic" performerReward="1" receiverReward="0" weight="0" minReputation="0" />
<action type="topic" alias="LikeTopic" performerReward="1" receiverReward="1" weight="1" minReputation="70" />
<action type="topic" alias="DisLikeTopic" mandatoryComment="true" performerReward="0" receiverReward="-1" weight="-1" minReputation="70" />
<action type="comment" alias="NewComment" performerReward="1" receiverReward="0" weight="0" minReputation="0" />
<action type="comment" alias="LikeComment" performerReward="1" receiverReward="1" weight="1" minReputation="70" />
<action type="comment" alias="DisLikeComment" mandatoryComment="true" performerReward="1" receiverReward="-1" weight="-1" minReputation="70" />
<action type="comment" alias="TopicSolved" performerReward="10" receiverReward="20" weight="100" minReputation="0" />
<action type="wiki" alias="WikiUp" performerReward="1" receiverReward="0" weight="1" minReputation="70" />
<action type="wiki" alias="WikiDown" performerReward="0" mandatoryComment="true" receiverReward="0" weight="-1" minReputation="70" />
<action type="project" alias="ProjectUp" performerReward="1" receiverReward="5" weight="1" minReputation="70" />
<action type="project" alias="ProjectDown" mandatoryComment="true" performerReward="0" receiverReward="0" weight="-1" minReputation="70" />
<action type="projectVersion" alias="ProjectVersionVote" performerReward="1" recieverReward="0" weight="1" minReputation="0"/>
</actions>
<buddha>
<folder>/upowers</folder>
<types>topic,comment,wiki,project</types>
<timespans>
<timespan>28</timespan>
<timespan>365</timespan>
</timespans>
</buddha>
<karma total="32323" days28="232323" days365="232323">
<action type="topic">
<received total="2626" days28="232" days365="2323" >
<entry id="4699" points="5" datetime="2388273" />
<entry id="23443" points="-1" datetime="2388273" />
</received>
<performed total="32232">
</performed>
</action>
</karma>
</configuration>
-12
View File
@@ -13,8 +13,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "uForum", "uForum\uForum.csproj", "{547C2D0D-1B55-493B-AE0B-E031A5B8EE77}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "uPowers", "uPowers\uPowers.csproj", "{00F050B9-E3ED-49A7-AB97-E8BEC2513553}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "our.umbraco.org", "our.umbraco.org\our.umbraco.org.csproj", "{A625544F-660A-4C01-BA49-1B467D0322D9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notification", "Notification\Notification.csproj", "{80E5F59D-A7A0-4CEE-AEB6-6C626C44B2B2}"
@@ -64,16 +62,6 @@ Global
{547C2D0D-1B55-493B-AE0B-E031A5B8EE77}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{547C2D0D-1B55-493B-AE0B-E031A5B8EE77}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{547C2D0D-1B55-493B-AE0B-E031A5B8EE77}.Release|x86.ActiveCfg = Release|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Debug|x86.ActiveCfg = Debug|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Release|Any CPU.Build.0 = Release|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{00F050B9-E3ED-49A7-AB97-E8BEC2513553}.Release|x86.ActiveCfg = Release|Any CPU
{A625544F-660A-4C01-BA49-1B467D0322D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A625544F-660A-4C01-BA49-1B467D0322D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A625544F-660A-4C01-BA49-1B467D0322D9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
@@ -1,7 +1,9 @@
using System;
using OurUmbraco.Powers.BusinessLogic;
using OurUmbraco.Powers.Library;
using uForum.Services;
using uPowers.BusinessLogic;
using Umbraco.Core;
using Action = OurUmbraco.Powers.BusinessLogic.Action;
namespace our.CustomHandlers
{
@@ -14,19 +16,19 @@ namespace our.CustomHandlers
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
uPowers.BusinessLogic.Action.BeforePerform += new EventHandler<ActionEventArgs>(CommentVote);
uPowers.BusinessLogic.Action.AfterPerform += new EventHandler<ActionEventArgs>(CommentScoring);
Action.BeforePerform += new EventHandler<ActionEventArgs>(CommentVote);
Action.AfterPerform += new EventHandler<ActionEventArgs>(CommentScoring);
}
void CommentScoring(object sender, ActionEventArgs e)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "LikeComment" || a.Alias == "DisLikeComment" || a.Alias == "TopicSolved")
{
int score = uPowers.Library.Xslt.Score(e.ItemId, a.DataBaseTable);
int score = Xslt.Score(e.ItemId, a.DataBaseTable);
//we then add the sum of the total score to the
our.Data.SqlHelper.ExecuteNonQuery("UPDATE forumComments SET score = @score WHERE id = @id", Data.SqlHelper.CreateParameter("@id", e.ItemId), Data.SqlHelper.CreateParameter("@score", score));
@@ -38,7 +40,7 @@ namespace our.CustomHandlers
void CommentVote(object sender, ActionEventArgs e)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
var ts = new TopicService(ApplicationContext.Current.DatabaseContext);
var cs = new CommentService(ApplicationContext.Current.DatabaseContext, ts);
@@ -1,6 +1,7 @@
using System;
using OurUmbraco.Powers.BusinessLogic;
using umbraco.BusinessLogic;
using uPowers.BusinessLogic;
using Action = OurUmbraco.Powers.BusinessLogic.Action;
namespace our.CustomHandlers
{
@@ -8,16 +9,16 @@ namespace our.CustomHandlers
{
public ExternalVote()
{
uPowers.BusinessLogic.Action.BeforePerform += new EventHandler<ActionEventArgs>(this.Action_BeforePerform);
Action.BeforePerform += new EventHandler<ActionEventArgs>(this.Action_BeforePerform);
}
void Action_BeforePerform(object sender, ActionEventArgs e)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "ExternalVote")
{
var memberId = uPowers.BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT memberId FROM externalUrls WHERE (@id = id)", uPowers.BusinessLogic.Data.SqlHelper.CreateParameter("@id", e.ItemId));
var memberId = OurUmbraco.Powers.BusinessLogic.Data.SqlHelper.ExecuteScalar<int>("SELECT memberId FROM externalUrls WHERE (@id = id)", OurUmbraco.Powers.BusinessLogic.Data.SqlHelper.CreateParameter("@id", e.ItemId));
e.ReceiverId = memberId;
}
}
@@ -1,4 +1,5 @@
using uForum;
using OurUmbraco.Powers.BusinessLogic;
using uForum;
using uForum.Extensions;
using uForum.Services;
using Umbraco.Core;
@@ -26,7 +27,7 @@ namespace our.CustomHandlers {
member.IncreaseForumPostCount();
ms.Save(member);
uPowers.BusinessLogic.Action a = new uPowers.BusinessLogic.Action("NewComment");
Action a = new Action("NewComment");
a.Perform(member.Id, e.Comment.Id, "New comment created");
}
}
@@ -40,7 +41,7 @@ namespace our.CustomHandlers {
member.IncreaseForumPostCount();
ms.Save(member);
uPowers.BusinessLogic.Action a = new uPowers.BusinessLogic.Action("NewTopic");
Action a = new Action("NewTopic");
a.Perform(member.Id, e.Topic.Id, "New topic created");
}
}
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using OurUmbraco.Powers.Library;
using OurUmbraco.Wiki.BusinessLogic;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
@@ -27,7 +28,7 @@ namespace our.CustomHandlers
}
//if the score is above the minimum, set the approved variable
int score = uPowers.Library.Xslt.Score(sender.Id, "powersProject");
int score = Xslt.Score(sender.Id, "powersProject");
if (score >= 15)
{
sender.getProperty("approved").Value = true;
+10 -8
View File
@@ -1,9 +1,11 @@
using System;
using System.Linq;
using System.Web.Security;
using OurUmbraco.Powers.BusinessLogic;
using OurUmbraco.Powers.Library;
using uForum.Services;
using uPowers.BusinessLogic;
using Umbraco.Core;
using Action = OurUmbraco.Powers.BusinessLogic.Action;
namespace our.CustomHandlers
{
@@ -16,9 +18,9 @@ namespace our.CustomHandlers
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
uPowers.BusinessLogic.Action.BeforePerform += new EventHandler<ActionEventArgs>(TopicVote);
uPowers.BusinessLogic.Action.BeforePerform += new EventHandler<ActionEventArgs>(TopicSolved);
uPowers.BusinessLogic.Action.AfterPerform += new EventHandler<ActionEventArgs>(TopicScoring);
Action.BeforePerform += new EventHandler<ActionEventArgs>(TopicVote);
Action.BeforePerform += new EventHandler<ActionEventArgs>(TopicSolved);
Action.AfterPerform += new EventHandler<ActionEventArgs>(TopicScoring);
}
private const string ModeratorRoles = "admin,HQ,Core,MVP";
@@ -28,7 +30,7 @@ namespace our.CustomHandlers
var ts = new TopicService(ApplicationContext.Current.DatabaseContext);
var cs = new CommentService(ApplicationContext.Current.DatabaseContext, ts);
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "TopicSolved")
{
var c = cs.GetById(e.ItemId);
@@ -61,11 +63,11 @@ namespace our.CustomHandlers
{
if (!e.Cancel)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "LikeTopic" || a.Alias == "DisLikeTopic")
{
int topicScore = uPowers.Library.Xslt.Score(e.ItemId, a.DataBaseTable);
int topicScore = Xslt.Score(e.ItemId, a.DataBaseTable);
//this uses a non-standard coloumn in the forum schema, so this is added manually..
our.Data.SqlHelper.ExecuteNonQuery("UPDATE forumTopics SET score = @score WHERE id = @id", Data.SqlHelper.CreateParameter("@id", e.ItemId), Data.SqlHelper.CreateParameter("@score", topicScore));
@@ -77,7 +79,7 @@ namespace our.CustomHandlers
{
var ts = new TopicService(ApplicationContext.Current.DatabaseContext);
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "LikeTopic" || a.Alias == "DisLikeTopic")
{
@@ -1,7 +1,9 @@
using System;
using uPowers.BusinessLogic;
using OurUmbraco.Powers.BusinessLogic;
using OurUmbraco.Powers.Library;
using Umbraco.Core;
using Umbraco.Web;
using Action = OurUmbraco.Powers.BusinessLogic.Action;
namespace our.CustomHandlers
{
@@ -10,20 +12,20 @@ namespace our.CustomHandlers
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
uPowers.BusinessLogic.Action.BeforePerform += new EventHandler<ActionEventArgs>(ProjectVote);
uPowers.BusinessLogic.Action.AfterPerform += new EventHandler<ActionEventArgs>(Action_AfterPerform);
Action.BeforePerform += new EventHandler<ActionEventArgs>(ProjectVote);
Action.AfterPerform += new EventHandler<ActionEventArgs>(Action_AfterPerform);
}
void Action_AfterPerform(object sender, ActionEventArgs e)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "ProjectUp")
{
var contentService = UmbracoContext.Current.Application.Services.ContentService;
var content = contentService.GetById(e.ItemId);
if (content.GetValue<bool>("approved") == false &&
uPowers.Library.Xslt.Score(content.Id, "powersProject") >= 15)
Xslt.Score(content.Id, "powersProject") >= 15)
{
content.SetValue("approved", true);
contentService.SaveAndPublishWithStatus(content);
@@ -33,7 +35,7 @@ namespace our.CustomHandlers
void ProjectVote(object sender, ActionEventArgs e)
{
uPowers.BusinessLogic.Action a = (uPowers.BusinessLogic.Action)sender;
Action a = (Action)sender;
if (a.Alias == "ProjectUp" || a.Alias == "ProjectDown")
{
-4
View File
@@ -426,10 +426,6 @@
<Project>{547C2D0D-1B55-493B-AE0B-E031A5B8EE77}</Project>
<Name>uForum</Name>
</ProjectReference>
<ProjectReference Include="..\uPowers\uPowers.csproj">
<Project>{00F050B9-E3ED-49A7-AB97-E8BEC2513553}</Project>
<Name>uPowers</Name>
</ProjectReference>
<ProjectReference Include="..\uRelease\uRelease.csproj">
<Project>{c5b74e6a-abce-4a9a-896d-89c33fdafcd8}</Project>
<Name>uRelease</Name>
-12
View File
@@ -236,19 +236,7 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Api\PowersController.cs" />
<Compile Include="Buddha\Buddha.cs" />
<Compile Include="BusinessLogic\Data.cs" />
<Compile Include="config.cs" />
<Compile Include="BusinessLogic\Events.cs" />
<Compile Include="Library\Utils.cs" />
<Compile Include="Library\xslt.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="BusinessLogic\Action.cs" />
<Compile Include="BusinessLogic\Reputation.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="uPowers.config" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />