protected override ActionResult OnExecute()
            {
                var database = Session.Database;

                if (!database.Tables.Contains(TableName))
                {
                    return(ActionResult.Success);
                }

                try
                {
                    using (var view = database.OpenView($"SELECT `{KeyNameScope}`, `{KeyNamePath}` FROM `{TableName}`"))
                    {
                        view.Execute();

                        var customActionData = new CustomActionData();
                        foreach (var row in view)
                        {
                            var index = Math.Abs(($"{row[KeyNameScope]}_{row[KeyNamePath]}").GetHashCode());
                            customActionData[PrefixScope + index] = row[KeyNameScope].ToString();
                            customActionData[PrefixPath + index]  = row[KeyNamePath].ToString();
                        }

                        Session["Vita_RegistryKeyCleanerDeferred"] = customActionData.ToString();
                    }
                }
                finally
                {
                    database.Close();
                }
                return(ActionResult.Success);
            }
            protected override ActionResult OnExecute()
            {
                var database = Session.Database;

                if (!database.Tables.Contains(TableName))
                {
                    return(ActionResult.Success);
                }

                try
                {
                    using (var view = database.OpenView($"SELECT `{KeyNameName}`, `{KeyNameStartType}` FROM `{TableName}`"))
                    {
                        view.Execute();

                        var customActionData = new CustomActionData();
                        foreach (var row in view)
                        {
                            customActionData[row[KeyNameName].ToString()] = row[KeyNameStartType].ToString();
                        }

                        Session["Vita_ServiceManagerDeferred"] = customActionData.ToString();
                    }
                }
                finally
                {
                    database.Close();
                }
                return(ActionResult.Success);
            }
Esempio n. 3
0
        public static ActionResult InstallFfmpegPrepare(Session session)
        {
            try
            {
                Record progressRec = new Record(2);
                progressRec[1] = 3;
                progressRec[2] = ticksFfmpegDownload + ticksFfmpegExctract; // ticks
                if (MessageResult.Cancel == session.Message(InstallMessage.Progress, progressRec))
                {
                    return(ActionResult.UserExit);
                }

                CustomActionData _data = new CustomActionData();

                _data["UILevel"]                        = session["UILevel"].Replace(";", ";;");
                _data["TEMPFOLDER"]                     = session["TEMPFOLDER"].Replace(";", ";;");
                _data["AFX_FFMPEGFOLDER"]               = session["AFX_FFMPEGFOLDER"].Replace("; ", ";;");
                _data["InstallFfmpegConnect"]           = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegConnect'")).Replace(";", ";;");
                _data["InstallFfmpegConnect_Template"]  = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegConnect_Template'")).Replace(";", ";;");
                _data["InstallFfmpegDownload"]          = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegDownload'")).Replace(";", ";;");
                _data["InstallFfmpegDownload_Template"] = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegDownload_Template'")).Replace(";", ";;");
                _data["InstallFfmpegExtract"]           = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegExtract'")).Replace(";", ";;");
                _data["InstallFfmpegExtract_Template"]  = ((string)session.Database.ExecuteScalar("SELECT `Text` FROM `UIText` WHERE `Key`='InstallFfmpegExtract_Template'")).Replace(";", ";;");

                session["InstallFfmpegAction"] = _data.ToString();
                return(ActionResult.Success);
            }
            catch (Exception e)
            {
                session.Log("Error: " + e.ToString());
            }

            return(ActionResult.Success);
        }
Esempio n. 4
0
        public static ActionResult GetProperties(Session session)
        {
            Trace.WriteLine("GetProperties : ");


            string[] a = { "WebExchange1_13", "WebExchange1_14" };

            foreach (string s in a)
            {
                string propertyData = session[s];
                Trace.WriteLine("Prop : " + s);

                CustomActionData iniAddLineData = new CustomActionData(propertyData);
                string           section        = iniAddLineData["SECTION"];
                string           key            = iniAddLineData["KEY"];
                string           newValue       = iniAddLineData["VALUE"];
                if (iniAddLineData.ContainsKey("COMMENT"))
                {
                    string comment = iniAddLineData["COMMENT"];
                    Trace.WriteLine("comment : " + comment);
                }

                Trace.WriteLine("Section : " + section);
                Trace.WriteLine("key : " + key);
                Trace.WriteLine("newValue : " + newValue);
            }
            return(ActionResult.Success);
        }
