using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
namespace DanylkoWeb.Hubs
{
public class MyHub1 : Hub
{
public void Hello()
{
Clients.All.hello();
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}
}
I added the three methods at the end as a way to show how easy it is to check the status of whether they are online or offline.
Let's focus on our component. Here is what we have for our Hub.
Hubs\PostHub.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using BlogPlugin.EntityExtensions;
using BlogPlugin.GeneratedClasses;
using CaramelCMS.Core.Extensions;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace DanylkoWeb.Hubs
{
[HubName("postHub")]
public class PostHub : Hub
{
public Task Like(string postHashId)
{
var likePost = SaveLike(postHashId);
return Clients.All.updateLikeCount(likePost);
}
private LikePost SaveLike(string hashId)
{
var baseContext = this.Context.Request.GetHttpContext();
var unitOfWork = baseContext.GetUnitOfWork<BlogUnitOfWork>();
var item = unitOfWork.PostRepository.GetByHashId(hashId);
var liked = new PostLike
{
Id = Guid.NewGuid().ToString(),
IpAddress = baseContext.Request.UserHostAddress,
PostId = item.Id,
UserAgent = baseContext.Request.UserAgent,
UserLike = true,
DateLiked = DateTime.UtcNow
};
var dupe = item.PostLikes.FirstOrDefault(e => e.IpAddress == liked.IpAddress);
if (dupe == null)
{
item.PostLikes.Add(liked);
}
else
{
dupe.UserLike = !dupe.UserLike;
}
unitOfWork.PostLikeRepository.SaveChanges();
var post = unitOfWork.PostRepository.GetByHashId(hashId);
return post.ToLikePost();
}
}
}
public static T GetUnitOfWork<T>(this HttpContextBase contextBase) where T : AbstractUnitOfWork
{
var objectContextKey = String.Format("{0}-{1}", typeof(T),
contextBase.GetHashCode().ToString("x"));
if (contextBase.Items.Contains(objectContextKey))
return contextBase.Items[objectContextKey] as T;
T type;
using (IKernel kernel = new StandardKernel())
{
type = kernel.Get<T>();
}
contextBase.Items.Add(objectContextKey, type);
return contextBase.Items[objectContextKey] as T;
}
<button data-id="@Model.Post.Hash" type="button" class="like-button" title="Click to like this post!">
<i class="fa fa-thumbs-up"></i> Like
|
<span class="like-count">@Model.PostLikes</span>
</button>