using System; using System.Collections.Generic; using System.Linq; using System.Text; using Yaulw.Process; using System.IO; using Yaulw.Tools; using System.Diagnostics; using Yaulw.Other; namespace Yaulw.Installer { public static class Common { #region Setup / Spawners /// /// Spawn a Setup Process (Setup.exe for example) /// public static void PSetupSpwan(string SetupFileNameNPath, string param_s, bool bWait) { try { if (!String.IsNullOrEmpty(SetupFileNameNPath) && Tools.PathNaming.FileNameIsValid(System.IO.Path.GetFileName(SetupFileNameNPath))) { //string dir = Tools.PathNaming.MakeDirectoryPathValid(System.IO.Path.GetDirectoryName(SetupFileNameNPath)); //SetupFileNameNPath = dir + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(SetupFileNameNPath); //if (!String.IsNullOrEmpty(param_s)) //{ // CMDline cmd = new CMDline(null, null); // bool bIsValidParse = cmd.Parse(param_s.Split(' '), false); // if (bIsValidParse) // param_s = cmd.MakeValidCmdStrFromNewlyParsedCmdLine(); // else // return; // Invalid Parameters passed in that could cause OS Command Injection //} PStarter.StartProcess(PStartInfo.CreateProcess(SetupFileNameNPath, param_s, "", true, System.Diagnostics.ProcessWindowStyle.Hidden, false), bWait, false); } } catch (Exception e) { throw e; } } /// /// Spawn a Setup Process (Setup.exe for example) using shell execute /// public static void PSetupSpwanShell(string SetupFileNameNPath, string param_s, bool bWait) { try { if (!String.IsNullOrEmpty(SetupFileNameNPath) && Tools.PathNaming.FileNameIsValid(System.IO.Path.GetFileName(SetupFileNameNPath))) { //string dir = Tools.PathNaming.MakeDirectoryPathValid(System.IO.Path.GetDirectoryName(SetupFileNameNPath)); //SetupFileNameNPath = dir + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(SetupFileNameNPath); //if (!String.IsNullOrEmpty(param_s)) //{ // CMDline cmd = new CMDline(null, null); // bool bIsValidParse = cmd.Parse(param_s.Split(' '), false); // if (bIsValidParse) // param_s = cmd.MakeValidCmdStrFromNewlyParsedCmdLine(); // else // return; // Invalid Parameters passed in that could cause OS Command Injection //} PStarter.StartProcess(PStartInfo.CreateProcess(SetupFileNameNPath, param_s, "", true, System.Diagnostics.ProcessWindowStyle.Hidden, true), bWait, false); } } catch (Exception e) { throw e; } } /// /// Spawn a MSI Setup Process (*.msi) /// public static void PSetupMSIEXEC(string param_s) { try { string msiexec = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\msiexec.exe"; if (System.IO.File.Exists(msiexec)) { //if (!String.IsNullOrEmpty(param_s)) //{ // CMDline cmd = new CMDline(null, null); // bool bIsValidParse = cmd.Parse(param_s.Split(' '), false); // if (bIsValidParse) // param_s = cmd.MakeValidCmdStrFromNewlyParsedCmdLine(); // else // return; // Invalid Parameters passed in that could cause OS Command Injection //} PStarter.StartProcess(PStartInfo.CreateProcess(msiexec, param_s, "", true, System.Diagnostics.ProcessWindowStyle.Hidden, false), true, false); } } catch (Exception e) { throw e; } } /// /// Run a command on the commandline * Hidden * /// /// cmd to run public static string RunCmdLine(string cmdline) { string result = PStarter.RunDosCommand(cmdline); return result; } #endregion #region Service (ServiceW Repeat with Check Existence) /// /// Stop a service /// /// name of service to stop /// true if successful, false otherwise public static bool StopService(string ServiceName) { bool bSuccess = true; if (ServiceW.DoesServiceExist(ServiceName)) bSuccess = ServiceW.StopService(ServiceName, true, 120); return bSuccess; } /// /// Stop a service /// /// name of service to stop /// true if successful, false otherwise public static bool StopService(string ServiceName, int nTimeoutBeforeKill) { bool bSuccess = true; if (ServiceW.DoesServiceExist(ServiceName)) bSuccess = ServiceW.StopService(ServiceName, true, nTimeoutBeforeKill); return bSuccess; } /// /// start a service /// /// name of a service to start /// true if successful, false otherwise public static bool StartService(string ServiceName) { bool bSuccess = true; if (ServiceW.DoesServiceExist(ServiceName)) bSuccess = ServiceW.StartService(ServiceName, 120); return bSuccess; } /// /// Does Service Exist /// /// Name of service to check /// true if successful, false otherwise public static bool ServiceExists(string ServiceName) { return ServiceW.DoesServiceExist(ServiceName); } #endregion #region Windows Utils /// /// Use this to get the complete path to a .net framework utility like gacutil.exe or /// installutil.exe.. any .net framework utility. Will fall back to look in the %temp% folder, /// if not found, giving the opportunity to deploy the util directly with the components /// /// the utility in .net you are looking for like gacutil.exe /// the full filenameNpath or "", if no existing file found public static string GetNetFrameworkUtilFileNameNPathFile(string UtilFileName) { string windir = System.Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine); string NetFramework1_0 = windir + "\\Microsoft.Net\\Framework\\v1.0.3705"; string NetFramework1_1 = windir + "\\Microsoft.Net\\Framework\\v1.1.4322"; string NetFramework2_0 = windir + "\\Microsoft.Net\\Framework\\v2.0.50727"; string NetFramework3_0 = windir + "\\Microsoft.Net\\Framework\\v3.0"; string NetFramework3_5 = windir + "\\Microsoft.Net\\Framework\\v3.5"; string NetFramework4_0 = windir + "\\Microsoft.Net\\Framework\\v4.0.30319"; string TempPath = PathNaming.PathEndsWithNoSlash(Path.GetTempPath()); // We use this as a Fallback, in case file doesn't exist in the framework string[] Frameworks = new string[] { NetFramework2_0, NetFramework4_0, NetFramework1_0, NetFramework1_1, NetFramework3_0, NetFramework3_5, TempPath }; string NetUtilFileNameNPath = ""; foreach (string framework in Frameworks) { if (System.IO.File.Exists(framework + "\\" + UtilFileName)) { NetUtilFileNameNPath = framework + "\\" + UtilFileName; return NetUtilFileNameNPath; } }; return NetUtilFileNameNPath; } /// /// Quick Helper to get the Program Files Path for the specific system /// /// Program Files path with a '/' at the end public static string GetProgramFilesPathOnSystemWithEndSlash() { string ProgramFiles = System.Environment.GetEnvironmentVariable("ProgramFiles(x86)"); if (String.IsNullOrEmpty(ProgramFiles)) ProgramFiles = System.Environment.GetEnvironmentVariable("ProgramFiles"); return PathNaming.PathEndsWithSlash(ProgramFiles); } /// /// /// /// public static string SetOwnership() { // in order to do any of this, sadly, we must first install the windows resource kit //subinacl /subdirectories *.* /setowner=domainname\user return String.Empty; } /// /// To grant the specified User or group Full Control permissions to the folder and its contents /// /// full path to folder/directory /// domainname\administrator, any windows user or group /// public static bool GrantFullPermissionToFolderForUserOrGroup(string FolderNPath, string UserOrGroup) { if (Directory.Exists(FolderNPath)) { string command = String.Format("cacls \"{0}\" /t /e /g {1}:f", FolderNPath, UserOrGroup); if (command.Contains("Invalid arguments.")) return false; else return true; } return false; } #endregion #region Windows Commands /// /// Get The System up Time, important because we need SQL Server and Advantage up and running before /// doing anything /// /// public static TimeSpan GetSystemUpTime() { string Result = Yaulw.Installer.Common.RunCmdLine("net statistics server"); int n = Result.IndexOf("Sessions accepted"); if (n != -1) { Result = Result.Substring(0, n); n = Result.IndexOf("Statistics since "); if (n != -1) { Result = Result.Substring(n + "Statistics since ".Length); Result = Result.Replace("\n", ""); Result = Result.Replace("\r", ""); DateTime BootTime; if (DateTime.TryParse(Result, out BootTime)) return (DateTime.Now - BootTime); } } // Something went wrong with the first approach, // let's try another... using (var uptime = new PerformanceCounter("System", "System Up Time")) { uptime.NextValue(); //Call this an extra time before reading its value return TimeSpan.FromSeconds(uptime.NextValue()); } } /// /// Use this to create a quick File Shortcut on the system using ShellLink (File Only) /// /// A valid File on the system to point to (not a url) i believe url's are created differently /// a valid .lnk file name and location where to put the shortcut public static void CreateFileShortcut(string TargetFileNameNPath, string LnkFileNameNPath) { if (String.IsNullOrEmpty(TargetFileNameNPath) || String.IsNullOrEmpty(LnkFileNameNPath)) return; if (!System.IO.File.Exists(TargetFileNameNPath)) return; if (System.IO.File.Exists(LnkFileNameNPath)) System.IO.File.Delete(LnkFileNameNPath); using (ShellLink shortcut = new ShellLink()) { shortcut.Target = TargetFileNameNPath; shortcut.WorkingDirectory = Path.GetDirectoryName(TargetFileNameNPath); shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.Description = ""; // doesn't appear to do anything shortcut.Save(LnkFileNameNPath); } } #endregion #region Resource Extraction /// /// Extract a Binary Resource from a stream and write it to a file /// /// /// /// /// public static bool ExtractResourceStreamToFile(Stream resourceStream, string FileNameNPath, bool bForceWrite) { if (resourceStream != null && !String.IsNullOrEmpty(FileNameNPath)) { if (bForceWrite || !System.IO.File.Exists(FileNameNPath)) { try { using (resourceStream) using (BinaryReader br = new BinaryReader(resourceStream)) using (BinaryWriter bw = new BinaryWriter(new FileStream(FileNameNPath, FileMode.Create))) { byte[] buffer = new byte[64 * 1024]; int numread = br.Read(buffer, 0, buffer.Length); while (numread > 0) { bw.Write(buffer, 0, numread); numread = br.Read(buffer, 0, buffer.Length); } bw.Flush(); } return true; } catch (Exception) { /* ignore */ } } } return false; } #endregion } }