Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sharing actual values of variable between installer project and installed project in a solution

Status
Not open for further replies.

WomanPro

Programmer
Nov 1, 2012
180
GR
Hello, I have a solution with mulitple projects.
The main project wich is a game, a project with an installer class and a registration license key form named RegistrationLicense and the setup project.
In the setup project, inside user interface I have add a custom dialog with two option buttons one for trial and one for license it's being located after License Agreement.
During setup running in case the user chooses the licensed option I load the registration form in which there is the Product ID, I generate the product key with a button and I registrate through registate button the license and everything works fine. Inside the installer class ovveridden Install I use the SetEnvironmentVariable to store the selection of the user during installation.
Code:
Environment.SetEnvironmentVariable("AppFreeTrial", mSetupType.FreeTrialFlg)
Environment.SetEnvironmentVariable("AppLicensed", mSetupType.LicensedFlg)

Now, in the main program which is a game and belongs to another project in the same solution, I tried to retrieve the AppLicensed value with
Code:
MsgBox(Environment.GetEnvironmentVariable("AppLicensed"))
MsgBox(Environment.GetEnvironmentVariable("AppFreeTrial"))
in order to be sure that I have the appropriate value of the user selection in the radio button of the custom install, because if the selection is FreeTrial I want to run the FreeTrial function in the game program that is being installed. Unfortunately the values of AppLicensed and AppFreeTrial and I don't know how to achieve it, any suggestion please?

I thought about adding a reference in game project from the RegistrationLicense project, but I would have to create an instance of that, so it doesn't serves me at all because I will not get the actual values of user selection during installation. I thought about storing these values of installer project to a database but I have to install the database first, so I feel a little bit stuck to find a good solution. Any help will be much appreciated. Thank you so much in advanced.
 
I don't know how to that. How can I take advantage from this?
 
Really interesting, I would like to ask you, in case I use Registry, is it possible to prevent user to change these values manually? Because I want these values to be inserted only from installer class and the user to be unable to change these values from registry, because I don't want the user to be able to stop the FreeTrial version throught manually changing values
 
You can certainly prevent it better than you can with environment variables.

For example, once you have a reference to a RegistryKey (using the methods described in the documentation I linked to), you can set user access rights to that key (much like the security attributes on a file), e.g here
 
Thank you, I will give it a try and I will let you know if I have any question. Is it a better option rather than storing variables with their values to a txt file?
 
>Is it a better option

Depends on how determined you think your users may be in trying top beat your licencing. The registry is a slightly better option against users who know little about Windows. But in and of itself wouldn't be much of a barrier to e.g any decent Windows programmers. In the end storing a string under a key in the registry is simply a level of obfuscation when compared to saving the same key in a text file, and obfuscation isn't really security.

If you really want to stop people messing with licence keys you have to do a lot more work, which is why there's a whole industry grown up around this sort of thing. There are some free licencing libraries available for .Net, for example EasyLicence. Please be aware that I am not specifically recommending this library; I've not used it at all. It was just the first one that came up in a quick Google.
 
In the installer class I have the following code
Code:
Public Overrides Sub Install(stateSaver As IDictionary)
        '08062023
        Dim SelectionValue = Context.Parameters("SetupTypeValue")
        Dim myvalue = Integer.Parse(SelectionValue)

        mContextSelection = myvalue
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "BackgammonRegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey


        If myvalue = 1 Then
            My.Settings.FreeTrialStr = "FREETRIAL"
            My.Settings.FreeTrial = True
            mSetupType.FreeTrialFlg = True
            mSetupType.LicensedFlg = False
            Environment.SetEnvironmentVariable("AppFreeTrial", mSetupType.FreeTrialFlg)
            Environment.SetEnvironmentVariable("AppLicensed", mSetupType.LicensedFlg)
            'TestSqlConnection.SetupType.mSetupType.FreeTrialFlg = True
            Registry.SetValue(keyName, "Licensed", False.ToString)
            Registry.SetValue(keyName, "FreeTrial", True.ToString)
            Registry.SetValue(keyName, "Expired", False.ToString)
        ElseIf myvalue = 2 Then
            My.Settings.LicensedStr = "FULL"
            My.Settings.Licensed = True
            mSetupType.LicensedFlg = True
            mSetupType.FreeTrialFlg = False
            Environment.SetEnvironmentVariable("AppFreeTrial", mSetupType.FreeTrialFlg)
            Environment.SetEnvironmentVariable("AppLicensed", mSetupType.LicensedFlg)
            'TestSqlConnection.SetupType.mSetupType.LicensedFlg = True
            RegistrateFrm.Activate()
            RegistrateFrm.ShowDialog()
        End If
        RegistrateFrm.CreateFile()

        MyBase.Install(stateSaver)
    End Sub

In my main application that is being installed
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load    
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "BackgammonRegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        Dim tInteger As Integer = CInt(Registry.GetValue(keyName, "", -1))
        Dim LicensedFlg, TrialFlg As Boolean
        LicensedFlg = Convert.ToBoolean(Registry.GetValue(keyName, "Licensed", Nothing))
        TrialFlg = Convert.ToBoolean(Registry.GetValue(keyName, "FreeTrial", Nothing))
        MsgBox("TrialFlg " & TrialFlg)
        MsgBox("Licensed " & LicensedFlg)
        If TrialFlg <> Nothing Then
            If TrialFlg = True Then
                Trial()
            End If
        End If

        If My.Settings.Checked Then
            Dim user As String = Environment.UserDomainName & "\" & Environment.UserName
            Dim rs As New RegistrySecurity

            'Επιτρέπουμε στον χρήστη μόνο να διαβάσει το RegistryKey
            rs.AddAccessRule(New RegistryAccessRule(user, RegistryRights.ReadKey, InheritanceFlags.None,
                                                    PropagationFlags.None, AccessControlType.Allow))

            rs.AddAccessRule(New RegistryAccessRule(user, RegistryRights.WriteKey Or
                      RegistryRights.Delete Or RegistryRights.ChangePermissions Or RegistryRights.FullControl,
                                                    InheritanceFlags.None,
                                                    PropagationFlags.None, AccessControlType.Deny))
          
            Dim rk As RegistryKey = Nothing

            rk = Registry.CurrentUser.CreateSubKey("RegistryRightsExample",
                    RegistryKeyPermissionCheck.Default, rs)

            rk.SetValue("ValueName", "StringValue")
        End If
    End Sub
    Public Sub Trial()
        If Not My.Settings.Checked Then
            My.Settings.TrialTime = DateTime.Now  'TrialTime
            My.Settings.Checked = True
            My.Settings.ActivatedTrial = True
            My.Settings.LastDateUsed = DateTime.Now
            My.Settings.Expired = False
            MessageBox.Show("First Run...")
        Else
            If (My.Settings.TrialTime.Add(New TimeSpan(1, 0, 0, 0)) > DateTime.Now) And (My.Settings.LastDateUsed > DateTime.Now = False) And
               My.Settings.Expired = False Then

                My.Settings.ActivatedTrial = True
                MessageBox.Show("Trial Active...")
            Else
                If (DateTime.Now <= My.Settings.LastDateUsed Or My.Settings.TrialTime <= DateTime.Now Or My.Settings.Expired) Then
                    MessageBox.Show("Trial Expired...")
                    My.Settings.ActivatedTrial = False
                    My.Settings.Expired = True

                    Const userRoot As String = "HKEY_CURRENT_USER"
                    Const subkey As String = "BackgammonRegistrySetValueExample"
                    Const keyName As String = userRoot & "\" & subkey
                    Registry.SetValue(keyName, "Expired", True.ToString)

                    Me.Close()
                End If
            End If
        End If
    End Sub
Unfortunately the LicensedFlg and TrialFlg don't hold the value I have given Licensed and FreeTrial variables with the SetValue in the installer class. Why does this happen? What am I missing?
May you explain me please? Thank you so much in advanced.
Code:
LicensedFlg = Convert.ToBoolean(Registry.GetValue(keyName, "Licensed", Nothing))
TrialFlg = Convert.ToBoolean(Registry.GetValue(keyName, "FreeTrial", Nothing))
MsgBox("TrialFlg " & TrialFlg)
MsgBox("Licensed " & LicensedFlg)
 
Well,
Code:
[COLOR=blue]
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "ExampleMike"
        Const keyName As String = userRoot & "\" & subkey

        Registry.SetValue(keyName, "Licensed", False.ToString)
        Dim myresult As Boolean = Convert.ToBoolean(Registry.GetValue(keyName, "Licensed", Nothing))
        MsgBox(myresult)[/color]

