[r7]: / trunk / cforge / cforge / Helper.cs  Maximize  Restore  History

Download this file

309 lines (246 with data), 10.4 kB

  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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
using IronPython.Hosting;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace cforge
{
    /// <summary>
    /// Misc helper classes for all kinds of stuff
    /// </summary>
    class Helper
    {
        
        #region Registry


        /// <summary>
        /// Function to check if URL Handler for cforge tool is installed
        /// </summary>
        /// <returns>true, if yes. false, if not</returns>
        public static bool CheckRegistryProtocol()
        {
            RegistryKey cforge = Registry.ClassesRoot.OpenSubKey("cforge");
            if (cforge == null)
            {
                return false;

            }
            return true;
        }


        public static void RegisterProtocol(bool bVerbose)
        {
            try
            {
                String fullpath = GetCFORGEAssemblyPath();

                RegistryKey cforgekey = Registry.ClassesRoot.OpenSubKey("cforge");

                cforgekey = Registry.ClassesRoot.CreateSubKey("cforge", true);
                cforgekey.SetValue("", "URL:cforge Protocol");
                cforgekey.SetValue("URL Protocol", "");

                RegistryKey cforgeshell = cforgekey.CreateSubKey("shell");
                RegistryKey shellopen = cforgeshell.CreateSubKey("open");
                RegistryKey opencommand = shellopen.CreateSubKey("command");
                opencommand.SetValue("", "\"" + fullpath + "\" \"%1\"");

                Console.WriteLine("[INFO] Installed URL Handler for cforge tool. \r\n\tPath is: " + fullpath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception while adding the registry key. Perhaps you are not admin?");
                Console.WriteLine(ex.ToString());
            }
        }

        internal static void ShowLicenseInfo()
        {
            Console.WriteLine("License information ");
            Console.WriteLine("");
            Console.Write(Resources.license);
            Console.WriteLine("");
        }

        #endregion

        #region SystemPath

        public static void AddToSystemPath(bool bVerbose)
        {
            
            string strPath = System.Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
            string[] split = strPath.Split(new Char[] { ';' });

            String path = Path.GetDirectoryName(GetCFORGEAssemblyPath());
            String strNewSystemPath = strPath + ";" + path;

            if (!split.Contains(path))
            {
                System.Environment.SetEnvironmentVariable("Path", strNewSystemPath, EnvironmentVariableTarget.Machine);
            }

        }

        #endregion


        /// <summary>
        /// Function to retrieve the location of the currenty assembly (cforge.exe).
        /// This should be located in the CODESYS installation subfolder "CFORGE"
        /// </summary>
        /// <returns>full path to cforge.exe</returns>
        private static String GetCFORGEAssemblyPath()
        {
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            return path;
        }

        private static bool IsCODESYSPathInstallation()
        {
            String path = GetCFORGEAssemblyPath();
            if (path.Contains("bin") && (path.Contains("Debug") || path.Contains("Release")))
                return false;

            return true;
        }

        /// <summary>
        /// Function to retrieve the CODESYS AP_ROOT (this is where "Common" etc. folders are)
        /// </summary>
        /// <returns>full path to AP ROOT</returns>
        private static String GetCODESYSRoot()
        {
            if (IsCODESYSPathInstallation())
            {
                // twice up from cforge.exe (if installed in CODESYS)
                String path = GetCFORGEAssemblyPath();
                path = Directory.GetParent(path).FullName;
                return Directory.GetParent(path).FullName;
            }
            // for now return a normal installation path for CODESYS
            return @"C:\Program Files (x86)\3S CODESYS\CODESYS\";
        }


        /// <summary>
        /// Function to retrieve the CFORGE Script path (this is where the IronPython scripts should reside)
        /// </summary>
        /// <returns>full path to CFORGE Scripts</returns>
        private static String GetCFORGEScriptPath()
        {
            if (IsCODESYSPathInstallation())
            {
                // <AP_ROOT>\CFORGE\Scripts
                String path = GetCODESYSRoot();
                return Path.Combine(path, "CFORGE", "Scripts");
            }
            String localscriptpath = System.AppDomain.CurrentDomain.BaseDirectory;
            localscriptpath = Directory.GetParent(localscriptpath).FullName;
            localscriptpath = Directory.GetParent(localscriptpath).FullName;
            localscriptpath = Directory.GetParent(localscriptpath).FullName;
            return Path.Combine(localscriptpath,"Package", "CFORGE", "Scripts");
        }

       

        /// <summary>
        /// Function to enumerate all IronPython scripts to exend cforge.exe inside Scripts folder
        /// </summary>
        /// <returns>List of IPY scripts</returns>
        public static List<String> GetAllScripts()
        {
            List<string> liScripts = new List<string>();

            try
            {
                String path = GetCFORGEScriptPath();
                foreach (String file in Directory.EnumerateFiles(path))
                {
                    if (Path.GetExtension(file).ToLowerInvariant() == ".py")
                    {
                        String shortfilename = Path.GetFileNameWithoutExtension(file);
                        liScripts.Add(shortfilename);
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("[EXCEPTION] GetAllScripts: " + e.Message);
            }

            return liScripts;
        }

        public static bool IsUserElevated()
        {
            using (var curIdent = WindowsIdentity.GetCurrent())
            {
                var principal = new WindowsPrincipal(curIdent);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
        }

        public static void RunElevated(String args)
        {
            String strAssemblyPath = GetCFORGEAssemblyPath();

            try
            {
                Process p = new Process();
                p.StartInfo.FileName = strAssemblyPath;
                p.StartInfo.Arguments = args;
                p.StartInfo.Verb = "runas";

                p.Start();

                p.WaitForExit();
            }
            catch(Exception ex)
            {
                Console.WriteLine("[EXCEPTION] RunElevated: " + ex.Message);
            }
        }

        #region Scripting


        public static void ExecuteIPyScript(String command, String[] args, bool bVerbose)
        {
            String scriptfile = Path.Combine(GetCFORGEScriptPath(), command + ".py");
            Console.WriteLine();
            Console.WriteLine("[INFO] Executing: " + scriptfile);
            Console.WriteLine();

            if (!File.Exists(scriptfile))
            {
                Console.WriteLine();
                Console.WriteLine("[ERROR] Cannot execute command: no such file or directory: " + scriptfile);
                Console.WriteLine();

                return;
            }

            //ScriptEngine engine = Python.CreateEngine();
            ScriptEngine engine = IronPython.Hosting.Python.CreateEngine(new Dictionary<string, object> { { "Debug", ScriptingRuntimeHelpers.True } });
            Debug.Assert(engine.Runtime.Setup.DebugMode);

            try
            {
                dynamic sys  = Python.GetSysModule(engine);
                sys.argv = args;
                
                var source = engine.CreateScriptSourceFromFile(scriptfile);
                dynamic result = source.Execute();

                //Console.WriteLine("Script finished");
            }
            catch (Exception ex)
            {
                Console.WriteLine();

                Console.WriteLine("[Exception] command " + command + ".py caused an exception: " + ex.Message);

                ExceptionOperations eo = engine.GetService<ExceptionOperations>();
                string error = eo.FormatException(ex);
                Console.WriteLine(error);

            }
        }


        public static void ShowUsageIPyScript(string command, bool v)
        {
            String scriptfile = Path.Combine(GetCFORGEScriptPath(), command + ".py");
            if (!File.Exists(scriptfile))
            {
                Console.WriteLine("[ERROR] Cannot execute command: no such file or directory: " + scriptfile);
                return;
            }

            ScriptRuntime runtime;
            ScriptEngine engine;
            runtime = Python.CreateRuntime();
            engine = Python.GetEngine(runtime);

            

            try
            {
                
                dynamic script = runtime.UseFile(scriptfile);

                var help = script.cforge_usage();

                foreach (var item in help)
                {
                    String cmd = "--" + command + " " + item[0].ToString();
                    cmd = cmd.PadRight(32) + item[1];
                    Console.WriteLine(cmd);
                }
                
            }
            catch
            {
                
                // we silently ignore errors in this script, as we only want to show the usage!
                Console.WriteLine(("--" + command).PadRight(32) + "");
                
            }
        }

        #endregion
    }
}