0% found this document useful (0 votes)
8 views9 pages

Using System

The document is a C# ASP.NET web page for viewing and managing posts, allowing users to delete posts, vote (upvote/downvote), and check voting status. It includes methods for handling post interactions via AJAX, updating the database accordingly, and dynamically rendering posts on the page. The page also checks user roles (admin or guest) to enable or restrict certain functionalities.

Uploaded by

laymonko29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Using System

The document is a C# ASP.NET web page for viewing and managing posts, allowing users to delete posts, vote (upvote/downvote), and check voting status. It includes methods for handling post interactions via AJAX, updating the database accordingly, and dynamically rendering posts on the page. The page also checks user roles (admin or guest) to enable or restrict certain functionalities.

Uploaded by

laymonko29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

using System;

using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

public partial class ViewPosts : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["uname"].ToString() == "Guest") { }

if (!IsPostBack)
{
PopulatePosts();
}
}
[WebMethod]
public static void DeletePost(int postId)
{
// Implement your logic to delete the post with the specified postId
// For example:
string fileName = "[Link]";
string sql = "DELETE FROM Posts WHERE PostID = " + postId;
[Link](fileName, sql);
}
[WebMethod]
public static void Vote(int postId, string type, string userName)
{
string fileName = "[Link]";
string votesUsersColumn = type == "up" ? "UpVotesUsers" : "DownVotesUsers";

// Fetch the entire row to check if the username exists in the votes users column
string selectSql = "SELECT * FROM Posts WHERE PostID = '" + postId + "'";
DataTable table = [Link](fileName, selectSql);

if ([Link] == 1)
{
DataRow row = [Link][0];
string existingUsers = row[votesUsersColumn].ToString();
if ([Link](userName))
{
// Username already exists in the votes users column, do nothing
return;
}
}

if (type == "up")
{
string updateSql = "UPDATE Posts SET Upvotes = Upvotes + 1";
string updateVotesUsersSql = "UPDATE Posts SET UpVotesUsers =
CONCAT(UpVotesUsers, ', " + userName + "') WHERE PostID = '" + postId + "'";

[Link](fileName, updateSql);
[Link](fileName, updateVotesUsersSql);
}
else if (type == "down")
{
string updateSql = "UPDATE Posts SET Downvotes = Downvotes + 1";
string updateVotesUsersSql = "UPDATE Posts SET DownVotesUsers =
CONCAT(DownVotesUsers, ', " + userName + "') WHERE PostID = '" + postId + "'";

[Link](fileName, updateSql);
[Link](fileName, updateVotesUsersSql);
}
}

[WebMethod]

public static void unVote(int postId, string type, string userName)


{
string fileName = "[Link]";
if (type == "up")
{
string sql = "UPDATE Posts SET Upvotes = Upvotes - 1 WHERE PostID = " + postId;
string updateVotesUsersSql = "UPDATE Posts SET UpVotesUsers =
REPLACE(UpVotesUsers, '" + userName + "', '') WHERE PostID = '" + postId + "'";
[Link](fileName, sql);
[Link](fileName, updateVotesUsersSql);
}
else if (type == "down")
{
string sql = "UPDATE Posts SET Downvotes = Downvotes - 1 WHERE PostID = " + postId;
string updateVotesUsersSql = "UPDATE Posts SET DownVotesUsers =
REPLACE(DownVotesUsers, '" + userName + "', '') WHERE PostID = '" + postId + "'";
[Link](fileName, sql);
[Link](fileName, updateVotesUsersSql);
}
}
[WebMethod]
public static List<int> GetAllPostIds()
{
List<int> postIds = new List<int>();

// Replace "[Link]" with your actual database file name


string fileName = "[Link]";
string sql = "SELECT PostID FROM Posts";
DataTable table = [Link](fileName, sql);

foreach (DataRow row in [Link])


{
[Link](Convert.ToInt32(row["PostID"]));
}

return postIds;
}

