Skip to content

Instantly share code, notes, and snippets.

@saibimajdi
Last active April 5, 2017 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saibimajdi/296cd63d34d83ace85382b2461073743 to your computer and use it in GitHub Desktop.
Save saibimajdi/296cd63d34d83ace85382b2461073743 to your computer and use it in GitHub Desktop.
public class LicenceCheckerActionFilterAttribute : ActionFilterAttribute
{
public async override void OnActionExecuting(ActionExecutingContext filterContext)
{
var isValidLicence = await CheckLicence();
if (isValidLicence)
{
Debugger.Log(1, "LICENCE", "Licence is valid");
}
else
{
if (((string)filterContext.RouteData.Values["action"]).ToLower() != "error" ||
((string)filterContext.RouteData.Values["controller"]).ToLower() != "home")
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary(
new { controller = "Home", action = "Error" })
);
Debugger.Log(1, "LICENCE", "Licence not valid!");
}
//filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
}
#region Helpers
private async Task<bool> CheckLicence()
{
try
{
string token = File.ReadAllText(HttpContext.Current.Server.MapPath("/licence.lic"));
AES aes = new AES();
string clearText = aes.DecryptString(token);
if (clearText.Length == 114)
{
var thisServerID = $"{getCpuID()}{GetHardDiskSerialNo()}".PadLeft(100, '0');
var thisAppID = ConfigurationManager.AppSettings["appID"].ToString();
var serverID = clearText.Substring(0, 100);
var appID = clearText.Substring(100, 4);
var expirationDate = clearText.Substring(104, 10);
if (thisServerID == serverID && thisAppID == appID)
{
DateTime expDate = new DateTime(Convert.ToInt32(expirationDate.Substring(6, 4)),
Convert.ToInt32(expirationDate.Substring(3, 2)),
Convert.ToInt32(expirationDate.Substring(0, 2)));
// to be deleted
expDate = expDate.AddDays(10);
var now = DateTime.Now;
var daysLeft = Math.Abs((now - expDate).Days);
if (daysLeft <= 7)
{
if (expDate.CompareTo(now) < 0)
return false;
if (MvcApplication.LastAlertDate.Year != now.Year || MvcApplication.LastAlertDate.Month != now.Month || MvcApplication.LastAlertDate.Day != now.Day)
{
// send email to owner
await SendEmailToOwner(appID, daysLeft, expDate);
MvcApplication.LastAlertDate = now;
}
}
return expDate.CompareTo(now) > 0;
}
}
return false;
}
catch(Exception ex)
{
Debug.WriteLine($"EXCEPTION: {ex.Message}");
return false;
}
}
private async Task SendEmailToOwner(string appID, int daysLeft, DateTime expDate)
{
string body = $"Your application with the ID: <b>{appID}</b> will be locked after <span style='color:red;'>{daysLeft} day(s)</span>! <br />";
body += $"Expiration Date: <b>{expDate.ToShortDateString()}</b> <br />";
body += $"Please contact developers!";
var message = new MailMessage();
message.To.Add(new MailAddress(ConfigurationManager.AppSettings["owner_email"].ToString())); // owner email
message.From = new MailAddress("kouajamarwen@gmail.com"); // please replace the sendTo email address
message.Subject = $"Expiration Alert for {appID} application";
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = ConfigurationManager.AppSettings["MailLogin"].ToString(),
Password = ConfigurationManager.AppSettings["MailPassword"].ToString() };
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
}
private static string getCpuID()
{
ManagementClass management = new ManagementClass("win32_processor");
ManagementObjectCollection managementObjectCollection = management.GetInstances();
foreach (var managementObject in managementObjectCollection)
{
var cpuid = managementObject.Properties["processorID"].Value.ToString();
return cpuid;
}
return "";
}
private string getMotherBoardID()
{
string serial = "";
try
{
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard");
ManagementObjectCollection moc = mos.Get();
foreach (ManagementObject mo in moc)
{
serial = mo["SerialNumber"].ToString();
}
return serial;
}
catch (Exception ex)
{
//MessageBox.Show("Message : " + ex.Message, "Exception!");
return serial;
}
}
public string GetHardDiskSerialNo()
{
ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection mcol = mangnmt.GetInstances();
string result = "";
foreach (ManagementObject strt in mcol)
{
result += Convert.ToString(strt["VolumeSerialNumber"]);
}
return result;
}
#endregion
}
/*
<add key="owner_email" value="saibimajdi@gmail.com"/>
<add key="MailLogin" value="performrxinfo@gmail.com"/>
<add key="MailPassword" value="HealthHealth"/>
// Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
public static DateTime LastAlertDate { get; set; }
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment