3
\$\begingroup\$

I've created this function to grab the MSI ProductCode from the MSI file itself. i couldn't find any native method for it. So I've implemented it the following way:

public static string GetMSIProductCode(string msiFile)
{
    string _result = null;
    string productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
    Session product = Installer.OpenPackage(msiFile, true);
    Database msiDB = product.Database;
    View msiView = msiDB.OpenView(productCodeQuery);
    msiView.Execute();
    Record _record = msiView.Fetch();
    _result = _record.GetString(2);
    msiView.Close();
    msiDB.Dispose();
    return _result;
}

Would you do it any different?

Thanks.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  • Almost all objects you work with here are disposable so wrapping them with the using would be a good start.
  • The msiDB variable is not necessary.
  • It is not necessary now to define the result above the query. Variables should be defined as close to their usage as possible.
  • We use the _ usually only for private fields not for local variables.
  • You might consider the implicit type var. It would make your code less verbose.

After applaying this we get:

public static string GetMSIProductCode(string msiFile)
{
    var productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
    using(var product = Installer.OpenPackage(msiFile, true))
    using(var msiView = product.Database.OpenView(productCodeQuery))
    {
        msiView.Execute();
        using (var record = msiView.Fetch())
        {
            return record.GetString(2);
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ t3chb0t, 1. how do you know if an object is disposable? 2. how would you implement the following: Installer.SetInternalUI(InstallUIOptions.Silent) \$\endgroup\$ Commented Oct 5, 2016 at 15:55
  • \$\begingroup\$ @DaveGitenburgh in a database or stream context there are usually a lot of disposable objects. Later it's a gut feeling that something might be disposable. When you work with new types you can either see in the documentation if a class implements the IDisposable interface or just check if it has the .Dispose() method - like I did here because I couldn't find any docs about it :-| \$\endgroup\$
    – t3chb0t
    Commented Oct 5, 2016 at 16:02
  • \$\begingroup\$ @DaveGitenburgh 2. unfortunatelly I don't know an answer to this question. \$\endgroup\$
    – t3chb0t
    Commented Oct 5, 2016 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.