[WebMethod]
public static bool CheckUpvoteStatus(int postId)
{
string userName = [Link]["uname"].ToString();
string fileName = "[Link]";
string sql = "SELECT UpVotesUsers FROM Posts WHERE PostID = " + postId;
DataTable table = [Link](fileName, sql);

if ([Link] > 0)
{
string upVotesUsers = [Link][0]["UpVotesUsers"].ToString();
if ([Link](userName))
{
return true; // User has already upvoted
}
}

return false; // User has not upvoted yet


}

[WebMethod]
public static bool CheckDownvoteStatus(int postId)
{
string userName = [Link]["uname"].ToString();
string fileName = "[Link]";
string sql = "SELECT DownVotesUsers FROM Posts WHERE PostID = " + postId;
DataTable table = [Link](fileName, sql);

if ([Link] > 0)
{
string downVotesUsers = [Link][0]["DownVotesUsers"].ToString();
if ([Link](userName))
{
return true; // User has already downvoted
}
}

return false; // User has not downvoted yet


}

protected void PopulatePosts()


{
string fileName = "[Link]";
string sql = "SELECT * FROM Posts";
DataTable table = [Link](fileName, sql);

StringBuilder sb = new StringBuilder();

foreach (DataRow row in [Link])


{
[Link]("<div class='post'>");
[Link]("<p class='username'>" + row["UserID"] + "</p>");
int postId = Convert.ToInt32(row["PostID"]);

if (IsCurrentUserAuthor(row["UserID"].ToString()) || IsAdmin())
{
[Link]("<button class='delete-button' data-post-id='" + postId + "'><i class='fas
fa-trash'></i></button>");
}
[Link]("<h3 class='text-content'>" + row["TextContent"] + "</h3>");
[Link]("<img class='post-image' src='" + row["ImageURL"] + "' />");
[Link]("<p class='timestamp'>" + row["Timestamp"] + "</p>");

// Add voting buttons


[Link](" <div class=\"checkbox-options\">\r\n");

[Link]("<input type='checkbox' id='upvote-" + postId+"' name='" +postId+"'


class='upvote-button' data-post-id='"+postId+"' value='upvote' />");
[Link]("<label for='upvote-" + postId + "'>&#129153;</label>");

[Link]("<input type='checkbox' id='downvote-" + postId + "' name='" + postId + "'


class='downvote-button' data-post-id='" + postId + "' value='downvote' />");
[Link]("<label for='downvote-" + postId + "'>&#129155;</label>"); ;

[Link]("<div id='VotesNumber-" + postId + "' class='vote-count'>" +


(Convert.ToInt32(row["Upvotes"]) - (Convert.ToInt32(row["Downvotes"]))) + "</div>");
[Link]("</div>");

[Link]("</div>");
}

[Link] = [Link]();
}

protected bool IsAdmin()


{
// Check if the current user has admin privileges
// For example, you can check if the user belongs to an "Admin" role
if (Session["admin"].Equals("True"))
{
return true;
}
return false;
}

protected bool IsCurrentUserAuthor(string userId)


{
// Check if the UserID is present in the session
if (Session["uname"].Equals(userId) == true)
{
return true;
}
else
{
// If UserID is not present in the session, return false
return false;
}
}

protected bool isGuest()


{
if (Session["uname"].ToString() == "Guest")
{
return true;
}
else { return false; }
}

<%@ Page Title="" Language="C#" MasterPageFile="~/[Link]"


AutoEventWireup="true" CodeFile="[Link]" Inherits="ViewPosts" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">


<style>
/* Add your CSS styles here */
</style>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">


<form id="registrationForm" runat="server" method="post" action="">
<div id="registration-form">
<h1>View Posts</h1>
<br />
<div id="postsContainer" runat="server">
<!-- Posts will be dynamically generated here -->
</div>
</div>
</form>
<script src="[Link]
<script>

var userName = '<%= Session["uname"] %>'.toString();


$(document).ready(function () {

// Function to handle post deletion


function deletePost(postId) {
$.ajax({
type: "POST",
url: "[Link]/DeletePost",
data: [Link]({ postId: postId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
// Reload the page after successful deletion
[Link]();
},
error: function () {
alert("Failed to delete post.");
}
});
}
// Attach click event handler to delete buttons
$(document).on("click", ".delete-button", function () {
var postId = $(this).data("post-id");
deletePost(postId);
});

// Function to handle post voting


function vote(postId, type, userName) {
$.ajax({
type: "POST",
url: "[Link]/Vote",
data: [Link]({ postId: postId, type: type, userName: userName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
// Reload the page after successful voting
},
error: function () {
alert("Failed to vote on post.");
}
});
}

function unvote(postId, type, userName) {


$.ajax({
type: "POST",
url: "[Link]/unVote",
data: [Link]({ postId: postId, type: type, userName: userName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
// Reload the page after successful voting
},
error: function () {
alert("Failed to unvote on post.");
}
});
}

// Attach click event handler to upvote buttons


$(document).on("click", ".upvote-button", function () {
var postId = $(this).data("post-id");

// Check if the user is not a guest


if (userName !== "Guest") {
var isChecked = $(this).prop("checked");
var isDownChecked = $("#downvote-" + postId).is(":checked");
// Check if the user has not upvoted yet
if (!isChecked) {
var VotesChange = [Link]("VotesNumber-" + postId);
[Link] = parseInt([Link]) - 1;
unvote(postId, "up", userName);
} else if (!isDownChecked) {
var VotesChange = [Link]("VotesNumber-" + postId);
[Link] = parseInt([Link]) + 1;
unvote(postId, "down", userName);
vote(postId, "up", userName);
} else {
// User has already downvoted, so don't add votes for upvoting
// Instead, uncheck the downvote checkbox
unvote(postId, "down", userName);
$(this).prop("checked", false);
}
}
});

// Attach click event handler to downvote buttons


$(document).on("click", ".downvote-button", function () {
var postId = $(this).data("post-id");

// Check if the user is not a guest


if (userName !== "Guest") {
var isChecked = $(this).prop("checked");
var isUpChecked = $("#upvote-" + postId).is(":checked");

// Check if the user has not downvoted yet


if (!isChecked) {
var VotesChange = [Link]("VotesNumber-" + postId);
[Link] = parseInt([Link]) + 1;
unvote(postId, "down", userName);
} else if (!isUpChecked) {
var VotesChange = [Link]("VotesNumber-" + postId);
[Link] = parseInt([Link]) - 1;
unvote(postId, "up", userName);
vote(postId, "down", userName);
} else {
// User has already upvoted, so don't subtract votes for downvoting
// Instead, uncheck the upvote checkbox
unvote(postId, "up", userName);
$("#upvote-" + postId).prop("checked", false);
}
}
});

$(document).ready(function () {
// Call the GetAllPostIds method to retrieve all post IDs
$.ajax({
type: "POST",
url: "[Link]/GetAllPostIds",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var postIds = response.d; // Array of post IDs

// Iterate over each post ID


[Link](function (postId) {
// Check if the user has upvoted the post
$.ajax({
type: "POST",
url: "[Link]/CheckUpvoteStatus",
data: [Link]({ postId: postId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (upvoteResponse) {
// If the user has upvoted the post, mark the upvote checkbox as checked
if (upvoteResponse.d) {
$("#upvote-" + postId).prop("checked", true);
}
},
error: function (xhr, status, error) {
[Link]([Link]);
}
});

// Check if the user has downvoted the post


$.ajax({
type: "POST",
url: "[Link]/CheckDownvoteStatus",
data: [Link]({ postId: postId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (downvoteResponse) {
// If the user has downvoted the post, mark the downvote checkbox as
checked
if (downvoteResponse.d) {
$("#downvote-" + postId).prop("checked", true);
}
},
error: function (xhr, status, error) {
[Link]([Link]);
}
});
});
},
error: function (xhr, status, error) {
[Link]([Link]);
}
});
});

});

</script>
</asp:Content>

You might also like