Asked by:
Decode/Decrypt, AES, Passphrase, Expiring, QueryString, url, in c#or Javascript ASP.net WebSite?

Question
-
User1045460610 posted
I want to use decoding of the hostid from this url. The page works now searching the query string but I want to use AES compliant, Salt Passphrase, Expiring encoding and decoding. I have a javascript that works in a test file. I need to figure out how to integrate that encoding in the javascript into the asp.net c# page. Would i want to use the javascript or c#. If I use c# will the decode function decode with the same logic as the javascript function?
If I use the javascript how do I pass the hostid to the c# code behind page?
var returnUrl = Request.Params["ReturnUrl"];
var hostID = Request.Params["HostID"];javascript
//https://attendance.erpise.com/instructorcourse.aspx/?q=U2FsdGVkX1%2BOVOwZzCIOIXwBdE5tW%2FISjtOGhVegQJneEooUvdn%2BShw3ENnsvL%2FMQXD49LXxEIC2Q8MRVnBjnA%3D%3D
function decrypt() {
var params = new URLSearchParams(window.location.search),
queryString = params.get('q'),
key = 'iaUdrdMy7H';if (queryString) {
var decrypted = CryptoJS.AES.decrypt(queryString, key).toString(CryptoJS.enc.Utf8),
temp = decrypted.split('|'),
hostId = temp[0],
timestamp = new Date(temp[1]),
expired = diff_minutes(new Date(), timestamp) > 30;
document.getElementById('decrypt_result').innerText = 'Host ID was sent ' + hostId + ', Url ' + (expired ? 'expired' : 'not expired');
}
}function diff_minutes(dt2, dt1) {
var diff = (dt2.getTime() - dt1.getTime()) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="studentcourse.aspx.cs" Inherits="addcourse" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>On Grounds</title>
<style type="text/css">
.auto-style2 {
width: 123px;
}
.auto-style3 {
width: 26px;
}
.auto-style4 {
width: 27px;
}
.auto-style5 {
width: 288px;
}
.auto-style6 {
/*width: 140px;*/
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h2 class="auto-style5">
<asp:Image ID="Image1" runat="server" Height="103px" Width="216px" ImageUrl="~/headerLogo.png" />
</h2>
<h2>
Attendance</h2>
<h2>
Student - Course</h2>
<table>
<tr>
<td class="auto-style2">
Student ID:</td>
<td class="auto-style6"><asp:TextBox ID="txtStudentID" runat="server" Enabled="False" ></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Student Name:</td>
<td class="auto-style6">
<asp:TextBox ID="txtStudentName" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Instructor Name</td>
<td class="auto-style6">
<asp:TextBox ID="txtInstructorName" runat="server" Enabled="False"></asp:TextBox>
</td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Code</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseCode" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Title:</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseTitle" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Start Time:</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseStartTime" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Attendance Code:</td>
<td class="auto-style6">
<asp:TextBox ID="txtAttendanceCode" runat="server"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
</table>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Save Code" OnClick="btnAdd_Click" />
<br />
<br />
<asp:Button ID="btnHelp" runat="server" Text="?" ToolTip="Instructions/Notes: You must be in the assigned classroom and on the wireless network to post your attendance. If you do not have a smartphone or laptop, borrow one from a friend or see your instructor. Enter the Attendance Code given out by the instructor for this class session and click Save Code" />
<br />
<br />
<asp:Label ID="lblMsg" runat="server" EnableViewState="False"></asp:Label>
<br />
<asp:Label ID="lblMsg3" runat="server" EnableViewState="False" Visible="False"></asp:Label>
<br />
<asp:Label ID="lblMsg2" runat="server" EnableViewState="False"></asp:Label>
<br />
<br />
<table>
<tr>
<%--<td class="auto-style2">
Record ID:</td>--%>
<td>
<asp:TextBox ID="txtRecordID" runat="server" Enabled="False" Width="251px" BackColor="White" BorderStyle="None" ForeColor="#E5E5E5"></asp:TextBox>
</td>
<td class="auto-style4">
</td>
</tr>
<tr>
<%--<td class="auto-style2">
UserID:</td>--%>
<td>
<asp:TextBox ID="txtUserID" runat="server" Width="251px" Enabled="False" BackColor="White" BorderStyle="None" ForeColor="#E5E5E5"></asp:TextBox></td>
<td class="auto-style4">
</td>
</tr>
</table>
<br />
<br />
<asp:Panel ID="Panel1" runat="server" Width="216px">
<br />
<%--Instructions/Notes:
<br />
-You must be in the assigned classroom and on thewireless network to post your attendance.
<br />
-If you do not have a smartphone or laptop, borrow from a friend or see your instructor.
<br />
-Enter the Attendance Code given out by the instructor for this class session and click Save Code.--%>
</asp:Panel>
<br />
</form>
</body>
</html>c#
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;public partial class addcourse : System.Web.UI.Page
{protected void Page_LoadComplete(object sender, EventArgs e)
{//MessageBox.Show("You are in the Form.Shown event.");
{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
var returnUrl = Request.Params["ReturnUrl"];
var hostID = Request.Params["HostID"];
if (string.IsNullOrWhiteSpace(hostID))
{
if (!string.IsNullOrWhiteSpace(returnUrl))
Response.Redirect(returnUrl);throw new Exception("Variable \"HostID\" not found in query params");
}con.Open();
var query = @"select distinct u.hostid as StudentID
,u.ID as UserID
,sd.scheduledaysid as CourseID
,sd.status
,sd.minutes
,sm.crs_cde as CourseCode
,sm.SHORT_CRS_TITLE_1 as CourseTitle
,sm.yr_cde
,sm.trm_cde
,sd.startTime AS CourseStartTime
,sd.startTime
,CONCAT(u.LastName, ', ',u.FirstName) AS StudentName
,u.Email
,nm.FIRST_NAME
,nm.MIDDLE_NAME
,CONCAT(nm.LAST_NAME, ', ',nm.FIRST_NAME) AS InstructorName
from ScheduleDays as sd
inner join lms_section as s on
sd.sectionid = s.SectionID
inner JOIN LMS_Course AS c WITH (NOLOCK) ON s.CourseID = c.CourseID
inner join section_master as sm on
c.CourseCode + ' ' + s.NAME = sm.crs_cde and
left(s.erpcoursekey,4) = sm.yr_cde and
substring(s.ERPCourseKey,6,2) = sm.trm_cde
inner join student_crs_hist as sch on
sm.crs_cde = sch.crs_cde and
sm.yr_cde = sch.yr_cde and
sm.trm_cde = sch.trm_cde
inner join fwk_user as u on
sch.id_num = u.hostid
inner join .name_master as nm on
sm.LEAD_INSTRUCTR_ID = nm.id_num
wheresd.startdate <= dateadd(mi, 10, @Now)
and sd.enddate >= @Nowand u.HostID = @HostID
and sm.crs_cde not like 'ONSO%'
AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
and sm.LOC_CDE = 'main'
and sch.TRANSACTION_STS = 'C'
orsd.startdate <= dateadd(mi, 10, @Now)
and sd.enddate >= @Nowand u.HostID = @HostID
and sm.crs_cde not like 'ONSO%'
AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
and sm.LOC_CDE = 'main'
and sch.TRANSACTION_STS = 'C'";var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("HostID", hostID);
cmd.Parameters.AddWithValue("now", DateTime.Now);string studentId = null, userId = null, studentName = null, courseId = null, courseCode = null, courseTitle = null, courseStartTime = null, instructorName = null;var reader = cmd.ExecuteReader();
if (reader.Read())
{
studentId = reader["StudentID"].ToString();
userId = reader["UserID"].ToString();
studentName = reader["StudentName"].ToString();
courseId = reader["CourseID"].ToString(); //courseId "86ab3a58-1d7c-4ced-82f9-d7ffacf17421" string
courseCode = reader["CourseCode"].ToString();
courseTitle = reader["CourseTitle"].ToString();
courseStartTime = reader["CourseStartTime"].ToString();
instructorName = reader["InstructorName"].ToString();
txtCourseCode.Text = courseCode;
txtCourseStartTime.Text = courseStartTime;
txtCourseTitle.Text = courseTitle;
txtInstructorName.Text = instructorName;
txtRecordID.Text = courseId;
txtStudentID.Text = studentId;
txtUserID.Text = userId;
txtStudentName.Text = studentName;
}else
{
lblMsg.Text = "You do not have a class in the next hour.";
//btnUpdate.Enabled = false;
//btnUpdate.Visible = false;
}reader.Close();
}
//catch (Exception ex)
catch (Exception)
{
//lblMsg.Text = "Error --> " + ex.Message;
//lblMsg.Text = "You do not have a class in the next hour.";
}
finally
{
con.Close();
}
}}
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
con.Open(); //string studentIpAddress = HttpContext.Current.Request.UserHostAddress;
string studentHost = HttpContext.Current.Request.UserHostName;//Insert uniqueidentifier for retries
SqlCommand cmd = new SqlCommand("insert into attendance(RecordID,StudentID,CourseID,CourseCode,AttendanceCode,DateTimeStamp, StudentHost, StudentIpAddress) values(newid(),@StudentID,@CourseID,@CourseCode,@AttendanceCode,CURRENT_TIMESTAMP, @StudentHost, @StudentIpAddress)", con); //101292cmd.Parameters.AddWithValue("@RecordID", txtRecordID.Text);
cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text);
cmd.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
cmd.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
cmd.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);
cmd.Parameters.AddWithValue("@StudentHost", studentHost);
cmd.Parameters.AddWithValue("@StudentIpAddress", studentIpAddress);int count = cmd.ExecuteNonQuery();
if (count == 1)
lblMsg.Text = "Attendance code logged"; //record logging of attendance code
else
lblMsg.Text = "Could not add code to log"; //showing message if there is some system error, the attendance code does not need to be validated here,//var query2 = "select 1 from InstructorCourse where CourseID = @CourseID and CourseCode = @CourseCode and AttendanceCode = @AttendanceCode";
var query2 = "select 1 from InstructorCourse where CourseCode = @CourseCode and AttendanceCode = @AttendanceCode";
var checkCmd2 = new SqlCommand(query2, con);
checkCmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
checkCmd2.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
checkCmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);
var reader2 = checkCmd2.ExecuteReader();if (reader2.Read())
{
SqlCommand cmd2 = new SqlCommand("insert into lms_attendance(attendanceID, userid, scheduledaysID, status) values(newid(),CAST(@UserID AS UNIQUEIDENTIFIER),CAST(@CourseID AS UNIQUEIDENTIFIER),'0')", con);
cmd2.Parameters.AddWithValue("@RecordID", txtRecordID.Text); //column was reserved for uniqueidentifier
cmd2.Parameters.AddWithValue("@StudentID", txtStudentID.Text); //needs to be fwk.UserID
cmd2.Parameters.AddWithValue("@UserID", txtUserID.Text);
cmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text); //scheduledaysID
cmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);//attendance code is verified, save
int count2 = cmd2.ExecuteNonQuery();
if (count2 == 1)
//lblMsg2.Text = "Attendance Code[" + txtCourseCode.Text + "] lms_attendance has been added!";
lblMsg2.Text = "Attendance saved";
else
lblMsg2.Text = "Attendance not added.";
}
else
{
// attendance code invalid
lblMsg2.Text = "Attendance code invalid.";
}}
//catch (Exception ex)
catch (Exception)
{
//lblMsg2.Text = "Error --> " + ex.Message;
//lblMsg2.Text = "Error --> " + ex.Message + " Identity:" + ;
}
finally
{
con.Close();
}
}
}Wednesday, May 22, 2019 8:01 PM
All replies
-
User-1174608757 posted
Hi Tom4IT.
If I use the javascript how do I pass the hostid to the c# code behind page?According to your description,I suggest that you could use javascript then you could use Hiddenfield to save value from javascript to c# code behind page.Here is a demo ,I hope it could help you.
aspx:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script> function SetValue() {
//put hostid value to HiddenField var hide = document.getElementById("host"); var hostid = "123"; hide.value = hostid; } </script> </head> <body> <form id="form1" runat="server"> <div>
<%--it will run clientclick for javascript then onclick for code behind--%> <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="SetValue()" OnClick="Button1_Click"/> <asp:HiddenField ID="host" runat="server" /> </div> </form> </body> </html>code behind:
public partial class AA : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) {
//show the value in hidden field which set in javascript Response.Write(host.Value); } }You could see:
Best Regards
Wei
Thursday, May 23, 2019 2:54 AM -
User1045460610 posted
I get some errors is I add that to a webform
aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DecodeJavascript.aspx.cs" Inherits="DecodeJavascript" %><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function SetValue()
{
//put hostid value to HiddenField
var hide = document.getElementById("host");
var hostid = "123";
hide.value = hostid;}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<%--clientclick for javascript then onclick for code behind--%>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="SetValue()" OnClick="Button1_Click"/><%--Severity Code Description Project File Line Suppression State
Error 'decodejavascript_aspx' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'decodejavascript_aspx' could be found (are you missing a using directive or an assembly reference?) C:\Users\THines\source\repos\new\WaystosenddatabetweenASPNETPages\WaystosenddatabetweenASPNETPages\DecodeJavascript.aspx 23
Severity Code Description Project File Line Suppression State
Error An object reference is required for the non-static field, method, or property 'DecodeJavascript.host' C:\Users\THines\source\repos\new\WaystosenddatabetweenASPNETPages\WaystosenddatabetweenASPNETPages\DecodeJavascript.aspx.cs 24
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'DecodeJavascript.host' WaystosenddatabetweenASPNETPages C:\Users\THines\source\repos\new\WaystosenddatabetweenASPNETPages\WaystosenddatabetweenASPNETPages\DecodeJavascript.aspx.cs 24 Active--%>
<asp:HiddenField ID="host" runat="server" />
</div>
</form>
</body>
</html>c#
using System;using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page
{
//Using Session State
protected void btnSessionState_Click(object sender, EventArgs e)
{
Session["Data"] = txtData.Text;
Response.Redirect("SessionState.aspx");
}//Using Query String
protected void btnQueryString_Click(object sender, EventArgs e)
{
Response.Redirect("QueryString.aspx?Data=" + Server.UrlEncode(txtData.Text));
}//Using Public Properties
protected void btnPublicProperties_Click(object sender, EventArgs e)
{
Server.Transfer("PublicProperties.aspx");
}
public string PublicData
{
get
{
return txtData.Text;
}
}//Using Control
protected void btnControl_Click(object sender, EventArgs e)
{
Server.Transfer("Control.aspx");
}
}Thursday, May 23, 2019 2:20 PM -
User475983607 posted
The error is telling you that the markup defines a server side click handler but the handler does not exist in the code behind.
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="SetValue()" OnClick="Button1_Click"/>
On a side note, it is unlikely this design is going to work as expected because you've also defined a JavaScript click handler.
Edit: also keep in mind that any JavaScript encryption is not truly safe because the source code is open. You should always encrypt data on the server and send it to the browser or store the values on the server like a database by the user's username.
Thursday, May 23, 2019 2:27 PM