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;
		}
		private void SaveExecutionResult(string name, ExecutionResult res, DateTime started, DateTime ended)
		{
			StringBuilder builder = new StringBuilder();
			builder.AppendFormat("ResultCode={0}|", res.ResultCode);
			builder.AppendFormat("RebootRequired={0}|", res.RebootRequired);
			builder.AppendFormat("ErrorMessage={0}|", res.ErrorMessage);
			builder.AppendFormat("Value={0}|", res.Value);
			builder.AppendFormat("Started={0}|", started.ToString("yyyyMMddHHmmss"));
			builder.AppendFormat("Ended={0}", started.ToString("yyyyMMddHHmmss"));
			RegistryUtils.SetRegistryKeyStringValue(RegistryOutputKey, name, builder.ToString());
		}
		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 = 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;
		}
		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;
		}
		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;
		}
Beispiel #7
0
        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 failed!", attempts));
                    // 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);
        }
        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;
                    }
                }
            }
        }