internal ExecutionResult RemoteRun(string typeName, ref ExecutionContext context) { if (string.IsNullOrEmpty(typeName)) throw new ArgumentNullException("typeName"); string[] parts = typeName.Split(','); if (parts == null || parts.Length != 2) throw new ArgumentException("Incorrect type name " + typeName); Assembly assembly = typeof(ModuleLoader).Assembly; string fileName = parts[1].Trim(); if (!fileName.EndsWith(".dll")) fileName = fileName + ".dll"; string path = Path.Combine(Path.GetDirectoryName(assembly.Location), fileName); assembly = Assembly.LoadFrom(path); Type type = assembly.GetType(parts[0].Trim()); //Type type = Type.GetType(typeName); if (type == null) { throw new Exception(string.Format("Type {0} not found", typeName)); } IProvisioningModule module = Activator.CreateInstance(type) as IProvisioningModule; if (module == null) { throw new Exception(string.Format("Module {0} not found", typeName)); } return module.Run(ref context); }
public ExecutionResult Run(ref ExecutionContext context) { ExecutionResult ret = new ExecutionResult(); ret.ResultCode = 0; ret.ErrorMessage = null; ret.RebootRequired = false; context.ActivityDescription = "Changing password for built-in local Administrator account..."; context.Progress = 0; if (!context.Parameters.ContainsKey("Password")) { ret.ResultCode = 2; ret.ErrorMessage = "Parameter 'Password' not found"; Log.WriteError(ret.ErrorMessage); context.Progress = 100; return ret; } string password = context.Parameters["Password"]; if (string.IsNullOrEmpty(password)) { ret.ResultCode = 2; ret.ErrorMessage = "Password is null or empty"; Log.WriteError(ret.ErrorMessage); context.Progress = 100; return ret; } try { string userPath = string.Format("WinNT://{0}/{1}", System.Environment.MachineName, GetAdministratorName()); DirectoryEntry userEntry = new DirectoryEntry(userPath); userEntry.Invoke("SetPassword", new object[] { password }); userEntry.CommitChanges(); userEntry.Close(); } catch (Exception ex) { if (IsPasswordPolicyException(ex)) { ret.ResultCode = 1; ret.ErrorMessage = "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements."; } else { ret.ResultCode = 2; ret.ErrorMessage = ex.ToString(); } Log.WriteError(ret.ErrorMessage); } if (ret.ResultCode == 0) { Log.WriteInfo("Password has been changed successfully"); } context.Progress = 100; return ret; }
internal static ExecutionResult Run(string typeName, ref ExecutionContext context) { AppDomain domain = null; try { Evidence securityInfo = AppDomain.CurrentDomain.Evidence; AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; domain = AppDomain.CreateDomain("Remote Domain", securityInfo, info); ILease lease = domain.GetLifetimeService() as ILease; if (lease != null) { lease.InitialLeaseTime = TimeSpan.Zero; } domain.UnhandledException += new UnhandledExceptionEventHandler(OnDomainUnhandledException); ModuleLoader loader = (ModuleLoader)domain.CreateInstanceAndUnwrap( typeof(ModuleLoader).Assembly.FullName, typeof(ModuleLoader).FullName); foreach (TraceListener listener in Trace.Listeners) { loader.AddTraceListener(listener); } ExecutionResult ret = loader.RemoteRun(typeName, ref context); AppDomain.Unload(domain); return ret; } catch (Exception) { if (domain != null) { AppDomain.Unload(domain); } throw; } }
private void ProcessTasks() { // delete old results DeleteOldResults(); //process all tasks while (true) { //load completed tasks results string[] strResults = RegistryUtils.GetRegistryKeyValueNames(RegistryOutputKey); List<string> results = new List<string>(); foreach (string strResult in strResults) { if (!string.IsNullOrEmpty(strResult) && strResult.StartsWith(TaskPrefix) && strResult != CurrentTaskName) { //save only WebsitePanel tasks results.Add(strResult); } } // sorted list of tasks - will be sorted by the TaskID (time in ticks) SortedList<long, string> tasks = new SortedList<long, string>(); //load task definitions from input registry key string[] strTasks = RegistryUtils.GetRegistryKeyValueNames(RegistryInputKey); foreach (string strTask in strTasks) { if (results.Contains(strTask)) continue; // skip completed tasks if (!string.IsNullOrEmpty(strTask) && strTask.StartsWith(TaskPrefix)) { // extract Task ID parameter int idx = strTask.LastIndexOf('-'); if(idx == -1) continue; string strTaskId = strTask.Substring(idx + 1); long taskId = 0; try { taskId = Int64.Parse(strTaskId); } catch { continue; // wrong task format } //save only WebsitePanel tasks if(!tasks.ContainsKey(taskId)) tasks.Add(taskId, strTask); } } if (tasks.Count == 0) { if (rebootRequired) { ServiceLog.WriteInfo("Reboot required"); RebootSystem(); return; } //start timers StartPollTimer(); //starts task processing after poll interval StartIdleTimer(); //stops service if idle //no tasks - exit! return; } else { //stop idle timer as we need to process tasks StopIdleTimer(); } ExecutionContext context = null; foreach (long tid in tasks.Keys) { //find first correct task string taskDefinition = tasks[tid]; string taskParameters = RegistryUtils.GetRegistryKeyStringValue(RegistryInputKey, taskDefinition); if (taskDefinition.LastIndexOf("-") == -1 || taskDefinition.LastIndexOf('-') == taskDefinition.Length - 1) { ServiceLog.WriteError(string.Format("Task was deleted from queue as its definition is invalid : {0}", taskDefinition)); DeleteRegistryKeyValue(RegistryInputKey, taskDefinition); //go to next task continue; } string taskName = taskDefinition.Substring(0, taskDefinition.LastIndexOf("-")).Substring(TaskPrefix.Length); string taskId = taskDefinition.Substring(taskDefinition.LastIndexOf('-') + 1); if (!provisioningModules.ContainsKey(taskName)) { ServiceLog.WriteError(string.Format("Task was deleted from queue as its definition was not found : {0}", taskName)); DeleteRegistryKeyValue(RegistryInputKey, taskDefinition); //go to next task continue; } //prepare execution context for correct task context = new ExecutionContext(); context.ActivityID = taskId; context.ActivityName = taskName; ParseParameters(context.Parameters, taskParameters); context.ActivityDefinition = taskDefinition; break; } if (context != null) { string type = provisioningModules[context.ActivityName]; ExecutionResult res = null; DateTime start = DateTime.Now; try { //load module and run task ServiceLog.WriteStart(string.Format("Starting '{0}' module...", context.ActivityName)); context.Progress = 0; res = ModuleLoader.Run(type, ref context); context.Progress = 100; ServiceLog.WriteEnd(string.Format("'{0}' module finished.", context.ActivityName)); } catch (Exception ex) { ServiceLog.WriteError("Unhandled exception:", ex); res = new ExecutionResult(); res.ResultCode = -1; res.ErrorMessage = string.Format("Unhandled exception : {0}", ex); } DateTime end = DateTime.Now; SaveExecutionResult(context.ActivityDefinition, res, start, end); //DeleteRegistryKeyValue(RegistryInputKey, context.ActivityDefinition); if (res.RebootRequired) rebootRequired = true; } } }
public ExecutionResult Run(ref ExecutionContext context) { ExecutionResult ret = new ExecutionResult(); ret.ResultCode = 0; ret.ErrorMessage = null; ret.RebootRequired = false; context.ActivityDescription = "Configuring network adapter..."; context.Progress = 0; if (!CheckParameter(context, "MAC")) { ProcessError(context, ret, null, 2, "Parameter 'MAC' is not specified"); return ret; } string macAddress = context.Parameters["MAC"]; if (!IsValidMACAddress(macAddress)) { ProcessError(context, ret, null, 2, "Parameter 'MAC' has invalid format. It should be in 12:34:56:78:90:ab format."); return ret; } string adapterId = null; ManagementObject objAdapter = null; ManagementObjectCollection objAdapters = null; int attempts = 0; try { WmiUtils wmi = new WmiUtils("root\\cimv2"); string query = string.Format("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress = '{0}' AND IPEnabled = True", macAddress); //try to find adapter for 10 times while (true) { objAdapters = wmi.ExecuteQuery(query); if (objAdapters.Count > 0) { foreach (ManagementObject adapter in objAdapters) { objAdapter = adapter; adapterId = (string)adapter["SettingID"]; } break; } if (attempts > 9) { ProcessError(context, ret, null, 2, "Network adapter not found"); return ret; } attempts++; Log.WriteError(string.Format("Attempt #{0} to find network adapter (mac: {1}) failed!", attempts, macAddress)); // wait 1 min System.Threading.Thread.Sleep(60000); //repeat loop } } catch (Exception ex) { ProcessError(context, ret, ex, 2, "Network adapter configuration error: "); return ret; } if (CheckParameter(context, "EnableDHCP", "True")) { try { EnableDHCP(objAdapter); } catch (Exception ex) { ProcessError(context, ret, ex, 2, "DHCP error: "); return ret; } } else if (CheckParameter(context, "EnableDHCP", "False")) { if (!CheckParameter(context, "DefaultIPGateway")) { ProcessError(context, ret, null, 2, "Parameter 'DefaultIPGateway' is not specified"); return ret; } if (!CheckParameter(context, "IPAddress")) { ProcessError(context, ret, null, 2, "Parameter 'IPAddresses' is not specified"); return ret; } if (!CheckParameter(context, "SubnetMask")) { ProcessError(context, ret, null, 2, "Parameter 'SubnetMasks' is not specified"); return ret; } try { DisableDHCP(context, objAdapter); } catch (Exception ex) { ProcessError(context, ret, ex, 2, "Network adapter configuration error: "); return ret; } } if (CheckParameter(context, "PreferredDNSServer")) { try { SetDNSServer(context, objAdapter); } catch (Exception ex) { ProcessError(context, ret, ex, 2, "DNS error: "); return ret; } } context.Progress = 100; return ret; }
public ExecutionResult Run(ref ExecutionContext context) { ExecutionResult ret = new ExecutionResult(); ret.ResultCode = 0; ret.ErrorMessage = null; ret.RebootRequired = true; context.ActivityDescription = "Changing computer name..."; context.Progress = 0; if (!context.Parameters.ContainsKey("FullComputerName")) { ret.ResultCode = 2; ret.ErrorMessage = "Parameter 'FullComputerName' not found"; Log.WriteError(ret.ErrorMessage); context.Progress = 100; return ret; } // Call SetComputerEx string computerName = context.Parameters["FullComputerName"]; string netBiosName = computerName; string primaryDnsSuffix = ""; int idx = netBiosName.IndexOf("."); if (idx != -1) { netBiosName = computerName.Substring(0, idx); primaryDnsSuffix = computerName.Substring(idx + 1); } try { // set NetBIOS name bool res = SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname, netBiosName); if (!res) { ret.ResultCode = 1; ret.ErrorMessage = "Unexpected error"; Log.WriteError(ret.ErrorMessage); } // set primary DNS suffix res = SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsDomain, primaryDnsSuffix); if (!res) { ret.ResultCode = 1; ret.ErrorMessage = "Unexpected error"; Log.WriteError(ret.ErrorMessage); } } catch (Exception ex) { ret.ResultCode = 1; ret.ErrorMessage = ex.ToString(); Log.WriteError(ret.ErrorMessage); } if (ret.ResultCode == 0) { Log.WriteInfo("Computer name has been changed successfully"); } context.Progress = 100; return ret; }
private static bool CheckParameter(ExecutionContext context, string name, string value) { return (context.Parameters.ContainsKey(name) && context.Parameters[name] == value); }
private static bool CheckParameter(ExecutionContext context, string name) { return (context.Parameters.ContainsKey(name) && !string.IsNullOrEmpty(context.Parameters[name])); }
private static void DisableDHCP(ExecutionContext context, ManagementObject adapter) { string[] ipGateways = ParseArray(context.Parameters["DefaultIPGateway"]); string[] ipAddresses = ParseArray(context.Parameters["IPAddress"]); string[] subnetMasks = ParseArray(context.Parameters["SubnetMask"]); if (subnetMasks.Length != ipAddresses.Length) { throw new ArgumentException("Number of Subnet Masks should be equal to IP Addresses"); } ManagementBaseObject objNewIP = null; ManagementBaseObject objSetIP = null; ManagementBaseObject objNewGateway = null; objNewIP = adapter.GetMethodParameters("EnableStatic"); objNewGateway = adapter.GetMethodParameters("SetGateways"); //Set DefaultGateway objNewGateway["DefaultIPGateway"] = ipGateways; int[] cost = new int[ipGateways.Length]; for (int i = 0; i < cost.Length; i++) cost[i] = 1; objNewGateway["GatewayCostMetric"] = cost; //Set IPAddress and Subnet Mask objNewIP["IPAddress"] = ipAddresses; objNewIP["SubnetMask"] = subnetMasks; Log.WriteStart("Configuring static IP..."); objSetIP = adapter.InvokeMethod("EnableStatic", objNewIP, null); Log.WriteEnd("IP configured"); Log.WriteStart("Configuring default gateway..."); objSetIP = adapter.InvokeMethod("SetGateways", objNewGateway, null); Log.WriteEnd("Default gateway configured"); }
private static void ProcessError(ExecutionContext context, ExecutionResult ret, Exception ex, int errorCode, string errorPrefix) { ret.ResultCode = errorCode; ret.ErrorMessage = errorPrefix; if (ex != null) ret.ErrorMessage += ex.ToString(); Log.WriteError(ret.ErrorMessage); context.Progress = 100; }
private void SetDNSServer(ExecutionContext context, ManagementObject objAdapter) { string[] dnsServers = ParseArray(context.Parameters["PreferredDNSServer"]); Log.WriteStart("Configuring DNS..."); ManagementBaseObject objDNS = objAdapter.GetMethodParameters("SetDNSServerSearchOrder"); objDNS["DNSServerSearchOrder"] = dnsServers; if (dnsServers.Length == 1 && dnsServers[0] == "0.0.0.0") { objDNS["DNSServerSearchOrder"] = new string[] { }; } ManagementBaseObject objRet = objAdapter.InvokeMethod("SetDNSServerSearchOrder", objDNS, null); Log.WriteEnd("DNS configured"); }