Add expiration to C# windows application - c#

i am trying to make make app expire after some days using the registry option, i have successfully written and read from registry, my issue is to check for expiration, below is my code:
regKey = Registry.CurrentUser.OpenSubKey("Systemfiles");//subkeyname
if (regKey == null)
{
regKey = Registry.CurrentUser.CreateSubKey("Systemfiles");
regKey.SetValue("tere", Encrypt("4/16/2017"));
}
else
{
regKey = Registry.CurrentUser.OpenSubKey("Systemfiles");//subkeyname
string decryptDateValue = Decrypt(regKey.GetValue("tere").ToString()); //Keyname
DateTime mainDate = Convert.ToDateTime(decryptDateValue);
DateTime expiringDate = mainDate.AddDays(1);
if (mainDate > expiringDate)
{
expire = true;
}
else
{
//Continue execution
}
}
from my code i assumed the user's first run is the 04/16/2017, i also assumed i want the user to run the application for one day, which supposed to expire on the 04/17/2017, meaning if the user tries to start the application after 04/17/2017 the if part should execute, but i am not really getting it right, the else part always execute, i will appreciate a better way of doing it. Thanks

You've got this in your code:
DateTime expiringDate = mainDate.AddDays(1);
if (mainDate > expiringDate)
So,expiringDate would always be bigger than mainDate (one day exactly).
What you want to check is the actual Date, so it should be:
if (DateTime.Now>expiringDate)

Related

Xamarin/XAML/C# - How do I set up my App.Current.Properties dictionary?

Problem: I'm writing an app that calculates holiday leave days. On app start up, the user is prompted to enter their total number of leave days and this is stored in a static string called LeaveDays. I realised after reinstalling my app that the LeaveDays variable gets reset. Okay, so I need to save this data properly. I find that people often use the Application.Current.Properties option, so instead of assigning the LeaveDays variable to the value of the prompt entry, I assign it to the Application.Current.Properties["LeaveDays"] key.
Now my problem is that I don't have the key set anywhere and I'm getting a KeyNotFoundException. I think it should be set in the main App file but I don't want to instantiate it with any value. That value needs to come from the prompt. I'm sure I've just misread the documentation on this one but I'm not sure how the property dictionary should be set up and how it works with manual input.
Below is the code for my popup. Any help is much appreciated:
async void SetLeaveDaysPopup()
{
VersionTracking.Track();
var firstLaunch = VersionTracking.IsFirstLaunchEver;
if (firstLaunch == true || ChangeLeaveDaysButton.IsEnabled == true)
{
Application.Current.Properties["LeaveDays"] = await DisplayPromptAsync("Set Leave Days", "Please set the amount of total leave days you have");
EntitlementDaysText.Text = Application.Current.Properties["LeaveDays"] as string;
calculateLeaveHours(EntitlementDaysText.Text);
}
}
Fixed code with Jason's help:
async void SetLeaveDaysPopup()
{
VersionTracking.Track();
var firstLaunch = VersionTracking.IsFirstLaunchEver;
if (firstLaunch == true || ChangeLeaveDaysButton.IsEnabled == true)
{
Application.Current.Properties["LeaveDays"] = await DisplayPromptAsync("Set Leave Days", "Please set the amount of total leave days you have");
await Application.Current.SavePropertiesAsync();
if (Application.Current.Properties.ContainsKey("LeaveDays"))
{
EntitlementDaysText.Text = Application.Current.Properties["LeaveDays"] as string;
}
calculateLeaveHours(EntitlementDaysText.Text);
}
}

One time validation of user input to run application

