Tuesday, June 3, 2014

ClickOnce inside an MSI

So Recently I needed to create clickonce application inside an MSI and after many attempts, here is the resulting custom action which will publish the application to the location set in the properties.  To use the code you need the following inside your msi..




inside your wxs file you'll also need to create the asset folder which will be removed during install




drop your files into the ClickOnceDeploy Folder above wihtout the .deploy extension



finally you'll need to schedule your custom action...



Some example values for the properties...

FilePath = [WebApiFolder]ClickOnceDeploy
ManifestPath=[WebApiFolder]ClickOnceDeploy\
AppPath=[WebApiFolder]my.Calculator.application
ClickOnceAssetFolder=[ClickOnceAssetFolder]
IconFilePath=calculator.ico
VersionNum=1.2.3
AppDisplayName=My Calculator



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Microsoft.Deployment.WindowsInstaller;

namespace Gazprom.MT.Ops.Deployment
{
    public class ClickOnceActions
    {
        private const string DeployExt = ".deploy";
        private const string ManifestExt = ".manifest";

        [CustomAction]
        public static ActionResult UpdateResignDeploy(Session session)
        {
            session.Log("Begin UpdateRe-SignDeploy");

            var appPath = new FileInfo(session.CustomActionData["AppPath"]);
            var manifestPath = new FileInfo(session.CustomActionData["ManifestPath"]);

            try
            {
                foreach (var data in session.CustomActionData)
                {
                    session.Log("Key: " + data.Key + " Value: " + data.Value);
                }

                session.CustomActionData["AppFileName"] = appPath.Name;

                session.CustomActionData["InstallationUrl"] = session.CustomActionData["Web_Api_Uri"] + session.CustomActionData["AppFileName"];
                session.CustomActionData["ManifestDirectory"] = manifestPath.DirectoryName;
                
                LogPropertyValue(session, "FilePath");
                LogPropertyValue(session, "ManifestPath");
                LogPropertyValue(session, "AppPath");
                LogPropertyValue(session, "AppDisplayName");
                LogPropertyValue(session, "VersionNum");
                LogPropertyValue(session, "AppFileName");
                LogPropertyValue(session, "ManifestDirectory");
                LogPropertyValue(session, "InstallationUrl");
                LogPropertyValue(session, "IconFilePath");
                
                // Manifest
                CreateAppManifest(session);

                AddIconFileToManifestFile(session);

                ApplyDeployExt(session);

                SignAppManifest(session);

                //Application
                CreateApplicationFile(session);

                AddMapFileExtToApplicationFile(session);
               
                SignApplicationFile(session);

                session.Log("New version:  " + session.CustomActionData["VersionNum"]);
                session.Log(".manifest file is available at: " + session.CustomActionData["ManifestPath"]);
                session.Log(".application file is available at:  " + session.CustomActionData["AppPath"]);
            }
            catch (Exception ex)
            {
                const string failedToPublishClickonceApplication = "Failed to Publish ClickOnce Application: ";

                session.Log(failedToPublishClickonceApplication + ex.Message + ex.StackTrace);
                if (appPath.Exists)
                    File.Delete(appPath.FullName);

                if (manifestPath.DirectoryName != null && manifestPath.Exists) 
                    Directory.Delete(manifestPath.DirectoryName, true);

                MessageBox.Show(failedToPublishClickonceApplication + ex.Message, "Publish Application",
                    MessageBoxButton.OK, MessageBoxImage.Error);

                return ActionResult.Failure;
            }

            return ActionResult.Success;
        }

        private static void LogPropertyValue(Session session, string property)
        {
            var param = session.CustomActionData[property];
            session.Log(string.Format("located variable {0} with value {1}", property, param));
        }

