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
Related
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);
}
}
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)
I'm trying to write an application in c#, which select task by means of unique ID. I tried to use several methods.
The first with "SelectTPTask" method
using Project = Microsoft.Office.Interop.MSProject;
public static Project.Application prjApp;
public static Project.Project msPrj;
prjApp = new Project.Application();
prjApp.FileOpenEx(Path);
prjApp.Visible = true;
msPrj = prjApp.ActiveProject;
if (msPrj.Tasks != null)
foreach (Project.Task task in msPrj.Tasks)
{
if (task.UniqueID == Id)
{
prjApp.SelectTPTask(task.UniqueID);
//prjApp.SelectRow(task.ID);
}
}
else
{
MessageBox.Show("Nothing found");
}
But it gives an unknown error. The only thing that earned is "SelectRow" method. But it works correctly only once, and then selects the wrong task. But if I restart MS Project, it works correctly 1 time, and then again to choose the wrong tasks.
The SelectRow method takes several arguments, the second of which indicates if the new selection is relative to the active row; the default is True. Use False for the second argument to select the absolute row.
Application.SelectRow Method (Project)
I created session to move data between pages using c# asp.net but the result does not appear and the program does not give me error in the code
first page code:
Session["New1"] = desc1.Text;
to send data to Label in Second page
code:
var userType = (string)Session["New1"];
if (userType != null)
{
Label1.Text = userType.ToString() ;
}
else
{
// test "2" etc
}
Try this,
if (Session["New1"]!= null)
{
Label1.Text = Session["New1"].ToString() ;
}
else
{
// test "2" etc
}
Try explicitly checking of your Session variable exists before attempting to use it to avoid any null-reference issues :
// Explicitly check that it exists
if (Session["New1"] != null)
{
// Then grab it (if it is a non-string type, then you can use as to cast it
// (e.g. a List might use Session["List"] as List<Widget>;)
Label1.Text = Convert.ToString(Session["New1"]);
}
else
{
// Do something here
}
This assumes that your value will be set prior to this code getting called. Additionally, any hiccups to the web server (e.g. timeouts, restarts, major exceptions, etc.) will clear all of the values within the Session.
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.