I've made a WinForms application in C#.NET.
On first run I'm checking if 2 strings are equal, if its TRUE then the main form appears. However currently, this check is done whenever I start the program.
How can I pass this "validation result" to the computer so that every next run of the application, there will be no more checks needed?
One option is to store validation data in the registry. If the lines are equal, then create a branch in the registry and write the necessary data into it. Next, at the next start, we check for the presence of a branch and data in it. I attach a quick example.
string FisrtString = "Temp";
string SecondString = "Temp";
string SubBaseKeyString = #"SOFTWARE\ApplicationName";
RegistryKey vmsBaseKey = Registry.CurrentUser.OpenSubKey(SubBaseKeyString, true);
if (vmsBaseKey != null)
{
var Value = vmsBaseKey.GetValue("Validate");
if (Value != null)
{
if (Value.ToString() == "1")
{
//The user check passed here, you can open the window
}
}
else
{
//Here you must specify the action if the key is missing. Additional string comparison possible
}
}
else
{
if (FisrtString == SecondString)
{
//If the first line is equal to the second line, then assign a value
//The user check passed here, you can open the window
RegistryKey KEY_CREATE = Registry.CurrentUser.CreateSubKey(SubBaseKeyString);
KEY_CREATE.SetValue("Validate", "1");
KEY_CREATE.Close();
}
else
{
//If the first line is not equal to the second line, then we perform the desired action
}
}
You could save the result of your check into a config file and read it next time your program starts from the config file

How top expire exe after certain date-time in unity

I am developing unity build (exe) and trying to implement such an algorithm that expire my player after certain time (e.g., after one week or one month). Here is the complete tested code with one little (actually big) problem:
public class LocalLimitedDaysLicense : MonoBehaviour
{
float numberOfDays = 3;
public string currentDate;
bool isShowExpiryMessage;
void Awake()
{
string playerPrefKeyName = "PlayerStartDateKey";
currentDate = DateTime.Now.ToString();
string playerStartDate = PlayerPrefs.GetString(playerPrefKeyName, "");
if (!PlayerPrefs.HasKey(playerPrefKeyName))
{
Debug.Log("Player Start Date Setting");
PlayerPrefs.SetString(playerPrefKeyName, currentDate);
}
else
{
Debug.Log("Player Start Date already Set");
}
string playerPrefsSaveDate = PlayerPrefs.GetString(playerPrefKeyName);
DateTime today = DateTime.Now;
DateTime playerFirstActiveDate = Convert.ToDateTime(PlayerPrefs.GetString(playerPrefKeyName));
DateTime playerLimitDate = playerFirstActiveDate.AddDays(numberOfDays);
if (DateTime.Compare(today, playerLimitDate) > 0)//confirm that
{
Time.timeScale = 0;
isShowExpiryMessage = true;
}
if (DateTime.Compare(today, playerFirstActiveDate) < 0)//Confirm that user didn't change the date of system
{
Time.timeScale = 0;
isShowExpiryMessage = true;
}
}
void OnGUI()
{
if (isShowExpiryMessage)
{
GUI.Label(new Rect((Screen.width / 2) - 100, Screen.height / 2, 300, 100), "Sorry the exe has expired.!");
}
}
}
It truly halt the program if certain days passed in the build but the problem is, if the user removed the old build and installed the build again then it will allow three days again.
1.Create a web API that will register the date to the server database.
2.Create another API That returns true or false depending on your player expire logic and fire the API when the game starts every time.
It's not possible to control that from the client only.
By the way, there is another more simple flaw in your checking logic : user can simply change the date on its machine.
Do not try to enforce security features by trusting information from client only. Especially things that can be simply checked serverside.
As suggested by Reezoo Bose, you should implement some server-side checking.
(And if you want to prevent hacking this protection, you should also secure the communication with correct authentication and message signing. Of course it depends on which "tech level" users you are willing to protect your software against.)

Is there anything like 'update time' for ASP.NET-MVC application?