        private static void CreateAppManifest(Session session)
        {
            session.Log("Creating Application Manifest with AppName and adding any other files that aren't part of the publish process");

            string args = "-New Application -ToFile \"" + session.CustomActionData["ManifestPath"]
                          + "\" -FromDirectory \"" + session.CustomActionData["FilePath"]
                          + "\" -Name \"" + session.CustomActionData["AppDisplayName"]
                          + "\" -Version " + session.CustomActionData["VersionNum"]
                          + " -Processor x86";

            var output = CallMage(session, args);

            session.Log("Completed Creating Manifest " + output);
        }

        private static void SignAppManifest(Session session)
        {
            session.Log("Signing Manifest");

            string assetFolder = session.CustomActionData["ClickOnceAssetFolder"];

            string args = "-Sign \"" + session.CustomActionData["ManifestPath"] +
                          "\" -CertFile \"" + assetFolder + "CodeCert.pfx\" -Password 1234567890";

            var output = CallMage(session, args);

            session.Log("Completed Signing Manifest " + output);
        }

        private static void SignApplicationFile(Session session)
        {
            session.Log("Signing Application File");

            string assetFolder = session.CustomActionData["ClickOnceAssetFolder"];
            
            string args = "-Sign \"" + session.CustomActionData["AppPath"] +
                          "\" -CertFile \"" + assetFolder + "CodeCert.pfx\" -Password 1234567890";

            var output = CallMage(session, args);

            session.Log("Completed Signing Application File " + output);
        }

        private static string CallMage(Session session, string args)
        {
            string magePath = session.CustomActionData["ClickOnceAssetFolder"];

            session.Log("args:" + args);
            var p = new Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    FileName = magePath + "mage.exe",
                    CreateNoWindow = true,
                    Arguments = args,
                    RedirectStandardOutput = true
                }
            };

            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            if (p.ExitCode != 0)
            {
                string error = "Failed to call mage with Args :" + args + " Exit Code: " + p.ExitCode + " Message: " + output;
                
                throw new ApplicationException(error);
            }

            return output;
        }


        private static void CreateApplicationFile(Session session)
        {
            session.Log("Creating Application File (Deployment Manifest)");

            string args = "-New Deployment -ToFile \"" + session.CustomActionData["AppPath"]
                          + "\" -Name \"" + session.CustomActionData["AppDisplayName"]
                          + "\" -Version " + session.CustomActionData["VersionNum"]
                          + " -AppManifest \"" + session.CustomActionData["ManifestPath"]
                          + "\" -Install true -ProviderURL " + session.CustomActionData["InstallationUrl"] +
                          " -Processor x86";

            var output = CallMage(session, args);

            session.Log("Completed Creating Application File " + output);
        }

        private static void AddIconFileToManifestFile(Session session)
        {
            session.Log("Adding 'asmv2:iconFile' attribute to .manifest file, so the application has the correct icon");

            var fileContents = File.ReadAllText(session.CustomActionData["ManifestPath"]);

            fileContents = fileContents.Replace("<application />", 
                string.Format("<description asmv2:iconFile=\"{0}\" xmlns=\"urn:schemas-microsoft-com:asm.v1\" /> \r\n <application />", session.CustomActionData["IconFilePath"]));

            File.WriteAllText(session.CustomActionData["ManifestPath"], fileContents);
        }

        private static void AddMapFileExtToApplicationFile(Session session)
        {
            session.Log("Adding 'mapFileExtensions' attribute to .application file, so install looks for .deploy extension");

            var fileContents = File.ReadAllText(session.CustomActionData["AppPath"]);

            fileContents = fileContents.Replace("<deployment install=\"true\">",
                "<deployment install=\"true\" mapFileExtensions=\"true\">");

            File.WriteAllText(session.CustomActionData["AppPath"], fileContents);
        }

        private static void ApplyDeployExt(Session session)
        {
            session.Log("Applying .deploy file extension");

            var d = new DirectoryInfo(session.CustomActionData["FilePath"]);
            var infos = d.GetFiles();

            foreach (FileInfo f in infos)
            {
                if (!f.FullName.Contains(ManifestExt))
                    File.Move(f.FullName, f.FullName + DeployExt);
            }

            session.Log("Completed applying .deploy file extension");
        }


    }
}