works fine here, as I'd expect. So the only thing I can currently think of is that your installer is running in a different user context from the main program
 
"works fine here, as I'd expect. So the only thing I can currently think of is that your installer is running in a different user context from the main program"

Yes, you are definately right and the reason for that is that the installer runs during installation as I mentioned above I have 3 projects in a solution:
A project with an installer class and a registration license key form named RegistrationLicense (this runs during installation), the main project that is being installed and the setup project.
During setup installation I provide two options to be choosen to be installed, FreeTrial and Licensed. If the user chooses Licensed the Registration form is being loaded and the LicensedKey is generated and registrated through a button so the installer class is executed and passing the user context from custom action values to the registration form which belongs to the same project with the installer as I want it to run during installation. As far as FreeTrial option is concerned the installer class with the registration form doesn't take part at all. But I need the value of user context selection to be visible to main program that is being installed. So, when we first run-launch the main program (main project that is being installed) the FreeTrial function of main program takes part, in order to execute the Trial Version of the product for a specific period of time. As you understand in the setup project I have two differenent project outputs in file system to be executed seperately. And this is my main problem that I need the context user values of the radio button I set in the user interface to be retrieved to the main project. So, the registry didn't work for me, are we able to make it work with registry and how? Or do you have any other suggestion please? Thank you so much in advanced.
 
>HKEY_CURRENT_USER is not the only Registry hive we can use.

Have a look at HKEY_LOCAL_MACHINE, for eample. It has some tighter access rules about writing keys, but anyone can read. So run your installer with admin permissions, then this should work fine:

Code:
Const userRoot As String = "HKEY_LOCAL_MACHINE"
Const subkey As String = "SOFTWARE\WomanPro\Backgammon"
Const keyName As String = userRoot & "\" & subkey

Registry.SetValue(keyName, "Licensed", False.ToString)

and then in the main program (no admin rights required, just a normal user)

Code:
Const userRoot As String = "HKEY_LOCAL_MACHINE"
Const subkey As String = "SOFTWARE\WomanPro\Backgammon"
Const keyName As String = userRoot & "\" & subkey

Dim myresult As Boolean = Convert.ToBoolean(Registry.GetValue(keyName, "Licensed", Nothing)) ' RegistryValueKind.String))
MsgBox(myresult)

should work as well



t
 
I have a question please, you told me to run myinstaller with admin permissions, how can I do this with source code?
I am thinking that in case a user installs the game on his machine, I want him to have automatically the rights for that, not facing any problem
I haven't tried yes with HKEY_LOCAL_MACHINE, I tried creating a txt file for the variables and their values in order to be visible on multiple projects in my solution, it works fine but I have the same probem,
I must provide the rights manually to the c:\ in order the application to replace some values for the Trial function I have created. That's a serious problem because gives error during runtime of the game that is being installed. So I must do it automatically through code and I don't know how to do that, or if I will face the same problem with registries... Any suggestion please?
 
>how can I do this with source code?

In Visual Studio ide select

[tt]Project > Add New Item ... > Common Items > Application Manifest File[/tt] (you may need to select "[tt]Show All Templates[/tt]" after [tt]Add New Item[/tt] if the view starts in compact mode)

Change the [tt]<requestedExecutionLevel>[/tt] element in the manifest file to:

[tt]<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />[/tt]