My web-site returns information for items which it takes from disk (involving some logic located in the controller, so it is not just static assets). I tried to optimize it by returning 304 for items which are not changed, by getting file write time for the corresponding item. Now, after I update the code, my application still thinks that an item is not updated and returns 304 - it does not realize that application code is changed so the result would be different. Because of that users do not see the update immediately, only after they get rid of their cache. I would like to solve that problem by checking not only 'item update time' but also 'application update time'. Is there a way to get something like time when application was updated? By this time I would like to see kind of maximum of update times of all application files.
UPD:
As asked for example code, here is slightly simplified version:
public static DateTime? LastKnownDate(this HttpRequestBase request)
{
if (!string.IsNullOrEmpty(request.Headers["If-Modified-Since"]))
{
var provider = CultureInfo.InvariantCulture;
DateTime date;
if (DateTime.TryParse(
request.Headers["If-Modified-Since"],
provider,
DateTimeStyles.RoundtripKind,
out date)) return date;
}
return null;
}
public ActionResult Test(int id)
{
var path = #"C:\data\" + id;
var file = new FileInfo(path);
if (!file.Exists) return HttpNotFound();
var date = Request.LastKnownDate();
if (date != null && date >= file.LastWriteTimeUtc)
{
return Response.NotModified();
}
Response.AddHeader("Last-Modified", file.LastWriteTimeUtc.ToString("o"));
return File(path, "application/octet-stream");
}
I think you need something like HTTP conditional GET. More details in the spec.
This is how you can do that in ASP.NET : http://optimizeasp.net/conditional-get
Also take a loot at: Improving Performance with Output Caching

How can I check if a program is running for the first time?

My program sets its display based on if the program is running for the first time or not. In order to determine if the program is running for the first time I am currently using a
//this boolean exists within my programs settings
Setting boolean FirstRun = True;
When the program runs it calls a method that checks the state of that bool value and acts accordingly:
if(Properties.Settings.FirstRun == true)
{ lblGreetings.Text = "Welcome New User";
//Change the value since the program has run once now
Properties.Settings.FirstRun = false;
Properties.Settings.Save(); }
else
{ lblGreetings.Text = "Welcome Back User"; }
It seems to work pretty effectively, however if the .exe file is moved and launched from a new location it considers it a first run, and I'm concerned that I'm doing this in a messy fashion and perhaps there exists a more efficient manner to test for the programs first run. Is there a better way to do this?
Seems that your problem is actually that if you move executable to another location/folder on the same pc, it loses somehow the information about the fact that it was already run at least once.
Using UserSettings, on Properties.Settings.Default.FirstRun should resolve your problem.
Something like this, a pseudocode:
if(Properties.Settings.Default.FirstRun == true)
{ lblGreetings.Text = "Welcome New User";
//Change the value since the program has run once now
Properties.Settings.Default.FirstRun = false;
Properties.Settings.Default.Save(); }
else
{ lblGreetings.Text = "Welcome Back User"; }
Look on this sample how to achieve that in more detailed way.
Since your question appears to be concerned about each user that launches the application, then you should design a per-user solution.
Using Properties.Settings will actually work and be efficient as long as the setting in question is user-specific.
However, if this is not desired or appropriate for your application, you could also write a user-specific entry to the registry.
For example:
const string REGISTRY_KEY = #"HKEY_CURRENT_USER\MyApplication";
const string REGISTY_VALUE = "FirstRun";
if (Convert.ToInt32(Microsoft.Win32.Registry.GetValue(REGISTRY_KEY, REGISTY_VALUE, 0)) == 0)
{
lblGreetings.Text = "Welcome New User";
//Change the value since the program has run once now
Microsoft.Win32.Registry.SetValue(REGISTRY_KEY, REGISTY_VALUE, 1, Microsoft.Win32.RegistryValueKind.DWord);
}
else
{
lblGreetings.Text = "Welcome Back User";
}
Hard to guess what is messy if you don't post or describe it. An obvious approach is to have a setting named "ExePath". If you get null or a string that doesn't match Assembly.GetEntryAssembly().Location then it got either just installed or moved.

Categories