Drag & Drop using Dropzone
======================
$(document).ready(function () {
$('#contact-table').DataTable(
{
"stripeClasses": [],
bFilter: false, bInfo: false,
"lengthChange": true,
"lengthMenu": [[-1, 10, 25, 50], ["All", 10, 25, 50]],
"sDom": '<"top">rt<"bottom"lp><"clear">',
columnDefs: [
{ orderable: false, targets: -1 }
]
}
);
let Type = $('#<% =txtContactType.ClientID %>').val();
if (Type === 'C') {
$('.type').each(function () {
$(this).text('Caller');
});
}
var uploadButton = document.getElementById("uploadButton");
$("#uploadButton").click(function (e) {
this.disabled = true;
e.preventDefault();
});
// Initialize Dropzone on the specified div element
Dropzone.autoDiscover = false;
// Initialize Dropzone
var myDropzone = new Dropzone("#myDropzone", {
url: "Contacts.aspx",
maxFilesize: 10,
acceptedFiles: ".csv, .xlsx",
addRemoveLinks: true,
dictDefaultMessage: "Drop CSV or XLSX files here or click to upload (max. 10MB)", // Default message
autoProcessQueue: false,
maxFiles: 1,
init: function () {
this.on("addedfile", function (file) {
uploadButton.disabled = false;
console.log(this.files)
if (this.files.length > 1) {
this.removeAllFiles();
uploadButton.disabled = true;
}
if (!/\.(csv|xlsx)$/i.test(file.name)) {
$("#csvFileRequired").removeClass("d-none");
myDropzone.removeAllFiles();
uploadButton.disabled = true;
}
else {
$("#csvFileRequired").addClass("d-none");
uploadButton.disabled = false;
}
});
}
});
//myDropzone.on("sending", function (file, xhr, formData) {
//});
myDropzone.on("removedfile", function (file) {
if (myDropzone.getQueuedFiles().length === 0) {
uploadButton.disabled = true;
}
});
uploadButton.addEventListener("click", function () {
// Manually trigger the file upload when the button is clicked
myDropzone.processQueue();
});
myDropzone.on("success", function (file, response) {
location.reload();
// Check if the upload was successful
if (response.success === true) {
alert('success')
location.reload();
afterUploadCompletion(file);
} else {
console.error("File upload failed: " + file.name);
}
});
});
==================================================================================================================================================
Session Timeout
============
====
Model
======
<div
class="modal fade delete-modal"
id="sessionOutApp"
data-bs-backdrop="static"
data-bs-keyboard="false"
tabindex="-1"
aria-labelledby="deleteBackdropLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header delete-header">
<img src="/Images/Theme/delete.svg" />
</div>
<div class="modal-body">
<h3 class="heading-des">Session Expired</h3>
<p class="tb-btns">Your session has timed out. Please log in again.</p>
</div>
<div class="modal-footer delet-footer">
<div class="footer-group">
<asp:Button ID="btnDelete" runat="server" CssClass="delet-user" Text="Login again" autopostback="true" OnClick="LogOut_Click" />
</div>
</div>
</div>
</div>
</div>
=======
javascript
let sessionTimeout;
function setupSessionTimeoutAlert() {
sessionTimeout = setTimeout(function () {
let myModal = new bootstrap.Modal(document.getElementById('sessionOutApp'))
myModal.show()
}, 1200000); // 1200,000 milliseconds (20 minutes)
}
function resetSessionTimeout() {
clearTimeout(sessionTimeout);
setupSessionTimeoutAlert();
}
// Call the setupSessionTimeoutAlert function when the page loads
window.onload = setupSessionTimeoutAlert;
// Add event listeners to reset the timer on user interaction
window.addEventListener('mousemove', resetSessionTimeout);
window.addEventListener('keypress', resetSessionTimeout);
============
web config
============
<sessionState mode="InProc" timeout="20" /> for normal session
//for asp.net Membership logout
<authentication mode="Forms">
<forms loginUrl="~/Secure/Account/Login.aspx" timeout="20"/>
</authentication>
=======================
Global.asax
==================
void Session_End(object sender, EventArgs e)
{
if (Session["DataRealmID"] != null)
{
Session.Remove("DataRealmID");
}
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
===============
log out method
===============
protected void LogOut_Click(object sender, EventArgs e)
{
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-1);
}
if (Request.Cookies["DataRealmID"] != null)
{
Response.Cookies["DataRealmID"].Expires = DateTime.Now.AddDays(-1);
}
if (Session["DataRealmID"] != null)
{
Session.Remove("DataRealmID");
}
Session.Abandon();
FormsAuthentication.SignOut();
Response.Redirect("/Secure/Account/Login.aspx");
}
==================================================================================================================================================
Cryptography Encrypt Decrypt for adding token in url
====================
<add key="EncryptionKey" value="D34A256F5E6B49A1DB786E527DE9F6A3"/>
<add key="EncryptionIV" value="7F0E3A2C1D9B8F7A"/>
public static string GenerateToken(string username, Guid userId)
{
var customToken = new CustomToken
{
Username = username,
UserId = userId
};
string jsonToken = new JavaScriptSerializer().Serialize(customToken);
string encryptedToken = Encrypt(jsonToken);
return encryptedToken;
}
public static CustomToken ParseToken(string encryptedToken)
{
string decryptedToken = Decrypt(encryptedToken);
// Deserialize the token from JSON
var customToken = new JavaScriptSerializer().Deserialize<CustomToken>(decryptedToken);
return customToken;
}
static string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
static string Decrypt(string cipherText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
public class CustomToken
{
public string Username { get; set; }
public Guid UserId { get; set; }
}
==================================================================================================================================================
Send Email
Attach a photo
public static void SendEmail(string emailbody, string subject, string toEmail, bool isBodyHtml = true){string FromEmail = ConfigurationManager.AppSettings["FromEmail"].ToString();MailMessage mailMessage = new MailMessage(FromEmail, toEmail);mailMessage.Body = emailbody;mailMessage.Subject = subject;mailMessage.IsBodyHtml= isBodyHtml;// No need to specify the SMTP settings as these// are already specified in web.configSmtpClient smtpClient = new SmtpClient();smtpClient.Send(mailMessage);}
Web configuation for Email
<smtp from="toseef.ahmad@tkxel.io">
<network host="smtp.gmail.com" port="587" userName="email" password="app password" enableSsl="true" />
</smtp>
==================================================================================================================================================
XLSX Import using EPPLUS
if (file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
Stream stream = file.InputStream;
using (var package = new ExcelPackage(stream))
{
var worksheet = package.Workbook.Worksheets[0];
// Find the column indices based on column headers
int columnAIndex = -1; // 'Last Name'
int columnBIndex = -1; // 'First Name'
var headerRow = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column];
foreach (var cell in headerRow)
{
if (cell.Text == "Last Name")
{
columnAIndex = cell.Start.Column;
}
else if (cell.Text == "First Name")
{
columnBIndex = cell.Start.Column;
}
// Exit the loop once both columns are found
if (columnAIndex != -1 && columnBIndex != -1)
break;
}
if (columnAIndex != -1 && columnBIndex != -1)
{
for (int row = worksheet.Dimension.Start.Row + 1; row <= worksheet.Dimension.End.Row; row++)
{
string lastName = worksheet.Cells[row, columnAIndex].Text;
string firstName = worksheet.Cells[row, columnBIndex].Text;
dt.Rows.Add(Guid.NewGuid(), DataRealmID, this.Type, lastName, firstName);
}
}
else
{
throw new Exception("Invalid Template");
}
}
}
**********************************************************************************
*****************************************************************************
UTC Time Setting For showing correct time on browser without using on library
*****************************************************************************
Code:
$("#contact-table tr").each(function () {
var utcDateString = $(this).find('.utc-date').text().trim();
console.log("utc date from backend: ", utcDateString)
var dateTimeParts = utcDateString.split(/[\s/:]+/);
var month = dateTimeParts[0] - 1;
var day = dateTimeParts[1];
var year = dateTimeParts[2];
var hour = dateTimeParts[3];
var minute = dateTimeParts[4];
var second = dateTimeParts[5];
var date = new Date(Date.UTC(year, month, day, hour, minute, second));
console.log("newly made date: ", date)
const formattedDate = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}, ${date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })}`;
console.log("formatted client Datetime now: ", formattedDate);
//$(this).text(formattedDate);
//console.log(utcDateString);
//var utcDate = new Date(utcDateString);
//var localDate = utcDate.toLocaleString('en-US', { timeZone: 'UTC' }); // You can specify the user's time zone here
$(this).find('.local-date').text(formattedDate);
});
Console Logs:
utc date from backend: 7/17/2023 11:20:02 AM
DatabaseMaintenance.aspx:110 newly made date: Mon Jul 17 2023 16:20:02 GMT+0500 (Pakistan Standard Time)
DatabaseMaintenance.aspx:112 formatted client Datetime now: 7/17/2023, 4:20:02 PM
*******************************************************************************************
UTC Time Setting but this issue is server is adding its time automatically/magically. so for this Solution
*******************************************************************************************
Code C#:
TimeSpan timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now);
// Get the time zone offset in hours and minutes
hiddenFieldOffsetHours.Value = timeZoneOffset.Hours.ToString();
hiddenFieldOffsetMinutes.Value = timeZoneOffset.Minutes.ToString();
******************************************
html
*************************************
<asp:HiddenField ID="hiddenFieldOffsetMinutes" runat="server" />
<asp:HiddenField ID="hiddenFieldOffsetHours" runat="server" />
Code JS:
$('#UserTable tr').each(function () {
var curr = $(this);
var crDateValue = curr.find(".creationDate").text().trim();
var loginDateValue = curr.find(".loginDate").text().trim();
console.log('before', crDateValue);
crDateValue = ConvertToLocal(crDateValue);
loginDateValue = ConvertToLocal(loginDateValue);
console.log('after', crDateValue);
var creationDate = ConvertToUTC(crDateValue);
var loginDate = ConvertToUTC(loginDateValue);
if (creationDate != null && creationDate != "" && creationDate !== undefined) {
curr.find(".creationDate").text(creationDate.toLocaleString());
} if (loginDate != null && loginDate != "" && loginDate !== undefined) {
curr.find(".loginDate").text(loginDate.toLocaleString());
}
}
);
function ConvertToUTC(tempDate)
{
if (tempDate != null && tempDate != "" && tempDate !== undefined)
{
var dateTimeParts = tempDate.trim().split(/[\s/:]+/);
var month = dateTimeParts[0] - 1;
var day = dateTimeParts[1];
var year = dateTimeParts[2];
var hour = dateTimeParts[3];
var minute = dateTimeParts[4];
var second = dateTimeParts[5];
var date = new Date(Date.UTC(year, month, day, hour, minute, second));
const formattedDate = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}, ${date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })}`;
return formattedDate;
}
}
function ConvertToLocal(myDate) {
var offsetHours = document.getElementById('<%= hiddenFieldOffsetHours.ClientID %>').value;
var offsetMinutes = document.getElementById('<%= hiddenFieldOffsetMinutes.ClientID %>').value;
var myDate = new Date(myDate);
myDate.setHours(myDate.getHours() - parseInt(offsetHours));
myDate.setMinutes(myDate.getMinutes() - parseInt(offsetMinutes));
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1; // Months are zero-based
var day = myDate.getDate();
var hours = myDate.getHours();
var minutes = myDate.getMinutes();
var seconds = myDate.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
if (hours > 12) {
hours -= 12;
}
var formattedDate = month + '/' + day + '/' + year + ' ' + hours + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds + ' ' + ampm;
return formattedDate;
}
*********************************************************************************
*********************************************************************************
*********************************************************************************
*********************************************************************************
PII Compliance Just the above function decrypt encrypt method to use. I had a database that is existing so I have done some changes that are: created a User Defined Table Type and created a procedure for getting data table and modified with encrypted data
*****
SQL
*****
/****** Object: UserDefinedTableType [dbo].[ValuesType] Script Date: 10/23/2023 11:45:12 AM ******/ CREATE TYPE [dbo].[ValuesType] AS TABLE( [ID] [uniqueidentifier] NULL, [Value] [nvarchar](256) NULL ) GO
/****** Object: StoredProcedure [dbo].[spSetEncyptionOnPhoneNumbersEmailsAddresses] Script Date: 10/23/2023 11:46:07 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spSetEncyptionOnPhoneNumbersEmailsAddresses]
@ValueType [dbo].[ValuesType] READONLY,
@Table nvarchar(50)
AS
BEGIN
If (@Table = 'PhoneNumber')
Begin
UPDATE p
SET p.PhoneNumber = vt.[Value]
FROM [dbo].[PhoneNumbers] p
INNER JOIN @ValueType vt ON p.PhoneNumberID = vt.ID
End
If (@Table = 'Email')
Begin
UPDATE e
SET e.Email = vt.[Value]
FROM [dbo].[Emails] e
INNER JOIN @ValueType vt ON e.EmailID = vt.ID
End
If (@Table = 'Address1')
Begin
UPDATE a
SET a.Address1 = vt.[Value]
FROM [dbo].[Addresses] a
INNER JOIN @ValueType vt ON a.AddressiD = vt.ID
End
If (@Table = 'Address2')
Begin
UPDATE a
SET a.Address2 = vt.[Value]
FROM [dbo].[Addresses] a
INNER JOIN @ValueType vt ON a.AddressiD = vt.ID
End
If (@Table = 'ZIP')
Begin
UPDATE a
SET a.ZIP = vt.[Value]
FROM [dbo].[Addresses] a
INNER JOIN @ValueType vt ON a.AddressiD = vt.ID
End
END
******
C#
******
sp call
// use this to encrypt exising data by uncommenting the below code for PII Compliance.
//public static void SetEncyptionOnPhoneNumbersEmailsAddresses(DataTable valuesTypeTable, string table)
//{
// if(valuesTypeTable == null || string.IsNullOrEmpty(table))
// {
// return;
// }
// using (SqlConnection con = GetDatabaseConnection())
// {
// using (SqlCommand cmd = new SqlCommand("spSetEncyptionOnPhoneNumbersEmailsAddresses", con) { CommandType = CommandType.StoredProcedure })
// {
// SqlParameter parameter = new SqlParameter("@ValueType", SqlDbType.Structured);
// parameter.Value = valuesTypeTable;
// parameter.TypeName = "dbo.ValuesType";
// cmd.Parameters.Add(parameter);
// cmd.Parameters.AddWithValue("@Table", table);
// cmd.ExecuteNonQuery();
// }
// }
//}
Setting data table
#region "Helper.SetEncyptionOnPhoneNumbersEmailsAddresses"
//DataTable tableValueType = new DataTable();
//tableValueType.Columns.Add("ID", typeof(Guid));
//tableValueType.Columns.Add("Value", typeof(string));
//List<TableValues> tableValues = new List<TableValues>();
//Guid[] phoneIds ={
//new Guid(""),
//new Guid(""),
//new Guid(""),
//new Guid(""),
//new Guid(""),
//new Guid(""),
//new Guid(""),
//};
//string[] phoneValues = {
// "22222",
// "50550",
// "11111",
// "50550",
// "55117",
// "45660",
// "23233",
//};
//for (int i = 0; i < phoneIds.Length; i++)
//{
// TableValues table = new TableValues();
// table.Id = phoneIds[i];
// table.Value = Helpers.Encrypt(phoneValues[i]);
// tableValues.Add(table);
//}
//foreach (var item in tableValues)
//{
// tableValueType.Rows.Add(item.Id, item.Value);
//}
//Helpers.SetEncyptionOnPhoneNumbersEmailsAddresses(tableValueType, "ZIP");
#endregion "Helper.SetEncyptionOnPhoneNumbersEmailsAddresses"
*********************************************
Encrypt Decrypt methods with exception handled best for PII
public static string Encrypt(string plainText)
{
try
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
catch(Exception ex)
{
return plainText;
}
}
public static string Decrypt(string cipherText)
{
try
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
catch(Exception ex)
{
return cipherText;
}
}
*********************************************
*********************************************************************************************************************************************************************************************************************************************************
write above the <connectionStrings>
How to use it
c# part
******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
// Sorting Retention
var sortDirection = document.getElementById('<%= sortDirection.ClientID %>').value;
var columnIndex = document.getElementById('<%= sortColumnName.ClientID %>').value;
if (sortDirection === "" && columnIndex === "") {
localStorage.setItem("ContactIndex", 0);
localStorage.setItem("ContactDirection", 'asc');
}
$('#contact-table thead th').click(function () {
columnName = $(this).text().trim();
sortDirection = $(this).hasClass('sorting_asc') ? 'desc' : 'asc';
columnIndex = $('#contact-table thead th').index(this);
localStorage.setItem("ContactIndex", columnIndex);
localStorage.setItem("ContactDirection", sortDirection);
var ColumnName = document.getElementById('<%= sortColumnName.ClientID %>');
ColumnName.value = localStorage.getItem["ContactIndex"];
var Direction = document.getElementById('<%= sortDirection.ClientID %>');
Direction.value = localStorage.getItem["ContactDirection"];
});
// Sorting Retention End
----------------------------------------------------------------
,
order: [[localStorage.getItem("ContactIndex"), localStorage.getItem("ContactDirection")]],
----------------------------------------------------------------
before repeater in the table
<asp:HiddenField ID="sortDirection" Value="" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="sortColumnName" Value="" runat="server" ClientIDMode="Static"/>
------------------------------------------------------
More Example
$(document).ready(function () {
// Sorting Retention
var sortDirection = document.getElementById('<%= sortDirection.ClientID %>').value;
var columnIndex = document.getElementById('<%= sortColumnName.ClientID %>').value;
if (sortDirection === "" && columnIndex === "") {
localStorage.setItem("UserIndex", 0);
localStorage.setItem("UserDirection", 'asc');
}
$('#UserTable thead th').click(function () {
columnName = $(this).text().trim();
sortDirection = $(this).hasClass('sorting_asc') ? 'desc' : 'asc';
columnIndex = $('#UserTable thead th').index(this);
localStorage.setItem("UserIndex", columnIndex);
localStorage.setItem("UserDirection", sortDirection);
var ColumnName = document.getElementById('<%= sortColumnName.ClientID %>');
ColumnName.value = localStorage.getItem["UserIndex"];
var Direction = document.getElementById('<%= sortDirection.ClientID %>');
Direction.value = localStorage.getItem["UserDirection"];
});
// Sorting Retention End
$('#UserTable').DataTable(
{
"stripeClasses": [],
bFilter: false, bInfo: false,
"lengthChange": true,
"lengthMenu": [[-1, 10, 25, 50], ["All", 10, 25, 50]],
"sDom": '<"top">rt<"bottom"lp><"clear">',
columnDefs: [
{ orderable: false, targets: -1 }
],
order: [[localStorage.getItem("UserIndex"), localStorage.getItem("UserDirection")]],
}
);
=======================================================================================================================================================================================================================================
No comments:
Post a Comment