private static LaunchData GetLaunchDataFromPost(HttpRequest request) { var ld = new LaunchData(); if (request.Form?.TryGetValue("file", out StringValues file) == true) { ld.File = file; } if (request.Form?.TryGetValue("password", out StringValues pass) == true) { ld.Password = pass; } if (request.Form?.TryGetValue("html", out StringValues html) == true) { ld.AddHtmlCode = html == "1"; } if (request.Form?.TryGetValue("nocopy", out StringValues noCopy) == true) { ld.AddCopyProtection = noCopy == "1"; } if (request.Form?.TryGetValue("multi", out StringValues multi) == true) { ld.RenderMultiTo = multi.ToString().ToInt(); } T setProp <T>(TaskSettingProp prop, T defaultValue) => ReadPropFromForm(request, ld, "", prop, defaultValue); ld.Settings.ItemsCount = TaskLoader.LoadItemsCount(setProp(TaskSettingProp.ItemsCount, "")); ld.Settings.Level = setProp(TaskSettingProp.Level, "").Split(','); ld.Settings.RandomOrder = setProp(TaskSettingProp.RandomOrder, ld.Settings.RandomOrder); ld.Settings.Round = setProp(TaskSettingProp.Round, ld.Settings.Round); ld.Settings.SeparatePreviousPairs = setProp(TaskSettingProp.SeparatePreviousPairs, ld.Settings.SeparatePreviousPairs); ld.Settings.Seed = setProp(TaskSettingProp.Seed, ld.Settings.Seed); return(ld); }
/// <summary> /// Cleans up any context or state that may have been built up for a given task. /// </summary> /// <param name="task">The task to clean up.</param> /// <remarks> /// For many factories, this method is a no-op. But some factories may have built up /// an AppDomain as part of an individual task instance, and this is their opportunity /// to shutdown the AppDomain. /// </remarks> public void CleanupTask(ITask task) { ErrorUtilities.VerifyThrowArgumentNull(task, "task"); AppDomain appDomain; if (_tasksAndAppDomains.TryGetValue(task, out appDomain)) { _tasksAndAppDomains.Remove(task); if (appDomain != null) { // Unload the AppDomain asynchronously to avoid a deadlock that can happen because // AppDomain.Unload blocks for the process's one Finalizer thread to finalize all // objects. Some objects are RCWs for STA COM objects and as such would need the // VS main thread to be processing messages in order to finalize. But if the main thread // is blocked in a non-pumping wait waiting for this build request to complete, we would // deadlock. By unloading asynchronously, the AppDomain unload can block till the main // thread is available, even if it isn't available until after this MSBuild Task has // finished executing. Task.Run(() => AppDomain.Unload(appDomain)); } } TaskHostTask taskAsTaskHostTask = task as TaskHostTask; if (taskAsTaskHostTask != null) { taskAsTaskHostTask.Cleanup(); } else { // It's really not necessary to do it for TaskHostTasks TaskLoader.RemoveAssemblyResolver(); } }
public IEnumerable <Tuple <IEnumerable <ClientRating>, IEnumerable <Offer> > > Offers(IEnumerable <ClientRating> ratings, int count) { return(TaskLoader.ParallelLoader(ratings.GroupBy(r => r.ClientId).ToList(), g => GetOffers(g.Key), count) .Select(t => Tuple.Create <IEnumerable <ClientRating>, IEnumerable <Offer> >( t.Item1.ToArray(), t.Item2))); }
public bool LoadFromFile(string taskDataFile) { if (!LoadXmlFile(taskDataFile)) { return(false); } if (!VerifyIsoVersion()) { return(false); } LinkedIds = LinkListLoader.Load(this); Units = UnitLoader.Load(this); Customers = CustomerLoader.Load(this); Farms = FarmLoader.Load(this); Crops = CropLoader.Load(this); Fields = FieldLoader.Load(this); Products = ProductLoader.Load(this); ProductMixes = ProductMixLoader.Load(this); Workers = WorkerLoader.Load(this); Comments = CommentLoader.Load(this); Tasks = TaskLoader.Load(this); RasterPrescriptions = PrescriptionLoader.Load(this); Machines = DeviceLoader.Load(this); return(true); }
private void AddWaitQueue(TaskLoader taskLoader) { if (!_waitLoadQueue.Contains(taskLoader)) { _waitLoadQueue.Add(taskLoader); } _isCurrentLoading = true; }
public void LoadComplete(TaskLoader task) { _currentLoadQueue.Remove(task); if (_waitLoadQueue.Count <= 0) { _isCurrentLoading = false; } }
public void LoadGameObject(string path, LoadGameObjectCompleteHandler handler = null) { TaskLoader taskLoader = CreateLoadTaskLoader(path, ETaskType.gameobject); taskLoader.onGoComplete += handler; AddWaitQueue(taskLoader); }
public void Load(string path, LoadObjectCompleteHandler handler = null) { TaskLoader taskLoader = CreateLoadTaskLoader(path, ETaskType.asset); taskLoader.onAssetComplete += handler; AddWaitQueue(taskLoader); }
public void Load(string path, AssetBundleManager.LoadAssetCompleteHandler handler = null) { TaskLoader taskLoader = CreateLoadTaskLoader(path, ETaskType.abinfo); taskLoader.onAbInfoComplete += handler; AddWaitQueue(taskLoader); }
internal override void Execute() { var cmdlet = (ReceiveTmxTestTaskCommand)Cmdlet; var clientSettings = ClientSettings.Instance; clientSettings.StopImmediately = false; var taskLoader = new TaskLoader(new RestRequestCreator()); // 20141020 squeezing a task to its proxy ITestTask task = null; // ITestTaskProxy task = null; // ITestTaskCodeProxy task = null; // temporarily // TODO: to a template method var startTime = DateTime.Now; while (!clientSettings.StopImmediately) { // TODO: move to aspect try { task = taskLoader.GetCurrentTask(); } catch (ClientNotRegisteredException) { if (Guid.Empty != ClientSettings.Instance.ClientId && string.Empty != ClientSettings.Instance.ServerUrl) { var registration = new Registration(new RestRequestCreator()); ClientSettings.Instance.ClientId = registration.SendRegistrationInfoAndGetClientId(ClientSettings.Instance.CurrentClient.CustomString); } // TODO: AOP Trace.TraceWarning("ReceiveTestTaskCommand.1"); // temporary Trace.TraceWarning("ClientNotRegisteredException"); throw; } catch (Exception e) { // NullreferenceException // TODO: AOP Trace.TraceWarning("ReceiveTestTaskCommand.2"); // temporary Trace.TraceWarning(e.Message); } if (null != task) break; if (!cmdlet.Continuous) if ((DateTime.Now - startTime).TotalSeconds >= cmdlet.Seconds) throw new Exception("Failed to receive a task in " + cmdlet.Seconds + " seconds"); System.Threading.Thread.Sleep(Preferences.ReceivingTaskSleepIntervalMilliseconds); } clientSettings.StopImmediately = false; clientSettings.CurrentTask = task; cmdlet.WriteObject(task); }
/// <summary> /// This is responsible for cleaning up the task after the OutOfProcTaskHostNode has gathered everything it needs from this execution /// For example: We will need to hold on new AppDomains created until we finish getting all outputs from the task /// Add any other cleanup tasks here. Any method calling ExecuteTask must remember to call CleanupTask. /// </summary> internal void CleanupTask() { if (_taskAppDomain != null) { AppDomain.Unload(_taskAppDomain); } TaskLoader.RemoveAssemblyResolver(); _wrappedTask = null; }
private void btnSave_Click(object sender, EventArgs e) { if (mTreeView.Nodes[0].Nodes.Count == 0) { MessageService.ShowMessage("Please define at least one copy task"); return; } if (string.IsNullOrEmpty(txtName.Text)) { MessageService.ShowMessage("Please specify a name for this task"); return; } TaskManager tmgr = ServiceManager.Instance.GetService <TaskManager>(); if (IsNew && tmgr.GetTask(txtName.Text) != null) { MessageService.ShowMessage("A task named " + txtName.Text + " already exists. Please specify a name for this task"); return; } //This could take a while... using (new TempCursor(Cursors.WaitCursor)) { LoggingService.Info("Updating loaded task. Please wait."); TaskLoader loader = new TaskLoader(); if (IsNew) { string name = string.Empty; FdoBulkCopyOptions opts = loader.BulkCopyFromXml(Save(), ref name, false); FdoBulkCopy bcp = new FdoBulkCopy(opts); tmgr.AddTask(name, bcp); this.Close(); } else { FdoBulkCopy bcp = tmgr.GetTask(txtName.Text) as FdoBulkCopy; if (bcp == null) { MessageService.ShowMessage("This named task is not a bulk copy task or could not find the named task to update"); return; } string name = string.Empty; FdoBulkCopyOptions opts = loader.BulkCopyFromXml(Save(), ref name, false); Debug.Assert(name == txtName.Text); //unchanged //Update options bcp.Options = opts; MessageService.ShowMessage("Task updated. To save to disk, right-click the task object and choose: " + ResourceService.GetString("CMD_SaveTask")); this.Close(); } } }
/// <summary> /// This is responsible for cleaning up the task after the OutOfProcTaskHostNode has gathered everything it needs from this execution /// For example: We will need to hold on new AppDomains created until we finish getting all outputs from the task /// Add any other cleanup tasks here. Any method calling ExecuteTask must remember to call CleanupTask. /// </summary> internal void CleanupTask() { #if FEATURE_APPDOMAIN if (_taskAppDomain != null) { AppDomain.Unload(_taskAppDomain); } TaskLoader.RemoveAssemblyResolver(); #endif wrappedTask = null; }
private TaskLoader CreateLoadTaskLoader(string abFileName, ETaskType t) { TaskLoader loader = null; if (_loaderCache.ContainsKey(abFileName)) { loader = _loaderCache[abFileName]; } else { loader = new TaskLoader(abFileName, t); _loaderCache[abFileName] = loader; } return(loader); }
private void DoOpen(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { return; } if (!File.Exists(fileName)) { return; } _recorderFile = new FileInfo(fileName); UpdateTitle(); var loader = new TaskLoader(); LoadTree(loader.LoadTasks(fileName)); }
public override void Run() { TaskManager mgr = ServiceManager.Instance.GetService <TaskManager>(); TaskLoader ldr = new TaskLoader(); string file = FileService.OpenFile(ResourceService.GetString("TITLE_LOAD_TASK"), ResourceService.GetString("FILTER_TASK_DEFINITION")); if (FileService.FileExists(file)) { using (new TempCursor(Cursors.WaitCursor)) { LoggingService.Info(ResourceService.GetString("LOADING_TASK_DEFINITION_WAIT")); if (TaskDefinitionHelper.IsBulkCopy(file)) { string name = string.Empty; FdoBulkCopyOptions opt = ldr.BulkCopyFromXml(file, ref name, false); FdoBulkCopy cpy = new FdoBulkCopy(opt); mgr.AddTask(name, cpy); } else if (TaskDefinitionHelper.IsJoin(file)) { string name = string.Empty; FdoJoinOptions opt = ldr.JoinFromXml(file, ref name, false); FdoJoin join = new FdoJoin(opt); mgr.AddTask(name, join); } else if (TaskDefinitionHelper.IsSequentialProcess(file)) { using (var fs = File.OpenRead(file)) { int counter = 0; var prefix = Path.GetFileNameWithoutExtension(file); var name = prefix; while (mgr.NameExists(name)) { counter++; name = prefix + counter; } var def = (SequentialProcessDefinition)SequentialProcessDefinition.Serializer.Deserialize(fs); var proc = new FdoSequentialProcess(def); mgr.AddTask(name, proc); } } } } }
/// <summary> /// Handles the file drop /// </summary> /// <param name="file">The file being dropped</param> public void HandleDrop(string file) { TaskManager mgr = ServiceManager.Instance.GetService <TaskManager>(); TaskLoader ldr = new TaskLoader(); string prefix = string.Empty; FdoJoinOptions opt = ldr.JoinFromXml(file, ref prefix, false); FdoJoin join = new FdoJoin(opt); string name = prefix; int counter = 0; while (mgr.NameExists(name)) { counter++; name = prefix + counter; } mgr.AddTask(name, join); }
void Update() { if (_isCurrentLoading) { if (_waitLoadQueue.Count > 0) { int canLoadCount = MaxRequstCount - _currentLoadQueue.Count; while (canLoadCount > 0 && _waitLoadQueue.Count > 0) { TaskLoader taskLoader = _waitLoadQueue[0]; _waitLoadQueue.RemoveAt(0); _currentLoadQueue.Add(taskLoader); taskLoader.Begin(); canLoadCount--; } } } }
/// <summary> /// Handles the file drop /// </summary> /// <param name="file">The file being dropped</param> public void HandleDrop(string file) { TaskManager mgr = ServiceManager.Instance.GetService <TaskManager>(); TaskLoader ldr = new TaskLoader(); SequentialProcessDefinition spd = (SequentialProcessDefinition)SequentialProcessDefinition.Serializer.Deserialize(File.OpenRead(file)); FdoSequentialProcess proc = new FdoSequentialProcess(spd); string prefix = Path.GetFileNameWithoutExtension(file); string name = prefix; int counter = 0; while (mgr.NameExists(name)) { counter++; name = prefix + counter; } mgr.AddTask(name, proc); }
static void Main(string[] args) { var tasks = TaskLoader.LoadTasksFromFile("data1.xml"); var settings = tasks.Setting.MakeCopy(); settings.Seed = "abc123"; settings.SetProps |= TaskSettingProp.Round; for (int i = 1; i <= 10; i++) { settings.Round = i; Console.WriteLine($"Round {i}"); var text = TaskRender.Render(tasks, settings); Console.WriteLine(text); } Console.ReadLine(); }
private static LaunchData GetLaunchDataFromMoodle(HttpRequest request) { // TODO: chceck OAuth hash var ld = new LaunchData(); if (request.Form?.TryGetValue("custom_file", out StringValues file) == true) { ld.File = file; } if (request.Form?.TryGetValue("oauth_consumer_key", out StringValues pass) == true) { ld.Password = pass; } if (request.Form?.TryGetValue("custom_html", out StringValues html) == true) { ld.AddHtmlCode = html == "1"; } if (request.Form?.TryGetValue("custom_nocopy", out StringValues noCopy) == true) { ld.AddCopyProtection = noCopy == "1"; } if (request.Form?.TryGetValue("custom_multi", out StringValues multi) == true) { ld.RenderMultiTo = multi.ToString().ToInt(); } T setProp <T>(TaskSettingProp prop, T defaultValue) => ReadPropFromForm(request, ld, "custom_", prop, defaultValue); ld.Settings.ItemsCount = TaskLoader.LoadItemsCount(setProp(TaskSettingProp.ItemsCount, "")); ld.Settings.Level = setProp(TaskSettingProp.Level, "").Split(','); ld.Settings.RandomOrder = setProp(TaskSettingProp.RandomOrder, ld.Settings.RandomOrder); ld.Settings.Round = setProp(TaskSettingProp.Round, ld.Settings.Round); ld.Settings.SeparatePreviousPairs = setProp(TaskSettingProp.SeparatePreviousPairs, ld.Settings.SeparatePreviousPairs); ld.Settings.Seed = setProp(TaskSettingProp.Seed, ld.Settings.Seed); if (request.Form?.TryGetValue("lis_person_contact_email_primary", out StringValues email) == true) { ld.Settings.Seed += email; } return(ld); }
private static LaunchData GetLaunchDataFromGet(HttpRequest request) { var ld = new LaunchData(); ld.File = request.Query["file"]; ld.Password = request.Query["password"]; ld.AddHtmlCode = request.Query["html"] == "1"; ld.AddCopyProtection = request.Query["nocopy"] == "1"; ld.RenderMultiTo = request.Query["multi"].ToString().ToInt(); T setProp <T>(TaskSettingProp prop, T defaultValue) { string key = TaskSetting.ShorPropNames[prop]; string sVal = request.Query[key]; if (String.IsNullOrEmpty(sVal)) { return(defaultValue); } var val = TaskExtensions.ConvertValue(defaultValue.GetType(), sVal, null); if (val == null || !(val is T)) { return(defaultValue); } ld.Settings.SetProps |= prop; return((T)val); } ld.Settings.ItemsCount = TaskLoader.LoadItemsCount(setProp(TaskSettingProp.ItemsCount, "")); ld.Settings.Level = setProp(TaskSettingProp.Level, "").Split(','); ld.Settings.RandomOrder = setProp(TaskSettingProp.RandomOrder, ld.Settings.RandomOrder); ld.Settings.Round = setProp(TaskSettingProp.Round, ld.Settings.Round); ld.Settings.SeparatePreviousPairs = setProp(TaskSettingProp.SeparatePreviousPairs, ld.Settings.SeparatePreviousPairs); ld.Settings.Seed = setProp(TaskSettingProp.Seed, ld.Settings.Seed); return(ld); }
/// <summary> /// Do the work of actually instantiating and running the task. /// </summary> private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask ( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; try { wrappedTask = TaskLoader.CreateTask(taskType, taskName, taskFile, taskLine, taskColumn, new TaskLoader.LogError(LogErrorDelegate), #if FEATURE_APPDOMAIN appDomainSetup, #endif true /* always out of proc */ #if FEATURE_APPDOMAIN , out _taskAppDomain #endif ); wrappedTask.BuildEngine = oopTaskHostNode; } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } foreach (KeyValuePair <string, TaskParameter> param in taskParams) { try { PropertyInfo paramInfo = wrappedTask.GetType().GetProperty(param.Key, BindingFlags.Instance | BindingFlags.Public); paramInfo.SetValue(wrappedTask, param.Value?.WrappedParameter, null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "InvalidTaskAttributeError", new string[] { param.Key, param.Value.ToString(), taskName } )); } } bool success = false; try { if (CancelPending) { return(new OutOfProcTaskHostTaskResult(TaskCompleteType.Failure)); } // If it didn't crash and return before now, we're clear to go ahead and execute here. success = wrappedTask.Execute(); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } return(new OutOfProcTaskHostTaskResult(TaskCompleteType.CrashedDuringExecution, e)); } PropertyInfo[] finalPropertyValues = wrappedTask.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); IDictionary <string, Object> finalParameterValues = new Dictionary <string, Object>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo value in finalPropertyValues) { // only record outputs if (value.GetCustomAttributes(typeof(OutputAttribute), true).Count() > 0) { try { finalParameterValues[value.Name] = value.GetValue(wrappedTask, null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } // If it's not a critical exception, we assume there's some sort of problem in the parameter getter -- // so save the exception, and we'll re-throw once we're back on the main node side of the // communications pipe. finalParameterValues[value.Name] = e; } } } return(new OutOfProcTaskHostTaskResult(success ? TaskCompleteType.Success : TaskCompleteType.Failure, finalParameterValues)); }
static void CommandHandler(string S) { try { var commandName = string.Join("", S.TakeWhile(ch => ch != ' ')); if (commandName == "calc") { SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY"); var excelFile = new ExcelFile(); var workSheet = excelFile.Worksheets.Add("NestingResults"); var rowNum = 0; var jsonConverter = new NestingConverter(); jsonConverter.SaveFromNfToDbs(); var dirs = Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory); foreach (var dir in dirs) { var fileName = dir + "\\nest_000.nres"; if (File.Exists(fileName)) { rowNum++; var domainSize = 0d; var maxSize = 0d; var listY = 0d; var nfRatio = 0d; using (var file = new StreamReader(fileName)) { while (!file.EndOfStream) { var line = file.ReadLine(); if (string.IsNullOrEmpty(line)) { continue; } var split = line.Split(' ').ToList(); if (split.FirstOrDefault() == "Material") { double.TryParse(split.LastOrDefault()?.Replace(".", ","), out nfRatio); continue; } if (split.Count < 2) { continue; } double.TryParse(split.FirstOrDefault()?.Replace(".", ","), out double X); double.TryParse(split.FirstOrDefault()?.Replace(".", ","), out double Y); if (X > domainSize) { domainSize = X; } if (X > maxSize && Math.Abs(X - domainSize) > 0.1) { maxSize = X; } if (listY <= 0 && Y > 0) { listY = Y; } } } var dirName = dir.Split('\\').ToList().Last(); var loader = new TaskLoader(); var task = loader.LoadTFlexTask(dirName + ".tfnesting"); var tFlexRatio = task.Results.FirstOrDefault()?.KIM ?? 0; CalculateDbsNesting(dirName); var siriusRatio = ""; var resultReportPath = "report\\report_result.htm"; if (File.Exists(resultReportPath)) { var resultsHtml = File.ReadAllText(resultReportPath); siriusRatio = resultsHtml?.Split(' ').LastOrDefault()?.Replace("</b></body></html>\r\n", ""); } Console.WriteLine( $"Size: {domainSize}x{listY} ({domainSize * listY}), fact size: {maxSize}x{listY} ({maxSize * listY}), NF ratio: {nfRatio}, TFlex ratio: {tFlexRatio}"); workSheet.Cells[rowNum, 0].Value = dirName; workSheet.Cells[rowNum, 1].Value = $"{domainSize}x{listY}"; workSheet.Cells[rowNum, 2].Value = task.Parts.Sum(i => i.Count); workSheet.Cells[rowNum, 4].Value = nfRatio; workSheet.Cells[rowNum, 5].Value = domainSize - maxSize; workSheet.Cells[rowNum, 6].Value = tFlexRatio; workSheet.Cells[rowNum, 8].Value = siriusRatio; } } excelFile.Save("results.xlsx"); } } catch (Exception ex) { Console.Write($"{ex.Message}\n{ex.StackTrace}\n"); } }
public LaunchData GetLaunchDataFromGetData(HttpRequest request) { try { string data64 = request.Query["data"]; string hash = request.Query["hash"]; if (String.IsNullOrEmpty(data64) || String.IsNullOrEmpty(hash)) { return(null); } string data = Encoding.UTF8.GetString(Convert.FromBase64String(data64)); string hashCals = GetHash(data); if (hashCals != hash) { return(null); } var prms = data.Split('&').Select(x => x.Split('=')).ToDictionary(k => k[0], v => v[1]); string timeOut = prms.GetValueOrDefault("timeout", ""); if (!String.IsNullOrEmpty(timeOut)) { var limit = DateTime.Parse(timeOut); if (DateTime.Now > limit) { return(null); } } var ld = new LaunchData(); T setProp <T>(TaskSettingProp prop, T defaultValue) { string key = TaskSetting.ShorPropNames[prop]; string sVal = ""; if (prms.ContainsKey(key)) { sVal = prms[key]; } if (String.IsNullOrEmpty(sVal)) { return(defaultValue); } var val = TaskExtensions.ConvertValue(defaultValue.GetType(), sVal, null); if (val == null || !(val is T)) { return(defaultValue); } ld.Settings.SetProps |= prop; return((T)val); } ld.Settings.ItemsCount = TaskLoader.LoadItemsCount(setProp(TaskSettingProp.ItemsCount, "")); ld.Settings.Level = setProp(TaskSettingProp.Level, "").Split(','); ld.Settings.RandomOrder = setProp(TaskSettingProp.RandomOrder, ld.Settings.RandomOrder); ld.Settings.Round = setProp(TaskSettingProp.Round, ld.Settings.Round); ld.Settings.SeparatePreviousPairs = setProp(TaskSettingProp.SeparatePreviousPairs, ld.Settings.SeparatePreviousPairs); ld.Settings.Seed = setProp(TaskSettingProp.Seed, ld.Settings.Seed); ld.Password = prms.GetValueOrDefault("password", ld.File); ld.File = prms.GetValueOrDefault("file", ld.File); ld.AddHtmlCode = prms.GetValueOrDefault("html", ld.File) == "1"; ld.AddCopyProtection = prms.GetValueOrDefault("nocopy", ld.File) == "1"; return(ld); } catch { return(null); } }
private static int RunTarget() { StaticTarget target; var ser = new DataContractJsonSerializer(typeof(StaticTarget)); using (var memoryStream = new MemoryStream()) { using (var writer = new StreamWriter(memoryStream, Encoding.Default, 1024 * 4, true)) { string s; while ((s = Console.ReadLine()) != null) { writer.WriteLine(s); } } memoryStream.Position = 0; target = (StaticTarget)ser.ReadObject(memoryStream); } foreach (StaticTarget.Task staticTask in target.Tasks) { Type type; if (staticTask.AssemblyFile != null) { AssemblyName an = AssemblyName.GetAssemblyName(staticTask.AssemblyFile); if (an == null) { Console.WriteLine("Caouldn't get assembly name for assembly file: " + staticTask.AssemblyFile); return(1); } Assembly a = Assembly.Load(an); if (a == null) { Console.WriteLine("Couldn't loaded assembly for assembly: " + an.FullName + " from file: " + staticTask.AssemblyFile); return(1); } type = a.GetType(staticTask.Name.Split(',')[0]); if (type == null) { Console.WriteLine("Couldn't create type for string: " + staticTask.Name.Split(',')[0] + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null")); Console.WriteLine("Types in the assembly:\n" + string.Join(",\n", a.GetTypes().Select(availableType => availableType.FullName))); return(1); } } else { type = Type.GetType(staticTask.Name); if (type == null) { Console.WriteLine("Couldn't create type for string: " + staticTask.Name + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null")); return(1); } } var assemblyLoadInfo = AssemblyLoadInfo.Create(assemblyFile: staticTask.AssemblyFile, assemblyName: staticTask.AssemblyName); if (assemblyLoadInfo == null) { Console.WriteLine("Couldn't create type for assembly file: " + (staticTask.AssemblyFile ?? "null") + " and name: " + (staticTask.AssemblyName ?? "null")); return(1); } LoadedType loadedType = new LoadedType(type, assemblyLoadInfo, null); TaskPropertyInfo[] taskProperties = AssemblyTaskFactory.GetTaskParameters(loadedType); ITask task = TaskLoader.CreateTask(loadedType, staticTask.Name, staticTask.AssemblyName, 0, 0, null #if FEATURE_APPDOMAIN , null #endif , false #if FEATURE_APPDOMAIN , out var appDomain #endif ); foreach (var parameter in staticTask.Parameters) { var taskPropertyInfo = taskProperties.FirstOrDefault(property => property.Name == parameter.Key); if (taskPropertyInfo == null) { Console.Error.WriteLine("Could not find property: \"" + parameter.Key + "\" for task + \"" + staticTask.Name + "\""); return(1); } StaticTarget.Task.ParameterType parameterType = parameter.Value.ParameterType; switch (parameterType) { case StaticTarget.Task.ParameterType.Primitive: object value = GetTypedValue(parameter.Value.Primitive.Type, parameter.Value.Primitive.Value); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, value); break; case StaticTarget.Task.ParameterType.Primitives: var values = GetTypedArrayValue(parameter.Value.Primitives.Type, parameter.Value.Primitives.Values); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, values); break; case StaticTarget.Task.ParameterType.TaskItem: TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, new TaskItem(parameter.Value.TaskItem.ItemSpec, parameter.Value.TaskItem.Metadata)); break; case StaticTarget.Task.ParameterType.TaskItems: ITaskItem[] taskItems = parameter.Value.TaskItems.Select(taskItem => new TaskItem(taskItem.ItemSpec, taskItem.Metadata)).ToArray(); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, taskItems); break; } } task.BuildEngine = new SimpleBuildEngine(); try { // MSBuild ignores this return value :( task.Execute(); } catch (Exception e) { Console.Error.WriteLine("TASK ERROR: " + e); return(1); } } return(0); }
private static void AppConfig() { TaskLoader.Start(); }
/// <summary> /// Create an instance of the wrapped ITask for a batch run of the task. /// </summary> internal ITask CreateTaskInstance(ElementLocation taskLocation, TaskLoggingContext taskLoggingContext, IBuildComponentHost buildComponentHost, IDictionary <string, string> taskIdentityParameters, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif bool isOutOfProc) { bool useTaskFactory = false; IDictionary <string, string> mergedParameters = null; _taskLoggingContext = taskLoggingContext; // Optimization for the common (vanilla AssemblyTaskFactory) case -- only calculate // the task factory parameters if we have any to calculate; otherwise even if we // still launch the task factory, it will be with parameters corresponding to the // current process. if ((_factoryIdentityParameters != null && _factoryIdentityParameters.Count > 0) || (taskIdentityParameters != null && taskIdentityParameters.Count > 0)) { VerifyThrowIdentityParametersValid(taskIdentityParameters, taskLocation, _taskName, "MSBuildRuntime", "MSBuildArchitecture"); mergedParameters = MergeTaskFactoryParameterSets(_factoryIdentityParameters, taskIdentityParameters); useTaskFactory = !NativeMethodsShared.IsMono && (_taskHostFactoryExplicitlyRequested || !TaskHostParametersMatchCurrentProcess(mergedParameters)); } else { // if we don't have any task host parameters specified on either the using task or the // task invocation, then we will run in-proc UNLESS "TaskHostFactory" is explicitly specified // as the task factory. useTaskFactory = _taskHostFactoryExplicitlyRequested; } if (useTaskFactory) { ErrorUtilities.VerifyThrowInternalNull(buildComponentHost, "buildComponentHost"); mergedParameters = mergedParameters ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); string runtime = null; string architecture = null; if (!mergedParameters.TryGetValue(XMakeAttributes.runtime, out runtime)) { mergedParameters[XMakeAttributes.runtime] = XMakeAttributes.MSBuildRuntimeValues.clr4; } if (!mergedParameters.TryGetValue(XMakeAttributes.architecture, out architecture)) { mergedParameters[XMakeAttributes.architecture] = XMakeAttributes.GetCurrentMSBuildArchitecture(); } TaskHostTask task = new TaskHostTask(taskLocation, taskLoggingContext, buildComponentHost, mergedParameters, _loadedType #if FEATURE_APPDOMAIN , appDomainSetup #endif ); return(task); } else { #if FEATURE_APPDOMAIN AppDomain taskAppDomain = null; #endif ITask taskInstance = TaskLoader.CreateTask(_loadedType, _taskName, taskLocation.File, taskLocation.Line, taskLocation.Column, new TaskLoader.LogError(ErrorLoggingDelegate) #if FEATURE_APPDOMAIN , appDomainSetup #endif , isOutOfProc #if FEATURE_APPDOMAIN , out taskAppDomain #endif ); #if FEATURE_APPDOMAIN if (taskAppDomain != null) { _tasksAndAppDomains[taskInstance] = taskAppDomain; } #endif return(taskInstance); } }
public void Show() { var parentHandle = new IntPtr(ArcMap.Application.hWnd); WpfProgressDialog progressDialog = new WpfProgressDialog { Title = Title, HideCancelButton = HideCancelButton, IsIndeterminate = IsIndetermiante }; var windowInteropHelper = new WindowInteropHelper(progressDialog) { Owner = parentHandle }; BackgroundWorker worker = new BackgroundWorker { WorkerReportsProgress = true }; if (ActionDelegate is Action <ProgressHandler> ) { worker.DoWork += (s, ea) => { ProgressHandler progressHandler = new ProgressHandler(); progressHandler.ProgressEvent += (progress, text) => { (s as BackgroundWorker).ReportProgress(progress); progressDialog.ProgressText.Dispatcher.Invoke( () => { progressDialog.ProgressText.Content = text; }, DispatcherPriority.ContextIdle); }; //var workerThread = new Thread(new ThreadStart(() => { // // to update the collection, we need to do it from within the Dispatcher's thread, because of thread affinity. // var item = DoOperationThatCallsIEComObjectAndReturnsItem(); // Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Send, addItem, item); //})); //workerThread.SetApartmentState(ApartmentState.STA); // set ApartmentState to STA //workerThread.Start(); // start it ActionDelegate.DynamicInvoke(progressHandler); }; worker.ProgressChanged += (s, ex) => progressDialog.ProgressBar.Value = ex.ProgressPercentage; worker.RunWorkerCompleted += (o, ea) => progressDialog.Close(); worker.RunWorkerAsync(); progressDialog.ShowDialog(); } else { //var workerThread = new Thread(new ThreadStart(() => //{ // ActionDelegate.DynamicInvoke(Params); // progressDialog.Close(); //})); //workerThread.SetApartmentState(ApartmentState.STA); //workerThread.Start(); //progressDialog.ShowDialog(); Task <object> TaskLoader; TaskLoader = Task <object> .Factory.StartNew(() => { ActionDelegate.DynamicInvoke(Params); progressDialog.SetNativeEnabled(true); progressDialog.Show(); return(null); }); TaskLoader.ContinueWith(t => { progressDialog.Close(); }, TaskScheduler.FromCurrentSynchronizationContext()); } }