Esempio n. 5
0
        public static ActionResult TrackUninstallationImmediate(Session session)
        {
            Database db = session.Database;

            try
            {
                View view = db.OpenView("SELECT `TrackingId` FROM `GoogleAnalytics`");
                view.Execute();

                CustomActionData data = new CustomActionData();

                var productVersion = db.ExecutePropertyQuery("ProductVersion");
                data["ProductVersion"] = productVersion;

                foreach (Record row in view)
                {
                    data["TrackingId"] = row["TrackingId"].ToString();
                }

                session["TrackUninstallationDeferred"] = data.ToString();

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
            finally
            {
                db.Close();
            }
        }
Esempio n. 6
0
        public static ActionResult TrackInstallationDeferred(Session session)
        {
            try
            {
                CustomActionData data = session.CustomActionData;

                var productVersion = data["ProductVersion"];

                foreach (KeyValuePair <string, string> datum in data)
                {
                    if (datum.Value.ToUpper().StartsWith("UA-"))
                    {
                        try
                        {
                            GoogleAnalyticsApi.TrackEvent(datum.Value, "WixGAExtension", "Install", productVersion);
                        }
                        catch (Exception ex)
                        {
                            session.Log("GoogleAnalytics tracking error: " + ex.Message);
                        }
                    }
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
        }
Esempio n. 7
0
        private static MsiAction ParseMsiAction(CustomActionData data)
        {
            Func <string, bool> parse = (c) => !String.IsNullOrEmpty(c) && bool.Parse(c);

            MsiAction action = MsiAction.None;

            if (parse(data["FirstInstall"]))
            {
                action |= MsiAction.FirstInstall;
            }
            if (parse(data["Upgrading"]))
            {
                action |= MsiAction.Upgrading;
            }
            if (parse(data["RemovingForUpgrade"]))
            {
                action |= MsiAction.RemovingForUpgrade;
            }
            if (parse(data["Uninstalling"]))
            {
                action |= MsiAction.Uninstalling;
            }
            if (parse(data["Maintenance"]))
            {
                action |= MsiAction.Maintenance;
            }

            return(action);
        }
        public static ActionResult ShowMessageImmediate(Session session)
        {
            Database db = session.Database;

            try
            {
                View view = db.OpenView("SELECT `Id`, `Type` FROM `SuperElementTable`");
                view.Execute();

                CustomActionData data = new CustomActionData();

                foreach (Record row in view)
                {
                    data[row["Id"].ToString()] = row["Type"].ToString();
                }

                session["ShowMessageDeferred"] = data.ToString();

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
            finally
            {
                db.Close();
            }
        }
        public static ActionResult CostUninstallFiles(Session session)
        {
            CustomActionData customActionData = new CustomActionData();

            customActionData.Add("INSTALLLOCATION", session["INSTALLLOCATION"]);
            session.DoAction("UninstallFiles", customActionData);
            return(ActionResult.Success);
        }
        public static ActionResult CostDownloadAndExtractZip(Session session)
        {
            CustomActionData customActionData = new CustomActionData();

            customActionData.Add("INSTALLLOCATION", session["INSTALLLOCATION"]);
            customActionData.Add("URL", session["URL"]);
            customActionData.Add("UILEVEL", session["UILevel"]);
            session.DoAction("DownloadAndExtractZip", customActionData);
            return(ActionResult.Success);
        }
        public void CustomActionData()
        {
            string dataString  = "Key1=Value1;Key2=;Key3;Key4=Value=4;Key5";
            string dataString2 = "Key1=;Key2=Value2;Key3;Key4;Key6=Value;;6=6;Key7=Value7";

            CustomActionData data = new CustomActionData(dataString);

            Assert.AreEqual <string>(dataString, data.ToString());

            data["Key1"] = String.Empty;
            data["Key2"] = "Value2";
            data["Key4"] = null;
            data.Remove("Key5");
            data["Key6"] = "Value;6=6";
            data["Key7"] = "Value7";

            Assert.AreEqual <string>(dataString2, data.ToString());

            MyDataClass myData = new MyDataClass();

            myData.Member1 = "test1";
            myData.Member2 = "test2";
            data.AddObject("MyData", myData);

            string           myDataString = data.ToString();
            CustomActionData data2        = new CustomActionData(myDataString);

            MyDataClass myData2 = data2.GetObject <MyDataClass>("MyData");

            Assert.AreEqual <MyDataClass>(myData, myData2);

            List <string> myComplexDataObject = new List <string>();

            myComplexDataObject.Add("CValue1");
            myComplexDataObject.Add("CValue2");
            myComplexDataObject.Add("CValue3");

            CustomActionData myComplexData = new CustomActionData();

            myComplexData.AddObject("MyComplexData", myComplexDataObject);
            myComplexData.AddObject("NestedData", data);
            string myComplexDataString = myComplexData.ToString();

            CustomActionData myComplexData2       = new CustomActionData(myComplexDataString);
            List <string>    myComplexDataObject2 = myComplexData2.GetObject <List <string> >("MyComplexData");

            Assert.AreEqual <int>(myComplexDataObject.Count, myComplexDataObject2.Count);
            for (int i = 0; i < myComplexDataObject.Count; i++)
            {
                Assert.AreEqual <string>(myComplexDataObject[i], myComplexDataObject2[i]);
            }

            data2 = myComplexData2.GetObject <CustomActionData>("NestedData");
            Assert.AreEqual <string>(data.ToString(), data2.ToString());
        }
Esempio n. 12
0
        public static CustomActionData GetCustomActionData(Session session)
        {
            var ret = new CustomActionData();

            ret[PropertyNames.InstallDir]           = session.GetPropertyValue(PropertyNames.InstallDir);
            ret[PropertyNames.Manufacturer]         = session.GetPropertyValue(PropertyNames.Manufacturer);
            ret[PropertyNames.ProductName]          = session.GetPropertyValue(PropertyNames.ProductName);
            ret[PropertyNames.Remove]               = session.GetPropertyValue(PropertyNames.Remove);
            ret[PropertyNames.Patch]                = session.GetPropertyValue(PropertyNames.Patch);
            ret[PropertyNames.OlderVersionDetected] = session.GetPropertyValue(PropertyNames.OlderVersionDetected);
            return(ret);
        }
Esempio n. 13
0
        public static CustomActionData GetCustomActionData(Session session)
        {
            var commponProps = BaseSetupInfo.GetCustomActionData(session);

            var dbProps = new CustomActionData();

            dbProps[DatabaseSetupInfo.AllInfoPropertyName]     = session.GetPropertyValue(DatabaseSetupInfo.AllInfoPropertyName);
            dbProps[DatabaseSetupInfo.FeaturePropertyName]     = session.GetPropertyValue(DatabaseSetupInfo.FeaturePropertyName);
            dbProps[DatabaseSetupInfo.AllFeaturesPropertyName] = session.GetPropertyValue(DatabaseSetupInfo.AllFeaturesPropertyName);
            commponProps.Merge(dbProps);

            return(commponProps);
        }
Esempio n. 14
0
        public void CustomActionData()
        {
            string dataString = "Key1=Value1;Key2=;Key3;Key4=Value=4;Key5";
            string dataString2 = "Key1=;Key2=Value2;Key3;Key4;Key6=Value;;6=6;Key7=Value7";

            CustomActionData data = new CustomActionData(dataString);
            Assert.AreEqual<string>(dataString, data.ToString());

            data["Key1"] = String.Empty;
            data["Key2"] = "Value2";
            data["Key4"] = null;
            data.Remove("Key5");
            data["Key6"] = "Value;6=6";
            data["Key7"] = "Value7";

            Assert.AreEqual<string>(dataString2, data.ToString());

            MyDataClass myData = new MyDataClass();
            myData.Member1 = "test1";
            myData.Member2 = "test2";
            data.AddObject("MyData", myData);

            string myDataString = data.ToString();
            CustomActionData data2 = new CustomActionData(myDataString);

            MyDataClass myData2 = data2.GetObject<MyDataClass>("MyData");
            Assert.AreEqual<MyDataClass>(myData, myData2);

            List<string> myComplexDataObject = new List<string>();
            myComplexDataObject.Add("CValue1");
            myComplexDataObject.Add("CValue2");
            myComplexDataObject.Add("CValue3");

            CustomActionData myComplexData = new CustomActionData();
            myComplexData.AddObject("MyComplexData", myComplexDataObject);
            myComplexData.AddObject("NestedData", data);
            string myComplexDataString = myComplexData.ToString();

            CustomActionData myComplexData2 = new CustomActionData(myComplexDataString);
            List<string> myComplexDataObject2 = myComplexData2.GetObject<List<string>>("MyComplexData");

            Assert.AreEqual<int>(myComplexDataObject.Count, myComplexDataObject2.Count);
            for (int i = 0; i < myComplexDataObject.Count; i++)
            {
                Assert.AreEqual<string>(myComplexDataObject[i], myComplexDataObject2[i]);
            }

            data2 = myComplexData2.GetObject<CustomActionData>("NestedData");
            Assert.AreEqual<string>(data.ToString(), data2.ToString());
        }
Esempio n. 15
0
 public static ActionResult Server(Session session)
 {
     try
     {
         var customActionData = new CustomActionData();
         customActionData.Add(INSTALLFOLDER, session[INSTALLFOLDER]);
         session.DoAction("DeferredServerAction", customActionData);
         return(ActionResult.Success);
     }
     catch (Exception ex)
     {
         session.Log("Exception Occured during custom action details:" + ex.Message);
         return(ActionResult.Failure);
     }
 }
Esempio n. 16
0
        public static ActionResult RegistryAutorun(Session session)
        {
            CustomActionData customActionData = session.CustomActionData;

            string autorunFlag = customActionData["AUTORUN"];
            string path        = customActionData["INSTALLFOLDER"] + "\\T-Rec.exe";

            if (autorunFlag == "1")
            {
                var registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                registryKey.SetValue("T_Rec", path);
                registryKey.Close();
            }

            return(ActionResult.Success);
        }
Esempio n. 17
0
        public static ActionResult SaveDeferredCustomActionData(Session session)
        {
            var customActionData = new CustomActionData
            {
                { "NR_LICENSE_KEY", session["NR_LICENSE_KEY"] },
                { "NETAGENTCOMMONFOLDER", session["NETAGENTCOMMONFOLDER"] },
                { "LOGSFOLDER", session["LOGSFOLDER"] },
                { "NETAGENTFOLDER", session["NETAGENTFOLDER"] },
                { "AppDataExtensionsFolder", session["FrameworkExtensionsFolder"] }
            };

            session.DoAction("MigrateConfiguration", customActionData);
            session.DoAction("SetLicenseKey", customActionData);
            session.DoAction("CleanupPreviousInstall", customActionData);

            return(ActionResult.Success);
        }
Esempio n. 18
0
        public static ActionResult run_before_finish(Session session)
        {
            CustomActionData data = session.CustomActionData;

            string installDir = data["TARGETDIR"];
            string languageID = data["Language"];
            string language   = "English";

            if (languageID == "2052")
            {
                language = "Chinese";
            }

            ChangeLanguage(Path.Combine(installDir, "bin"), language);

            //System.Windows.Forms.MessageBox.Show(codePage);

            return(ActionResult.Success);
        }
        public static ActionResult ShowMessageDeferred(Session session)
        {
            try
            {
                CustomActionData data = session.CustomActionData;

                foreach (KeyValuePair <string, string> datum in data)
                {
                    DisplayWarningMessage(session, string.Format("{0} => {1}", datum.Key, datum.Value));
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
        }
Esempio n. 20
0
        public static ActionResult UninstallFfmpegPrepare(Session session)
        {
            try
            {
                CustomActionData _data = new CustomActionData();

                _data["UILevel"]          = session["UILevel"].Replace(";", ";;");
                _data["AFX_FFMPEGFOLDER"] = session["AFX_FFMPEGFOLDER"].Replace("; ", ";;");

                session["RollbackFfmpegAction"]  = _data.ToString();
                session["UninstallFfmpegAction"] = _data.ToString();
                return(ActionResult.Success);
            }
            catch (Exception e)
            {
                session.Log("Error: " + e.ToString());
            }

            return(ActionResult.Success);
        }
Esempio n. 21
0
        public static ActionResult CADefferedProperties(Session session)
        {
            //System.Diagnostics.Debugger.Launch();

            session.Log("CADefferedProperties: start");

            //create custom action data from immidated session properties
            CustomActionData data = new CustomActionData();

            data["INSTALLDIR"] = session["INSTALLDIR"];
            data["TARGETDIR"]  = session["LAPINSTALLDIR"];
            data["Language"]   = session["Language"];

            //Store custom action data for each deffered CAs
            session[CAConstants.RunBeforeModify]    = data.ToString();
            session[CAConstants.RunBeforeFinish]    = data.ToString();
            session[CAConstants.RunBeforeUninstall] = data.ToString();

            session.Log("CADefferedProperties: Complete");
            return(ActionResult.Success);
        }
Esempio n. 22
0
        public static ActionResult MyDeferredCustomAction(Session session)
        {
            // This logging is visible in MsiExec log file
            session.Log("Begin MyDeferredCustomAction");

            // In deferred custom action, WiX property values can only be accessed through CustomActionData
            // Accessing property value using session indexer throws exception
            CustomActionData customActionData = session.CustomActionData;

            string message =
                $"customActionData = '{customActionData}'{Environment.NewLine}{Environment.NewLine}" +
                $"customActionData[\"MY_PROPERTY\"] = '{customActionData["MY_PROPERTY"]}'{Environment.NewLine}{Environment.NewLine}" +
                $"session[\"MY_PROPERTY\"] -> throws InstallerException{Environment.NewLine}" +
                "'Cannot access session details from a non-immediate custom action'";

            // System.Diagnostics.Debugger.Launch();
            MessageBox.Show(message, "Deferred mode custom action", MessageBoxButtons.OK, MessageBoxIcon.Information);

            session.Log($"MY_PROPERTY value in MyDeferredCustomAction = {customActionData["MY_PROPERTY"]}");
            session.Log($"MY_INSTALL_LOCATION value in MyDeferredCustomAction = {customActionData["MY_INSTALL_LOCATION"]}");
            session.Log("End MyDeferredCustomAction");

            return(ActionResult.Success);
        }
Esempio n. 23
0
        public static ActionResult MyImmediateCustomAction(Session session)
        {
            // This logging is visible in MsiExec log file
            session.Log("Begin MyImmediateCustomAction");

            // In immediate custom action, WiX property values can be accessed directly (using session indexer)
            // CustomActionData.ToString() is empty and accessing a property using CustomActionData indexer throws exception
            CustomActionData customActionData = session.CustomActionData;

            string message =
                $"customActionData = '{customActionData}'{Environment.NewLine}{Environment.NewLine}" +
                $"customActionData[\"MY_PROPERTY\"] -> throws KeyNotFoundException{Environment.NewLine}" +
                $"'The given key was not present in the dictionary.'{Environment.NewLine}{Environment.NewLine}" +
                $"session[\"MY_PROPERTY\"] = '{session["MY_PROPERTY"]}'";

            // System.Diagnostics.Debugger.Launch();
            MessageBox.Show(message, "Immediate mode custom action", MessageBoxButtons.OK, MessageBoxIcon.Information);

            session.Log($"MY_PROPERTY value in MyImmediateCustomAction = {session["MY_PROPERTY"]}");
            session.Log($"MY_INSTALL_LOCATION value in MyImmediateCustomAction = {session["MY_INSTALL_LOCATION"]}");
            session.Log("End MyImmediateCustomAction");

            return(ActionResult.Success);
        }
Esempio n. 24
0
        public static ActionResult UpdateAddonPath(Session session)
        {
            session.Log("Begin UpdateAddonPath");
            CustomActionData data         = session.CustomActionData;
            string           templatePath = data["TEMPLATE"];

            if (templatePath == null)
            {
                session.Log("missing parameter 'VSTO'");
                return(ActionResult.Failure);
            }
            session.Log("using template: " + templatePath);

            String vstoFilePath = data["VSTO"];

            if (vstoFilePath == null)
            {
                session.Log("missing parameter dest");
                return(ActionResult.Failure);
            }
            session.Log("using vsto file: " + vstoFilePath);
            using (FileStream templateStream = new FileStream(templatePath, FileMode.Open, FileAccess.ReadWrite))
            {
                using (ZipArchive templateZip = new ZipArchive(templateStream, ZipArchiveMode.Update))
                {
                    session.Log("loading document from zip");
                    XmlDocument doc = loadCustomXml(templateZip);
                    session.Log("updating assembly path");
                    updateAssemblyPath(session, doc, vstoFilePath);
                    String updatedDoc = doc.OuterXml;
                    session.Log("replacing custom.xml");
                    replaceCustomFile(templateZip, updatedDoc);
                }
            }
            return(ActionResult.Success);
        }
 /// <summary>
 ///     Set the CustomActionData collection element: <paramref name="data" />,
 ///     Using the value of the session property: session[propertyName].
 /// </summary>
 /// <param name="session">Windows Installer Session.</param>
 /// <param name="propertyName">Property Name </param>
 /// <param name="data">Collection properties.</param>
 private static void SetCustomActionData(Session session, string propertyName, CustomActionData data)
 {
     if (data.ContainsKey(propertyName))
         data[propertyName] = session[propertyName];
     else
         data.Add(propertyName, session[propertyName]);
 }
Esempio n. 26
0
        private static ActionResult GetScriptsFromMsiDatabase(Session session, int elevated, string XmlDataProperty, string installAction)
        {
            Database db = session.Database;

            if (!db.Tables.Contains("PowerShellScripts"))
            {
                return(ActionResult.Success);
            }

            try
            {
                CustomActionData data;
                using (View view = db.OpenView(string.Format("SELECT `Id`, `Script` FROM `PowerShellScripts` WHERE `Elevated` = {0}", elevated)))
                {
                    view.Execute();

                    data = new CustomActionData();

                    Record row = view.Fetch();

                    while (row != null)
                    {
                        string script = Encoding.Unicode.GetString(Convert.FromBase64String(row["Script"].ToString()));
                        script = session.Format(script);
                        script = Convert.ToBase64String(Encoding.Unicode.GetBytes(script));

                        data.Add(row["Id"].ToString(), script);
                        session.Log("Adding {0} to CustomActionData", row["Id"]);

                        row = view.Fetch();
                    }
                }

                session[XmlDataProperty] = data.ToString();

                // Tell the installer to increase the value of the final total
                // length of the progress bar by the total number of ticks in
                // the custom action.
                MessageResult iResult;
                using (var hProgressRec = new Record(2))
                {
                    hProgressRec[1] = 3;
                    hProgressRec[2] = TotalTicks;
                    iResult         = session.Message(InstallMessage.Progress, hProgressRec);
                }

                if (iResult == MessageResult.Cancel)
                {
                    return(ActionResult.UserExit);
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.ToString());
                return(ActionResult.Failure);
            }
            finally
            {
                db.Close();
            }
        }
        private void AddingExisting()
        {
            // Для существующего добавления, информацию по базе данных получаем из списка существующих баз.
              WixComboBox combo = new WixComboBox(Session, sessionProp.ExistControlProperty);
              string value = combo.SelectedValue;
              if (value != "")
              {
            CustomActionData customActionData = new CustomActionData(value);
            DatabaseInfo info = customActionData.GetObject<DatabaseInfo>(typeof(DatabaseInfo).ToString());
            // Затем данную позицию удаляем из списка сущестующих баз.
            combo.RemoveItem(combo.SelectedValue);

            // Значение по умолчанию.
            combo.SelectedValue = combo.Items.Count > 0 ? combo.Items[0].Value : "";

            // Полученную информацию добавляем в сессию.
            Session.GetService<ISessionDatabaseInfoExtension>().AddDatabaseInfo(info);
              }
        }
        public static ActionResult SwhowPathInstall(Session session)
        {
            try
            {
                //  Active message only for debugging developing
                //  MessageBox.Show("SwhowPathInstall: For debugging , the Debug menu, ' Attach to process ' ate processes : msiexec.exe y rundll32.exe.",
                //    "Depurar: SwhowPathInstall", MessageBoxButtons.OK, MessageBoxIcon.Information);

                bool isCustomActionData = false;
                List<DataBasePathTO> listPaths;
                List<FeatureInstallTO> listFeactureScripts;
                var listFeactureNames = new List<string>();

                InstallUtilities.WriteLogInstall(session, "Initialised SwhowPathInstall ...", null, true);
                if (session == null)
                {
                    throw new ArgumentNullException("session");
                }

                // Setup Routes taken from CustomTable Id = " TABLE_DATABASE_PATHS " and set default route
                listPaths = GetCustomTableDataBasePaths(session, isCustomActionData);

                // Open the user form to change installation paths database .
                var frmA = new frmPaths(listPaths);
                if (frmA.ShowDialog() != DialogResult.OK)
                {
                    throw new InstallerException("Configuración de rutas de instalación no realizada");
                }

                // / Prepare CustomActionData for deferred CustomAction 
                var data = new CustomActionData();

                // Update CustomTable Id = " TABLE_DATABASE_PATHS " with modified routes
                // UpdateCustomTableDataBasePaths (session , listPaths , isCustomActionData );

                // Prepare list of paths to be sent to CustomActionData for deferred CustomAction
                data.AddObject("DATABASE_PATHS", listPaths);

                // Add the route list as a session property
                // Data.Add ( " DATABASE_PATHS " JsonConvert.SerializeObject ( listPaths ) ) ;

                // To retrieve the serialized property
                // List <DataBasePathTO> JsonConvert.DeserializeObject listPaths = < List <DataBasePathTO> > ( session.CustomActionData [" DATABASE_PATHS "] );

                // Prepare properties to be sent to CustomActionData for deferred CustomAction
                SetCustomActionData(session, "INSTALLLOCATION", data);
                SetCustomActionData(session, "DATABASE_SERVERNAME", data);
                SetCustomActionData(session, "DATABASE_NAME", data);
                SetCustomActionData(session, "DATABASE_WINDOWSAUTHENTICATION", data);
                SetCustomActionData(session, "DATABASE_AUTHENTICATEDATABASE", data);
                SetCustomActionData(session, "DATABASE_EXECUTESCRIPTS", data);
                SetCustomActionData(session, "DATABASE_USERNAME", data);
                SetCustomActionData(session, "DATABASE_PASSWORD", data);
                SetCustomActionData(session, "DATABASE_PROXYPASSWORD", data);
                SetCustomActionData(session, "DATABASE_MAILPROFILENAME", data);
                SetCustomActionData(session, "DATABASE_MAILBOX", data);
                SetCustomActionData(session, "DATABASE_MAILIP", data);
                SetCustomActionData(session, "DATABASE_OPERATORNAMENAME", data);
                SetCustomActionData(session, "DATABASE_OPERATORMAILBOX", data);
                SetCustomActionData(session, "DATABASE_PROXYWINDOWSUSER", data);

                // / Database Scripts to be installed, taken from the MSI  Feature using sql files * .
                foreach (FeatureInfo fi in session.Features)
                {
                    if (fi.RequestState == InstallState.Local || fi.RequestState == InstallState.Source ||
                        fi.RequestState == InstallState.Default)
                    {
                        listFeactureNames.Add(fi.Name);
                        InstallUtilities.WriteLogInstall(session,
                            "FEATURE fi.Name: " + fi.Name + ", fi.CurrentState: " + fi.CurrentState +
                            ", fi.RequestState:" + fi.RequestState, null, false);
                    }
                }
                listFeactureScripts = GetFeatureScriptDataBase(session, listFeactureNames);
                data.AddObject("DATABASE_FEACTURESCRIPTS", listFeactureScripts);

                // Add all the properties in a single variable
                //session["CUSTOMACTIONDATA_PROPERTIES"] = data.ToString();

                // Schedule deferred actions 
                session.DoAction("CA_DataBaseExecuteScripts", data);

                return ActionResult.Success;
            }
            catch (Exception ex)
            {
                InstallUtilities.WriteLogInstall(session,
                    "Exception to establish installation paths for database.", ex, true);
                return ActionResult.Failure;
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Adds distinct Zentity users to the collection.
        /// </summary>
        /// <param name="customActionData">The installer CustomActionData</param>
        /// <returns>Distinct Zentity users</returns>
        private static IEnumerable <KeyValuePair <string, string> > GetUserCredentials(CustomActionData customActionData)
        {
            Dictionary <string, string> credentials = new Dictionary <string, string>();

            credentials.Add(customActionData["appPoolUser"], customActionData["appPoolUserPassword"]);

            if (!credentials.Keys.Contains(customActionData["pivotUser"]))
            {
                credentials.Add(customActionData["pivotUser"], customActionData["pivotUserPassword"]);
            }

            if (!credentials.Keys.Contains(customActionData["notificationUser"]))
            {
                credentials.Add(customActionData["notificationUser"], customActionData["notificationUserPassword"]);
            }

            return(credentials.Distinct());
        }
        private static ActionResult FilesImmediate(Session session, int elevated, string deferredProperty)
        {
            Database db = session.Database;

            const string tableName = "PowerShellFiles";

            if (!db.Tables.Contains(tableName))
            {
                return(ActionResult.Success);
            }

            try
            {
                XDocument doc;
                using (View view = db.OpenView(string.Format("SELECT `Id`, `File`, `Arguments`, `IgnoreErrors`, `Condition` FROM `{0}` WHERE `Elevated` = {1} ORDER BY `Order`", tableName, elevated)))
                {
                    view.Execute();

                    doc = new XDocument(new XDeclaration("1.0", "utf-16", "yes"), new XElement("r"));

                    foreach (Record row in view)
                    {
                        string condition = row["Condition"]?.ToString();
                        if (!string.IsNullOrEmpty(condition) && !session.EvaluateCondition(condition))
                        {
                            session.Log($"Condition evaluated to false. Skip PS file {row["Id"]?.ToString()}");
                            continue;
                        }

                        var args         = session.Format(row["Arguments"].ToString());
                        var IgnoreErrors = session.Format(row["IgnoreErrors"].ToString());

                        session.Log("args '{0}'", args);

                        doc.Root.Add(new XElement("d", new XAttribute("Id", row["Id"]),
                                                  new XAttribute("file", session.Format(row["File"].ToString())), new XAttribute("args", args), new XAttribute("IgnoreErrors", IgnoreErrors)));
                    }
                }

                var cad = new CustomActionData {
                    { "xml", doc.ToString() }
                };

                session[deferredProperty] = cad.ToString();

                // Tell the installer to increase the value of the final total
                // length of the progress bar by the total number of ticks in
                // the custom action.
                MessageResult iResult;
                using (var hProgressRec = new Record(2))
                {
                    hProgressRec[1] = 3;
                    hProgressRec[2] = TotalTicks;
                    iResult         = session.Message(InstallMessage.Progress, hProgressRec);
                }

                if (iResult == MessageResult.Cancel)
                {
                    return(ActionResult.UserExit);
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
            finally
            {
                db.Close();
            }
        }
        private void Deleting()
        {
            string server;
              string database;
              // Получаем имена сервера и базы данных.
              NameViewConverter.ParseNameView(sessionProp.SelectedDatabase, out server, out database);

              // Получаем информацию об этой базе.
              DatabaseInfo info = Session.GetService<ISessionDatabaseInfoExtension>().GetDatabaseInfos().FirstOrDefault(v => v.Server == server && v.Name == database);

              // Если база данных существовала (т.е. не добавлена пользователем),
              // то запомним ее в специальном списке существующих баз данных (в элементе управления).
              // Так как это структура, то если ничего не будет найдено в запросе LINQ, поле Server не будет проинициализирован.
              if (!string.IsNullOrEmpty(info.Server) && !info.IsNew)
              {
            // Для вывода элемента будем использовать имя, версию и признак поддержки.
            // Для значения сохраним, в виде строки, сериализованный DatabaseInfo в CustomActionData.
            WixComboBox combo = new WixComboBox(Session, sessionProp.ExistControlProperty);
            // Здесь аккуратнее, так как ComboBox не отображает некоторые символы.
            string displayedName = sessionProp.SelectedDatabase + " " + info.Version + (info.IsRequiringUpdate ? "" : " (не поддерживается)");
            CustomActionData customActionData = new CustomActionData();
            customActionData.AddObject<DatabaseInfo>(typeof(DatabaseInfo).ToString(), info);
            combo.AddItem(new WixComboItem(displayedName, customActionData.ToString()));

            // Значение по умолчанию.
            combo.SelectedValue = combo.Items.Count > 0 ? combo.Items[0].Value : "";
              }

              Session.GetService<ISessionDatabaseInfoExtension>().DeleteDatabaseInfo(server, database);
        }
Esempio n. 32
0
        public static ActionResult JsonFileAppsettings(Session session)
        {
            try
            {
                if (session == null) { throw new ArgumentNullException("session"); }

                CustomActionData data = null;

                if(session["INSTALLATIONMODE"] == "virtualdirectory")
                    data = new CustomActionData(session["JsonFileAppsettingsVirtualDirectory"]);
                else
                    data = new CustomActionData(session["JsonFileAppsettingsWebsite"]);

                string file = data.ContainsKey("File") ? data["File"] : "";
                string rootKey = data.ContainsKey("RootKey") ? data["RootKey"] : "";
                string key = data.ContainsKey("Key") ? data["Key"] : "";
                string value = data.ContainsKey("Value") ? data["Value"] : "";
                if (value.IndexOf("[") > -1 && value.IndexOf("]") > -1)
                    value = session.Format(data["Value"]);

                var dir = session["INSTALLDIR"];
                if (dir == null)
                    return ActionResult.Success;

                file = Path.Combine(dir, file);
                if ( !File.Exists(file))
                    return ActionResult.Success;

                ReplaceInJsonFile(file, rootKey, key, value);

                return ActionResult.Success;
            }
            catch (Exception e)
            {
                if (session != null)
                    session.Log("Custom Action Exception " + e);
            }

            return ActionResult.Failure;
        }
        void Check(IActionWorker worker, bool serverMode, bool clientMode)
        {
            CustomActionData customActionData = new CustomActionData();
              Microsoft.Deployment.WindowsInstaller.Fakes.ShimSession.AllInstances.CustomActionDataGet = delegate { return customActionData; };

              // Проверка режима сервера.
              SetValue(worker, false);
              customActionData.AddObject<UIType>(SessionUITypeGetterExtension.keyUIType, UIType.Server);
              worker.Execute();
              Assert.AreEqual(serverMode, GetValue(worker), worker.GetType().ToString() + " Server");

              // Проверка режима клиента.
              SetValue(worker, false);
              customActionData.Clear();
              customActionData.AddObject<UIType>(SessionUITypeGetterExtension.keyUIType, UIType.Client);
              worker.Execute();
              Assert.AreEqual(clientMode, GetValue(worker), worker.GetType().ToString() + " Client");
        }
Esempio n. 34
0
        /// <summary>
        /// Executes a built-in action, custom action, or user-interface wizard action.
        /// </summary>
        /// <param name="action">Name of the action to execute.  Case-sensitive.</param>
        /// <param name="actionData">Optional data to be passed to a deferred custom action.</param>
        /// <exception cref="InvalidHandleException">the Session handle is invalid</exception>
        /// <exception cref="InstallCanceledException">the user exited the installation</exception>
        /// <remarks><p>
        /// The DoAction method executes the action that corresponds to the name supplied. If the
        /// name is not recognized by the installer as a built-in action or as a custom action in
        /// the CustomAction table, the name is passed to the user-interface handler object, which
        /// can invoke a function or a dialog box. If a null action name is supplied, the installer
        /// uses the upper-case value of the ACTION property as the action to perform. If no property
        /// value is defined, the default action is performed, defined as "INSTALL".
        /// </p><p>
        /// Actions that update the system, such as the InstallFiles and WriteRegistryValues
        /// actions, cannot be run by calling MsiDoAction. The exception to this rule is if DoAction
        /// is called from a custom action that is scheduled in the InstallExecuteSequence table
        /// between the InstallInitialize and InstallFinalize actions. Actions that do not update the
        /// system, such as AppSearch or CostInitialize, can be called.
        /// </p><p>
        /// If the called action is a deferred, rollback, or commit custom action, then the supplied
        /// <paramref name="actionData"/> will be available via the <see cref="CustomActionData"/>
        /// property of that custom action's session.
        /// </p><p>
        /// Win32 MSI API:
        /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidoaction.asp">MsiDoAction</a>
        /// </p></remarks>
        internal void DoAction(string action, CustomActionData actionData)
        {
            if (String.IsNullOrEmpty(action))
            {
                throw new ArgumentNullException("action");
            }

            this.ValidateSessionAccess();

            if (actionData != null)
            {
                this[action] = actionData.ToString();
            }

            uint ret = RemotableNativeMethods.MsiDoAction((int) this.Handle, action);
            if (ret != 0)
            {
                throw InstallerException.ExceptionFromReturnCode(ret);
            }
        }
Esempio n. 35
0
 public static ActionResult Server(Session session)
 {
     try
     {
         var customActionData = new CustomActionData();
         customActionData.Add(INSTALLFOLDER, session[INSTALLFOLDER]);
         session.DoAction("DeferredServerAction", customActionData);
         return ActionResult.Success;
     }
     catch (Exception ex)
     {
         session.Log("Exception Occured during custom action details:" + ex.Message);
         return ActionResult.Failure;
     }
 }
Esempio n. 36
0
        private static ActionResult ExecuteScriptsFromXmlDataProperty(Session session, string XmlDataProperty, string installAction)
        {
            MessageResult iResult;

            using (var hActionRec = new Record(3))
            {
                hActionRec[1] = XmlDataProperty;
                hActionRec[2] = "Setup Scripts";
                hActionRec[3] = "[1] of [2], [3]";
                iResult       = session.Message(InstallMessage.ActionStart, hActionRec);
            }

            if (iResult == MessageResult.Cancel)
            {
                return(ActionResult.UserExit);
            }

            // Tell the installer to use explicit progress messages.
            using (var hProgressRec = new Record(3))
            {
                hProgressRec[1] = 1;
                hProgressRec[2] = 1;
                hProgressRec[3] = 0;
                iResult         = session.Message(InstallMessage.Progress, hProgressRec);
            }

            if (iResult == MessageResult.Cancel)
            {
                return(ActionResult.UserExit);
            }

            try
            {
                CustomActionData data = session.CustomActionData;

                foreach (var datum in data)
                {
                    string script = Encoding.Unicode.GetString(Convert.FromBase64String(datum.Value));
                    session.Log("Executing PowerShell script:\n{0}", script);

                    using (var task = new PowerShellTask(script, session))
                    {
                        var result = task.Execute();
                        session.Log("PowerShell non-terminating errors: {0}", !result);

                        if (!result)
                        {
                            session.Log("Returning Failure");

                            return(ActionResult.Failure);
                        }
                    }
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log("PowerShell terminating error, returning Failure");
                session.Log(ex.ToString());
                return(ActionResult.Failure);
            }
        }
Esempio n. 37
0
 private static void SetCustomActionData(Session session, string propertyName, CustomActionData data)
 {
     if (data.ContainsKey(propertyName))
     {
         data[propertyName] = session[propertyName];
     }
     else
     {
         data.Add(propertyName, session[propertyName]);
     }
 }
Esempio n. 38
0
        private static ActionResult GetScriptFilesFromMsiDatabase(Session session, int elevated, string XmlDataProperty, string installAction)
        {
            Database db = session.Database;

            const string tableName = "PowerShellFiles";

            if (!db.Tables.Contains(tableName))
            {
                return(ActionResult.Success);
            }

            try
            {
                XDocument doc;
                using (View view = db.OpenView(string.Format("SELECT `Id`, `File`, `Arguments`, `IgnoreErrors`, `InstallAction` FROM `{0}` WHERE `Elevated` = {1}", tableName, elevated)))
                {
                    view.Execute();

                    doc = new XDocument(new XDeclaration("1.0", "utf-16", "yes"), new XElement("r"));

                    foreach (Record row in view)
                    {
                        var args         = session.Format(row["Arguments"].ToString());
                        var instAction   = session.Format(row["InstallAction"].ToString());
                        var IgnoreErrors = session.Format(row["IgnoreErrors"].ToString());

                        session.Log("args '{0}'", args);
                        session.Log("InstallAction '{0}'", installAction);
                        session.Log("InstallAction in file '{0}'", instAction);

                        if (instAction == installAction)
                        {
                            session.Log("Adding InstallAction in file '{0}'", instAction);

                            doc.Root.Add(new XElement("d",
                                                      new XAttribute("Id", row["Id"]),
                                                      new XAttribute("file", session.Format(row["File"].ToString())),
                                                      new XAttribute("args", args),
                                                      new XAttribute("IgnoreErrors", IgnoreErrors),
                                                      new XAttribute("InstallAction", instAction)));
                        }
                    }
                }

                var cad = new CustomActionData {
                    { "xml", doc.ToString() }
                };

                session[XmlDataProperty] = cad.ToString();

                // Tell the installer to increase the value of the final total
                // length of the progress bar by the total number of ticks in
                // the custom action.
                MessageResult iResult;
                using (var hProgressRec = new Record(2))
                {
                    hProgressRec[1] = 3;
                    hProgressRec[2] = TotalTicks;
                    iResult         = session.Message(InstallMessage.Progress, hProgressRec);
                }

                if (iResult == MessageResult.Cancel)
                {
                    return(ActionResult.UserExit);
                }

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
                return(ActionResult.Failure);
            }
            finally
            {
                db.Close();
            }
        }
Esempio n. 39
0
        public static ActionResult SwhowPathInstall(Session session)
        {
            try
            {
                bool isCustomActionData = false;
                List <DataBasePathTO>    listPaths;
                List <FeactureInstallTO> listFeactureScripts;
                List <string>            listFeactureNames = new List <string>();

                InstallUtilities.WriteLogInstall(session, "Starting SwhowPathInstall ...", null, true);
                if (session == null)
                {
                    throw new ArgumentNullException("session");
                }

                listPaths = GetCustomTableDataBasePaths(session, isCustomActionData);

                CustomActionData data = new CustomActionData();

                data.AddObject <List <DataBasePathTO> >("DATABASE_PATHS", listPaths);

                SetCustomActionData(session, "INSTALLLOCATION", data);
                SetCustomActionData(session, "DATABASE_SERVERNAME", data);
                SetCustomActionData(session, "DATABASE_NAME", data);
                SetCustomActionData(session, "DATABASE_WINDOWSAUTHENTICATION", data);
                SetCustomActionData(session, "DATABASE_AUTHENTICATEDATABASE", data);
                SetCustomActionData(session, "DATABASE_EXECUTESCRIPTS", data);
                SetCustomActionData(session, "DATABASE_USERNAME", data);
                SetCustomActionData(session, "DATABASE_PASSWORD", data);

                //SetCustomActionData(session, "DATABASE_PROXYPASSWORD", data);
                //SetCustomActionData(session, "DATABASE_MAILPROFILENAME", data);
                //SetCustomActionData(session, "DATABASE_MAILBOX", data);
                //SetCustomActionData(session, "DATABASE_MAILIP", data);
                //SetCustomActionData(session, "DATABASE_OPERATORNAMENAME", data);
                //SetCustomActionData(session, "DATABASE_OPERATORMAILBOX", data);
                //SetCustomActionData(session, "DATABASE_PROXYWINDOWSUSER", data);

                foreach (FeatureInfo fi in session.Features)
                {
                    if (fi.RequestState == InstallState.Local || fi.RequestState == InstallState.Source || fi.RequestState == InstallState.Default)
                    {
                        listFeactureNames.Add(fi.Name);
                        InstallUtilities.WriteLogInstall(session, "FEATURE fi.Name: " + fi.Name + ", fi.CurrentState: " + fi.CurrentState +
                                                         ", fi.RequestState:" + fi.RequestState, null, false);
                    }
                }
                listFeactureScripts = GetFeactureScriptDataBase(session, listFeactureNames);
                data.AddObject <List <FeactureInstallTO> >("DATABASE_FEACTURESCRIPTS", listFeactureScripts);

                //session["CUSTOMACTIONDATA_PROPERTIES"] = data.ToString();

                session.DoAction("CA_DataBaseExecuteScripts", data);

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                InstallUtilities.WriteLogInstall(session, "Exception to establish routes database installation", ex, true);
                return(ActionResult.Failure);
            }
        }