Note this does NOT have the correct effect if you try and run your program in Visual Studio (it'll tell you to restart Visual Studio as an administrator. IOntead, you'll need to Build the solution, and run that compiled build. At which point you'll get the UAC prompt, and bob's your uncle
 
I tried the following and getting error unhandled exception, the parameter is incorrect.

The following works fine in the installer class during installation without any error.
Code:
Public Overrides Sub Install(stateSaver As IDictionary)
        '08062023
        Dim SelectionValue = Context.Parameters("SetupTypeValue")
        Dim myvalue = Integer.Parse(SelectionValue)

        mContextSelection = myvalue
        Const userRoot As String = "HKEY_LOCAL_MACHINE"
        Const subkey As String = "SOFTWARE\WomanPro\Backgammon" '"BackgammonRegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey


        If myvalue = 1 Then
            My.Settings.FreeTrialStr = "FREETRIAL"
            My.Settings.FreeTrial = True
            mSetupType.FreeTrialFlg = True
            mSetupType.LicensedFlg = False
            mSetupType.SettingsChecked = True
            mSetupType.Expired = False
            mSetupType.TrialTime = DateTime.Now
            mSetupType.ActivatedTrial = True
            mSetupType.LastDateUsed = DateTime.Now

            Environment.SetEnvironmentVariable("AppFreeTrial", mSetupType.FreeTrialFlg)
            Environment.SetEnvironmentVariable("AppLicensed", mSetupType.LicensedFlg)
            Environment.SetEnvironmentVariable("AppChecked", mSetupType.SettingsChecked)
            Environment.SetEnvironmentVariable("AppExpired", mSetupType.Expired)
            Environment.SetEnvironmentVariable("AppTrialTime", mSetupType.TrialTime)
            Environment.SetEnvironmentVariable("AppActivatedTrial", mSetupType.ActivatedTrial)
            Environment.SetEnvironmentVariable("AppLastDateUsed", mSetupType.LastDateUsed)


            'TestSqlConnection.SetupType.mSetupType.FreeTrialFlg = True
            Registry.SetValue(keyName, "Licensed", False.ToString)
            Registry.SetValue(keyName, "FreeTrial", True.ToString)
            Registry.SetValue(keyName, "Expired", False.ToString)
            Registry.SetValue(keyName, "Checked", True.ToString)
            Registry.SetValue(keyName, "TrialTime", mSetupType.TrialTime.ToString)
            Registry.SetValue(keyName, "ActivatedTrial", mSetupType.ActivatedTrial.ToString)
            Registry.SetValue(keyName, "LastDateUsed", mSetupType.LastDateUsed.ToString)

            'MsgBox("Username " & GetUserName())
            'MyAPI.SetFolderPermissions("C:\BackgammonTxt\AppDataFile.txt", GetUserName, True)
            'MyAPI.SetFolderPermissions("C:\BackgammonTxt", GetUserName, True)
            RegistrateFrm.CreateFile()
            '17062023 na to ksanadw
            'MyAPI.SetFolderPermissions("C:\BackgammonTxt\AppDataFile.Txt", GetUserName, True)
        ElseIf myvalue = 2 Then
            My.Settings.LicensedStr = "FULL"
            My.Settings.Licensed = True
            mSetupType.LicensedFlg = True
            mSetupType.FreeTrialFlg = False
            Environment.SetEnvironmentVariable("AppFreeTrial", mSetupType.FreeTrialFlg)
            Environment.SetEnvironmentVariable("AppLicensed", mSetupType.LicensedFlg)
            Environment.SetEnvironmentVariable("AppExpired", False)
            'TestSqlConnection.SetupType.mSetupType.LicensedFlg = True
            RegistrateFrm.Activate()
            RegistrateFrm.ShowDialog()
        End If
        RegistrateFrm.CreateFile()

        MyBase.Install(stateSaver)
    End Sub

'Here I am getting error when trying to load my main form application
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        
        '15062023 keys
        Const userRoot As String = "HKEY_LOCAL_MACHINE" '"HKEY_CURRENT_USER"
        Const subkey As String = "SOFTWARE\WomanPro\Backgammon" '"BackgammonRegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        Dim tInteger As Integer = CInt(Registry.GetValue(keyName, "", -1))
        Dim LicensedFlg, TrialFlg As Boolean
        LicensedFlg = Convert.ToBoolean(Registry.GetValue(keyName, "Licensed", Nothing))
        TrialFlg = Convert.ToBoolean(Registry.GetValue(keyName, "FreeTrial", Nothing))

        MsgBox("TrialFlg " & TrialFlg)
        MsgBox("Licensed " & LicensedFlg)
        
       
        Dim user As String = Environment.UserDomainName & "\" & Environment.UserName
        Dim rs As New RegistrySecurity
        If My.Settings.Checked Then

            'Επιτρέπουμε στον χρήστη μόνο να διαβάσει το RegistryKey
            rs.AddAccessRule(New RegistryAccessRule(user, RegistryRights.ReadKey, InheritanceFlags.None,
                                                    PropagationFlags.None, AccessControlType.Allow))

            Dim rk As RegistryKey = Nothing

            rk = Registry.LocalMachine.CreateSubKey("RegistryRightsExample",
                    RegistryKeyPermissionCheck.Default, rs)

            rk.SetValue("ValueName", "StringValue")
            rk.Close()
        End If
        If FreeTrialFlg Then
            Trial(Checked)
        End If

        'We don't allow user to read or delete RegistryKey
        
        rs.AddAccessRule(New RegistryAccessRule(user, RegistryRights.WriteKey Or
                  RegistryRights.Delete Or RegistryRights.ChangePermissions Or RegistryRights.FullControl,
                                                InheritanceFlags.None,
                                                PropagationFlags.None, AccessControlType.Deny))

        Dim rk_ As RegistryKey = Nothing

        rk_ = Registry.LocalMachine.CreateSubKey("RegistryRightsExample",
                RegistryKeyPermissionCheck.Default, rs)

        rk_.SetValue("ValueName", "StringValue")
        rk_.Close()
       
    End Sub

Code:
 Public Sub Trial(ByVal Checked As Boolean)
        If  Checked Then
            Dim TrialTime, LastDateUsed As Date
            Dim Expired As Boolean
            TrialTime = Arranges.FirstOrDefault(Function(x) x.Name.Equals("TrialTime")).mTypeOfValue.ValueOfDateType
            LastDateUsed = Arranges.FirstOrDefault(Function(x) x.Name.Equals("LastDateUsed")).mTypeOfValue.ValueOfDateType
            Expired = Arranges.FirstOrDefault(Function(x) x.Name.Equals("Expired")).mTypeOfValue.ValueOfBoolType

            If (TrialTime.Add(New TimeSpan(1, 0, 0, 0)) > DateTime.Now) And (LastDateUsed > DateTime.Now = False) And
                Expired = False Then

                My.Settings.ActivatedTrial = True
                MessageBox.Show("Trial Active...")
            Else
                If (DateTime.Now <= LastDateUsed Or TrialTime <= DateTime.Now Or Expired) Then
                    MessageBox.Show("Trial Expired...")
                    My.Settings.ActivatedTrial = False
                    My.Settings.Expired = True

                    ReWriteToFile("ActivatedTrial=", My.Settings.ActivatedTrial.ToString)
                    ReWriteToFile("Expired=", My.Settings.Expired.ToString)

                    ReWriteToRegistry("ActivatedTrial", My.Settings.ActivatedTrial.ToString)
                    ReWriteToRegistry("Expired", My.Settings.Expired.ToString)

                    Me.Close()
                End If
            End If
        End If
    End Sub
  Public Sub ReWriteToRegistry(ByVal Name As String, ByVal Value As String)
        Dim regKey As RegistryKey
        regKey = My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\WomanPro\Backgammon", True).OpenSubKey("Backgammon", True)
        Registry.SetValue("SOFTWARE\WomanPro\Backgammon", Name, Value)
  End Sub
Where am I wrong?
However I looked at registries and under HKEY_LOCAL_MACHINE\Software there isn't WomanPro\Backgammon
 
>looked at registries and under HKEY_LOCAL_MACHINE\Software there isn't WomanPro\Backgammon
Are you quite sue you are actually ever setting the registry values? Are you sure that [tt]myvalue = 1[/tt]. If so, my next question is whether you are targeting 32bit or 64bit for your installer and application. If 32bit, and your platform is 64bit, then the keys are slightly redirected (by Windows, you don't have to do anything). But instead of looking for

[tt]HKEY_LOCAL_MACHINE\SOFTWARE\WomanPro\Backgammon[/tt]

look for

[tt]HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\WomanPro\Backgammon[/tt]

But whether the key exists or not, it shouldn't cause any error trying to read the key (you simply get an empty object back).

But your main app seems to be trying to write to keys in HKEY_LOCAL_MACHINE, and as we have already indicated this requires admin rights. But we don't want to give a backgammon program admin rights ... so maybe the registry isn't the way to go here for you.

(although I'd definitely expect

[tt]regKey = My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\WomanPro\Backgammon", True).OpenSubKey("Backgammon", True)[/tt]

to fail)
 
My machine that I write source code is 64bit, but I am targeting on any machine, that's why I have an apprehension if is a good solution or not.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top