internal bool IsTaskReadyToExecute(TaskItem task)
 {
     if (task == null) return false;
     var req = task.SystemData as TaskRequest;
     if (req == null) return true;
     return (req.LastAttempt + AttemptInterval <= DateTime.UtcNow);
 }
	public void refresh(TaskItem item)
	{	
		templateID = item.templateID;
		type = item.type;

		TaskName.text = item.name;
		TaskDes.text = item.decribe;

		if(type == (int)GlobalDef.TaskType.T_ONECE)
		{
			Title.spriteName = "08";
		}
		else if(type == (int)GlobalDef.TaskType.T_EVERTYDAY)
		{
			Title.spriteName = "07";
		}
//		if(item.isFinish())
//		{
//			Finish.gameObject.SetActive(true);
//		}
//		else 
//		{
//			Finish.gameObject.SetActive(false);
//		}
	}
 internal TimeSpan NeedWaitTask(TaskItem task)
 {
     TimeSpan timespan = TimeSpan.Zero;
     if (task == null) return timespan;
     var req = task.SystemData as TaskRequest;
     if (req == null) return timespan;
     return (req.LastAttempt + AttemptInterval) - DateTime.UtcNow;
 }
 public void Replace (TaskItem inner)
 {
   if (inner != Inner)
   {
     DisposeInner();
     Inner = inner;
   }
 }
 public void SaveAndReload ()
 {
   Inner.Save();
   var entryId = Inner.EntryID;
   DisposeInner();
   Thread.MemoryBarrier();
   Inner = _load (entryId);
 }
	/// <summary>
	/// 添加任务
	/// </summary>
	public void addTask(TaskItem task)
	{
		if(taskDict.ContainsKey(task.templateID))
		{
			Debug.LogError("already has this task!");
			return;
		}
		taskDict.Add(task.templateID, task);
	}
Example #7
0
        private void createTaskButton_Click(object sender, RoutedEventArgs e)
        {
            TaskItem newtask = new TaskItem()
            {
                AlertTime = new TimeSpan(13, 0, 0).ToString(),
                DueTime = new TimeSpan(13, 0, 0).ToString(),
                EscalationLevel1Time = new TimeSpan(13, 0, 0).ToString(),
                AssetCategoryID = 116,
                BusinessAreaID = 30,
                BypassManagerApproval = false,
                ChecklistID = 2,
                Comments = "No comments",
                Description = "Task2_Description",
                DocumentURL = "",
                FrequencyID = 7,
                FunctionalID = null,
                KeyControl = false,
                LocationID = 48,
                ManagerSelfApproval = false,
                RandomFrequencyID = null,
                SpecificFrequencyID = null,
                TaskName = "Task2",
                HolidayCalendar = true
            };

            List<User> taskassignees = new List<User>() { new User() {
                 BRID = "E20037236", 
                 UserLoginID = "ghoshnil"
            } };

            List<User> taskmanagers = new List<User>() { new User() {
                 BRID = "G47969783", 
                 UserLoginID = "mistryna"
            } };

            newtask.Assignees = taskassignees;
            newtask.Managers = taskmanagers;

            var request = new RestRequest("CreateTask", RestSharp.Method.POST) { RequestFormat = DataFormat.Json }.AddBody(newtask);

            checcklistadminclient.ExecuteAsync(request, (response) =>
            {
                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    int i = 1;
                }
                else
                {
                    var result = JsonConvert.DeserializeObject<List<TaskItem>>(response.Content);
                    int i = 1;
                }

            });



        }
Example #8
0
        public EditTaskItem(ICollectionView view, TaskItem taskItem)
        {
            InitializeComponent();

            this.DataContext = taskItem;
            _view = view;
            _taskItem = taskItem;

            this.Loaded += OnEditTaskItemLoaded;
            this.Closed += OnClosed;
        }
Example #9
0
 internal virtual void ExecuteTask(TaskItem task)
 {
     if (task == null) return;
     try
     {
         task.Task(task.UserData);
     }
     catch
     {
     }
 }
 public DesignDetailsViewModel()
     : base(null, null)
 {
     TaskItem = new TaskItem()
     {
         Title = "Sample Task",
         Description = "Description of the Sample Task",
         CreatedDate = DateTime.Now,
         DueDate = DateTime.Now.AddDays(1),
         Priority = Priority.Medium
     };
 }
Example #11
0
        public void AddDataItem(TaskItem newDataItem)
        {
            // Add a to-do item to the data context.
            dataDB.Items.InsertOnSubmit(newDataItem);

            // Save changes to the database.
            dataDB.SubmitChanges();

            // Add a to-do item to the "all" observable collection.
            AllDataItems.Add(newDataItem);
 
        }
Example #12
0
 private void SaveItemButton_Click(object sender, RoutedEventArgs e)
 {
     if (!String.IsNullOrEmpty(ItemName.Text) && !String.IsNullOrEmpty(ItemDescription.Text)
         && comboBox.SelectedIndex > -1)
     {
         TaskItem saveItem = new TaskItem(ItemName.Text, ItemDescription.Text);
         saveItem.startTime = ItemStartDate.Date.DateTime + ItemStartTime.Time;
         saveItem.endTime = ItemEndDate.Date.DateTime + ItemEndTime.Time;
         App.tasksManager.sections[comboBox.SelectedIndex].AddItem(saveItem);
         App.tasksManager.saveToFile();
         saveItem = null;
         this.Frame.Navigate(typeof(TaskItemView), App.tasksManager.sections[comboBox.SelectedIndex]);
     }
 }
        public void Description()
        {
            PropertiesChanged = new List<String>();
            var description = Guid.NewGuid().ToString();

            var taskItem = new TaskItem();

            taskItem.PropertyChanged += OnPropertyChanged;
            taskItem.Description = description;
            taskItem.PropertyChanged -= OnPropertyChanged;

            Assert.AreEqual(description, taskItem.Description, "Description");
            Assert.IsTrue(PropertiesChanged.Contains("Description"), "Description Property Changed");
        }
        public void DueDate()
        {
            PropertiesChanged = new List<String>();
            var dueDate = DateTime.Now;

            var taskItem = new TaskItem();

            taskItem.PropertyChanged += OnPropertyChanged;
            taskItem.DueDate = dueDate;
            taskItem.PropertyChanged -= OnPropertyChanged;

            Assert.AreEqual(dueDate, taskItem.DueDate, "DueDate");
            Assert.IsTrue(PropertiesChanged.Contains("DueDate"), "DueDate Property Changed");
        }
	public void addTempData()
	{
		for(int i = 0; i < 5; i++)
		{
			TaskItem item = new TaskItem();
			item.templateID = 800001 + i;
			everyDayTask.addTask(item);
			
			TaskItem item1 = new TaskItem();
			item1.templateID = 800001 + i;
			mainThreadTask.addTask(item1);
		}

	}
		public void SetUp()
		{
			_TaskTreeView = new NuGenTaskTreeView();
			_InitialCount = _TaskTreeView.Nodes.Count;
			_EventSink = new TaskTreeViewEventSink(_TaskTreeView);
			_ServiceProvider = new NuGenTaskServiceProvider();
			_XmlDoc = new XmlDocument();

			_TaskItemDescription = "Description";
			_TaskItemMock = new DynamicMock(typeof(TaskItem));
			_TaskItemMock.SetValue("Description", _TaskItemDescription);
			_TaskItem = (TaskItem)_TaskItemMock.Object;

			Assert.IsFalse(_TaskTreeView.LabelEdit);
		}
        public void DeleteTask()
        {
            var taskItem = new TaskItem();
            var expectedTasks = new ObservableCollection<TaskItem>();
            expectedTasks.Add(taskItem);

            TaskRepository.Tasks = expectedTasks;

            var args = new ExecuteEventArgs() { MethodParameter = taskItem };
            ViewModel.DeleteTask(null, args);

            var actualTasks = ViewModel.Tasks;

            Assert.IsFalse(actualTasks.Contains(taskItem));
        }
Example #18
0
File: Task.cs Project: taboo1/arena
    // Use this for initialization
    protected void Start()
    {
        library = GameObject.FindObjectOfType<Library>();
        taskValue = library.taskStrings.GetTaskValue(this.GetType().Name);

        item = library.pauseMenu.AddTask(this);

        item.SetDescription(GetDescription());
        item.SetReward(reward + "");

        if (PreferencesSaver.TaskIsComplete(1, this.GetType().Name))
        {
            SetComplete();
            item.SetDone();
        }
    }
Example #19
0
        public static void CallsExecuteAssemblyOnceForEachAssembly()
        {
            var visitor = new XmlTestExecutionVisitor(null, null);
            visitor.Finished.Set();
            var assm1 = new TaskItem(@"C:\Full\Path\1");
            var assm2 = new TaskItem(@"C:\Full\Path\2", new Dictionary<string, string> { { "ConfigFile", @"C:\Config\File" } });
            var xunit = new Testable_xunit { CreateVisitor_Result = visitor };
            xunit.Assemblies = new ITaskItem[] { assm1, assm2 };

            xunit.Execute();

            Assert.Collection(xunit.ExecuteAssembly_Calls,
                call => Assert.Equal(@"C:\Full\Path\1, (null)", call),
                call => Assert.Equal(@"C:\Full\Path\2, C:\Config\File", call)
            );
        }
Example #20
0
		public void TestCtor2 ()
		{
			string itemName = "itemName";
			string itemSpec = "a;b;c";
			// result of Utilities.Escape (itemSpec)
			string escapedInclude = "a%3bb%3bc";
			ITaskItem taskItem = new TaskItem (itemSpec);

			item = new BuildItem (itemName, taskItem);
	
			Assert.AreEqual (itemSpec, item.FinalItemSpec, "A1");
			Assert.AreEqual (escapedInclude, item.Include, "A2");
			Assert.AreEqual (String.Empty, item.Exclude, "A3");
			Assert.AreEqual (String.Empty, item.Condition, "A4");
			Assert.AreEqual (false, item.IsImported, "A5");
			Assert.AreEqual (itemName, item.Name, "A6");
		}
 internal override void ExecuteTask(TaskItem task)
 {
     var request = task.SystemData as TaskRequest;
     if (request == null) throw new ApplicationException("invalid task");
     request.CurrentAttempt++;
     request.LastAttempt = DateTime.UtcNow;
     bool done = false;
     try
     {
         done = task.Task(task.UserData);
     }
     catch
     {
     }
     if (!done)
     {
         if (request.CurrentAttempt < AttemptCount)
             EnqueueTaskInternal(task);
     }
 }
	public void onAddTask(SocketModel module)
	{
		TaskMessage.MsgAddNewTaskRep msg = MsgSerializer.Deserialize<TaskMessage.MsgAddNewTaskRep>(module);
	
		int templateID = msg.task.taskId;
		int type = StaticMission.Instance().getInt(templateID, "type");

		TaskItem item = new TaskItem();
		item.parseData(msg.task);
		if(type == (int)GlobalDef.TaskType.T_ONECE)
		{
			MonoInstancePool.getInstance<TaskManager>().getMainthreadTask().addTask(item);
			MonoInstancePool.getInstance<TaskManager>().getMainthreadTask().isDirty = true;
		}
		else if(type == (int)GlobalDef.TaskType.T_EVERTYDAY)
		{
			MonoInstancePool.getInstance<TaskManager>().getEveryDayTask().addTask(item);
			MonoInstancePool.getInstance<TaskManager>().getEveryDayTask().isDirty = true;
		}
	}
Example #23
0
        public IEnumerable<Project> Interpret(string dslText)
        {
            List<Project> projects = new List<Project>();
            var grammar = new ProjectsGrammar();
            var interpriter = new ScriptInterpreter(grammar);
            interpriter.Evaluate(dslText);
            if (interpriter.Status != InterpreterStatus.Ready)
            {
                throw new InvalidOperationException("Your syntax errored!?");
            }

            var program = interpriter.ParsedScript.Root.AstNode as StatementListNode;
            foreach (var node in program.ChildNodes)
            {
                if (node.Term.Name == "Project")
                {
                    var projectName = (LiteralValueNode) node.ChildNodes[0];
                    var project = new Project(projectName.Value.ToString().Trim());
                    projects.Add(project);
                    var notes = (StatementListNode) node.ChildNodes[1];
                    foreach(var note in notes.ChildNodes)
                    {
                        project.AddNote(((LiteralValueNode) note).Value.ToString().Trim());
                    }

                    var tasks = (StatementListNode)node.ChildNodes[2];
                    foreach (var child in tasks.ChildNodes)
                    {
                        var taskName = (LiteralValueNode)child.ChildNodes[0];
                        var task = new TaskItem(taskName.Value.ToString());
                        projects.Last().AddTask(task);
                        var taskNotes = (StatementListNode)child.ChildNodes[1];
                        foreach (var note in taskNotes.ChildNodes)
                        {
                            task.AddNote(((LiteralValueNode)note).Value.ToString().Trim());
                        }
                    }
                }
            }
            return projects;
        }
	public void onGetTaskList(SocketModel module)
	{
		TaskMessage.MsgGetTaskListRep msg = MsgSerializer.Deserialize<TaskMessage.MsgGetTaskListRep>(module);
		for(int i = 0; i < msg.mainTaskList.Count; i++)
		{
			TaskItem item = new TaskItem();
			TaskMessage.Task data = msg.mainTaskList[i];
			item.parseData(data);
//			Debug.Log("---------------id: " + msg.mainTaskList[i].param1_value + " " + msg.mainTaskList[i].param2_value + " " + item.param1_value + " " + item.param2_value);
			MonoInstancePool.getInstance<TaskManager>().getMainthreadTask().addTask(item);
			MonoInstancePool.getInstance<TaskManager>().getMainthreadTask().isDirty = true;
		}
		for(int i = 0; i < msg.dailyTaskList.Count; i++)
		{
			TaskItem item = new TaskItem();
			TaskMessage.Task data = msg.mainTaskList[i];
			item.parseData(data);
			MonoInstancePool.getInstance<TaskManager>().getEveryDayTask().addTask(item);
			MonoInstancePool.getInstance<TaskManager>().getEveryDayTask().isDirty = true;
		}



	}
Example #25
0
        public override bool Execute()
        {
            var prefixes        = BundleResource.SplitResourcePrefixes(ResourcePrefix);
            var bundleResources = new List <ITaskItem> ();

            if (BundleResources != null)
            {
                foreach (var item in BundleResources)
                {
                    var logicalName = BundleResource.GetLogicalName(ProjectDir, prefixes, item, !string.IsNullOrEmpty(SessionId));
                    // We need a physical path here, ignore the Link element
                    var    path = item.GetMetadata("FullPath");
                    string illegal;

                    if (!File.Exists(path))
                    {
                        Log.LogError(MSBStrings.E0099, logicalName, path);
                        continue;
                    }

                    if (logicalName.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal))
                    {
                        Log.LogError(null, null, null, item.ItemSpec, 0, 0, 0, 0, MSBStrings.E0100, logicalName);
                        continue;
                    }

                    if (logicalName == "Info.plist")
                    {
                        Log.LogWarning(null, null, null, item.ItemSpec, 0, 0, 0, 0, MSBStrings.E0101);
                        continue;
                    }

                    if (BundleResource.IsIllegalName(logicalName, out illegal))
                    {
                        Log.LogError(null, null, null, item.ItemSpec, 0, 0, 0, 0, MSBStrings.E0102, illegal);
                        continue;
                    }

                    var bundleResource = new TaskItem(item);
                    bundleResource.SetMetadata("LogicalName", logicalName);

                    bool optimize = false;

                    if (CanOptimize(item.ItemSpec))
                    {
                        var metadata = item.GetMetadata("Optimize");

                        // fall back to old metadata name
                        if (string.IsNullOrEmpty(metadata))
                        {
                            metadata = item.GetMetadata("OptimizeImage");
                        }

                        if (string.IsNullOrEmpty(metadata) || !bool.TryParse(metadata, out optimize))
                        {
                            switch (Path.GetExtension(item.ItemSpec).ToLowerInvariant())
                            {
                            case ".plist":
                            case ".strings": optimize = OptimizePropertyLists; break;

                            case ".png": optimize = OptimizePNGs; break;
                            }
                        }
                    }

                    bundleResource.SetMetadata("Optimize", optimize.ToString());

                    bundleResources.Add(bundleResource);
                }
            }

            BundleResourcesWithLogicalNames = bundleResources.ToArray();

            return(!Log.HasLoggedErrors);
        }
        // Extracts library project contents under e.g. obj/Debug/[__library_projects__/*.jar | res/*/*]
        // Extracts library project contents under e.g. obj/Debug/[lp/*.jar | res/*/*]
        void Extract(
            DirectoryAssemblyResolver res,
            IDictionary <string, ITaskItem> jars,
            ICollection <ITaskItem> resolvedResourceDirectories,
            ICollection <ITaskItem> resolvedAssetDirectories,
            ICollection <ITaskItem> resolvedEnvironments)
        {
            // lets "upgrade" the old directory.
            string oldPath = Path.GetFullPath(Path.Combine(OutputImportDirectory, "..", "__library_projects__"));

            if (!OutputImportDirectory.Contains("__library_projects__") && Directory.Exists(oldPath))
            {
                MonoAndroidHelper.SetDirectoryWriteable(Path.Combine(oldPath, ".."));
                Directory.Delete(oldPath, recursive: true);
            }
            var outdir = Path.GetFullPath(OutputImportDirectory);

            Directory.CreateDirectory(outdir);

            foreach (var assembly in Assemblies)
            {
                res.Load(assembly.ItemSpec);
            }

            bool skip;

            foreach (var assemblyItem in Assemblies)
            {
                var assemblyPath = assemblyItem.ItemSpec;
                var fileName     = Path.GetFileName(assemblyPath);
                if (MonoAndroidHelper.IsFrameworkAssembly(fileName) &&
                    !MonoAndroidHelper.FrameworkEmbeddedJarLookupTargets.Contains(fileName) &&
                    !MonoAndroidHelper.FrameworkEmbeddedNativeLibraryAssemblies.Contains(fileName))
                {
                    Log.LogDebugMessage($"Skipping framework assembly '{fileName}'.");
                    continue;
                }
                if (DesignTimeBuild && !File.Exists(assemblyPath))
                {
                    Log.LogDebugMessage($"Skipping non-existent dependency '{assemblyPath}' during a design-time build.");
                    continue;
                }
                if (bool.TryParse(assemblyItem.GetMetadata(GetAdditionalResourcesFromAssemblies.AndroidSkipResourceExtraction), out skip) && skip)
                {
                    Log.LogDebugMessage("Skipping resource extraction for '{0}' .", assemblyPath);
                    continue;
                }
                string assemblyFileName  = Path.GetFileNameWithoutExtension(assemblyPath);
                string assemblyIdentName = assemblyFileName;
                if (UseShortFileNames)
                {
                    assemblyIdentName = assemblyMap.GetLibraryImportDirectoryNameForAssembly(assemblyFileName);
                }
                string outDirForDll     = Path.Combine(OutputImportDirectory, assemblyIdentName);
                string importsDir       = Path.Combine(outDirForDll, ImportsDirectory);
                string nativeimportsDir = Path.Combine(outDirForDll, NativeImportsDirectory);
                string resDir           = Path.Combine(importsDir, "res");
                string assetsDir        = Path.Combine(importsDir, "assets");

                // Skip already-extracted resources.
                bool   updated      = false;
                string assemblyHash = MonoAndroidHelper.HashFile(assemblyPath);
                string stamp        = Path.Combine(outdir, assemblyIdentName + ".stamp");
                string stampHash    = File.Exists(stamp) ? File.ReadAllText(stamp) : null;
                if (assemblyHash == stampHash)
                {
                    Log.LogDebugMessage("Skipped resource lookup for {0}: extracted files are up to date", assemblyPath);
                    if (Directory.Exists(importsDir))
                    {
                        foreach (var file in Directory.EnumerateFiles(importsDir, "*.jar", SearchOption.AllDirectories))
                        {
                            AddJar(jars, Path.GetFullPath(file));
                        }
                    }
                    if (Directory.Exists(resDir))
                    {
                        var taskItem = new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> {
                            { OriginalFile, assemblyPath },
                        });
                        if (bool.TryParse(assemblyItem.GetMetadata(AndroidSkipResourceProcessing), out skip) && skip)
                        {
                            taskItem.SetMetadata(AndroidSkipResourceProcessing, "True");
                        }
                        resolvedResourceDirectories.Add(taskItem);
                    }
                    if (Directory.Exists(assetsDir))
                    {
                        resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> {
                            { OriginalFile, assemblyPath }
                        }));
                    }
                    foreach (var env in Directory.EnumerateFiles(outDirForDll, "__AndroidEnvironment__*", SearchOption.TopDirectoryOnly))
                    {
                        resolvedEnvironments.Add(new TaskItem(env, new Dictionary <string, string> {
                            { OriginalFile, assemblyPath }
                        }));
                    }
                    continue;
                }

                Log.LogDebugMessage($"Refreshing {assemblyFileName}.dll");

                var assembly = res.GetAssembly(assemblyPath);
                foreach (var mod in assembly.Modules)
                {
                    // android environment files
                    foreach (var envtxt in mod.Resources
                             .Where(r => r.Name.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase))
                             .Where(r => r is EmbeddedResource)
                             .Cast <EmbeddedResource> ())
                    {
                        var outFile = Path.Combine(outDirForDll, envtxt.Name);
                        using (var stream = envtxt.GetResourceStream()) {
                            updated |= MonoAndroidHelper.CopyIfStreamChanged(stream, outFile);
                        }
                        resolvedEnvironments.Add(new TaskItem(Path.GetFullPath(outFile), new Dictionary <string, string> {
                            { OriginalFile, assemblyPath }
                        }));
                    }

                    // embedded jars (EmbeddedJar, EmbeddedReferenceJar)
                    var resjars = mod.Resources
                                  .Where(r => r.Name.EndsWith(".jar", StringComparison.InvariantCultureIgnoreCase))
                                  .Select(r => (EmbeddedResource)r);
                    foreach (var resjar in resjars)
                    {
                        using (var stream = resjar.GetResourceStream()) {
                            AddJar(jars, importsDir, resjar.Name, assemblyPath);
                            updated |= MonoAndroidHelper.CopyIfStreamChanged(stream, Path.Combine(importsDir, resjar.Name));
                        }
                    }

                    var libzip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidNativeLibraries__.zip") as EmbeddedResource;
                    if (libzip != null)
                    {
                        List <string> files = new List <string> ();
                        using (var stream = libzip.GetResourceStream())
                            using (var zip = Xamarin.Tools.Zip.ZipArchive.Open(stream)) {
                                try {
                                    updated |= Files.ExtractAll(zip, nativeimportsDir, modifyCallback: (entryFullName) => {
                                        files.Add(Path.GetFullPath(Path.Combine(nativeimportsDir, entryFullName)));
                                        return(entryFullName
                                               .Replace("native_library_imports\\", "")
                                               .Replace("native_library_imports/", ""));
                                    }, deleteCallback: (fileToDelete) => {
                                        return(!files.Contains(fileToDelete));
                                    });
                                } catch (PathTooLongException ex) {
                                    Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}");
                                    return;
                                } catch (NotSupportedException ex) {
                                    Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}");
                                    return;
                                }
                            }
                    }

                    // embedded AndroidResourceLibrary archive
                    var reszip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidLibraryProjects__.zip") as EmbeddedResource;
                    if (reszip != null)
                    {
                        // temporarily extracted directory will look like:
                        //    __library_projects__/[dllname]/[library_project_imports | jlibs]/bin
                        using (var stream = reszip.GetResourceStream())
                            using (var zip = Xamarin.Tools.Zip.ZipArchive.Open(stream)) {
                                try {
                                    updated |= Files.ExtractAll(zip, importsDir, modifyCallback: (entryFullName) => {
                                        var path = entryFullName
                                                   .Replace("library_project_imports\\", "")
                                                   .Replace("library_project_imports/", "");
                                        if (path.EndsWith(".jar", StringComparison.OrdinalIgnoreCase))
                                        {
                                            AddJar(jars, importsDir, path, assemblyPath);
                                        }
                                        return(path);
                                    }, deleteCallback: (fileToDelete) => {
                                        return(!jars.ContainsKey(fileToDelete));
                                    });
                                } catch (PathTooLongException ex) {
                                    Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}");
                                    return;
                                } catch (NotSupportedException ex) {
                                    Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}");
                                    return;
                                }
                            }

                        // We used to *copy* the resources to overwrite other resources,
                        // which resulted in missing resource issue.
                        // Here we replaced copy with use of '-S' option and made it to work.
                        if (Directory.Exists(resDir))
                        {
                            var taskItem = new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> {
                                { OriginalFile, assemblyPath }
                            });
                            if (bool.TryParse(assemblyItem.GetMetadata(AndroidSkipResourceProcessing), out skip) && skip)
                            {
                                taskItem.SetMetadata(AndroidSkipResourceProcessing, "True");
                            }
                            resolvedResourceDirectories.Add(taskItem);
                        }
                        if (Directory.Exists(assetsDir))
                        {
                            resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> {
                                { OriginalFile, assemblyPath }
                            }));
                        }
                    }
                }

                if (Directory.Exists(importsDir))
                {
                    // Delete unknown files in the top directory of importsDir
                    foreach (var file in Directory.EnumerateFiles(importsDir, "*"))
                    {
                        var fullPath = Path.GetFullPath(file);
                        if (file.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase) && !resolvedEnvironments.Any(x => x.ItemSpec == fullPath))
                        {
                            Log.LogDebugMessage($"Deleting unknown AndroidEnvironment file: {Path.GetFileName (file)}");
                            File.Delete(fullPath);
                            updated = true;
                        }
                        else if (file.EndsWith(".jar", StringComparison.OrdinalIgnoreCase) && !jars.ContainsKey(fullPath))
                        {
                            Log.LogDebugMessage($"Deleting unknown jar: {Path.GetFileName (file)}");
                            File.Delete(fullPath);
                            updated = true;
                        }
                    }
                    if (assemblyHash != stampHash)
                    {
                        Log.LogDebugMessage($"Saving hash to {stamp}, changes: {updated}");
                        //NOTE: if the hash is different we always want to write the file, but preserve the timestamp if no changes
                        WriteAllText(stamp, assemblyHash, preserveTimestamp: !updated);
                    }
                }
            }
            foreach (var aarFile in AarLibraries ?? new ITaskItem[0])
            {
                if (!File.Exists(aarFile.ItemSpec))
                {
                    continue;
                }
                string aarIdentityName = Path.GetFileNameWithoutExtension(aarFile.ItemSpec);
                if (UseShortFileNames)
                {
                    aarIdentityName = assemblyMap.GetLibraryImportDirectoryNameForAssembly(aarIdentityName);
                }
                string outDirForDll = Path.Combine(OutputImportDirectory, aarIdentityName);
                string importsDir   = Path.Combine(outDirForDll, ImportsDirectory);
                string resDir       = Path.Combine(importsDir, "res");
                string assetsDir    = Path.Combine(importsDir, "assets");

                bool   updated     = false;
                string aarHash     = MonoAndroidHelper.HashFile(aarFile.ItemSpec);
                string stamp       = Path.Combine(outdir, aarIdentityName + ".stamp");
                string stampHash   = File.Exists(stamp) ? File.ReadAllText(stamp) : null;
                var    aarFullPath = Path.GetFullPath(aarFile.ItemSpec);
                if (aarHash == stampHash)
                {
                    Log.LogDebugMessage("Skipped {0}: extracted files are up to date", aarFile.ItemSpec);
                    if (Directory.Exists(importsDir))
                    {
                        foreach (var file in Directory.EnumerateFiles(importsDir, "*.jar", SearchOption.AllDirectories))
                        {
                            AddJar(jars, Path.GetFullPath(file));
                        }
                    }
                    if (Directory.Exists(resDir))
                    {
                        resolvedResourceDirectories.Add(new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> {
                            { OriginalFile, Path.GetFullPath(aarFile.ItemSpec) },
                            { AndroidSkipResourceProcessing, "True" },
                        }));
                    }
                    if (Directory.Exists(assetsDir))
                    {
                        resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> {
                            { OriginalFile, aarFullPath },
                        }));
                    }
                    continue;
                }

                Log.LogDebugMessage($"Refreshing {aarFile.ItemSpec}");

                // temporarily extracted directory will look like:
                // _lp_/[aarFile]

                using (var zip = MonoAndroidHelper.ReadZipFile(aarFile.ItemSpec)) {
                    try {
                        updated |= Files.ExtractAll(zip, importsDir, modifyCallback: (entryFullName) => {
                            var entryFileName = Path.GetFileName(entryFullName);
                            var entryPath     = Path.GetDirectoryName(entryFullName);
                            if (entryFileName.StartsWith("internal_impl", StringComparison.InvariantCulture))
                            {
                                var hash = Files.HashString(entryFileName);
                                var jar  = Path.Combine(entryPath, $"internal_impl-{hash}.jar");
                                AddJar(jars, importsDir, jar, aarFullPath);
                                return(jar);
                            }
                            if (entryFullName.EndsWith(".jar", StringComparison.OrdinalIgnoreCase))
                            {
                                AddJar(jars, importsDir, entryFullName, aarFullPath);
                            }
                            return(entryFullName);
                        }, deleteCallback: (fileToDelete) => {
                            return(!jars.ContainsKey(fileToDelete));
                        });

                        if (Directory.Exists(importsDir) && aarHash != stampHash)
                        {
                            Log.LogDebugMessage($"Saving hash to {stamp}, changes: {updated}");
                            //NOTE: if the hash is different we always want to write the file, but preserve the timestamp if no changes
                            WriteAllText(stamp, aarHash, preserveTimestamp: !updated);
                        }
                    } catch (PathTooLongException ex) {
                        Log.LogErrorFromException(new PathTooLongException($"Error extracting resources from \"{aarFile.ItemSpec}\"", ex));
                    }
                }
                if (Directory.Exists(resDir))
                {
                    resolvedResourceDirectories.Add(new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> {
                        { OriginalFile, aarFullPath },
                        { AndroidSkipResourceProcessing, "True" },
                    }));
                }
                if (Directory.Exists(assetsDir))
                {
                    resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> {
                        { OriginalFile, aarFullPath },
                    }));
                }
            }
        }
Example #27
0
        public override bool Execute()
        {
            Log.LogMessageFromText("Starting move", MessageImportance.Normal);
            bool allSucceeded = true;

            if (this.SourceFiles == null || this.SourceFiles.Length <= 0)
            {
                //if nothing to move just leave quietly
                this.DestinationFiles = new ITaskItem[0];
                Log.LogMessageFromText("Nothing to move", MessageImportance.Normal);
                return(true);
            }

            if (this.DestinationFiles == null && this.DestinationFolder == null)
            {
                Log.LogError("Unable to determine destination for files");
                return(false);
            }
            if (this.DestinationFiles != null && this.DestinationFolder != null)
            {
                Log.LogError("Both DestinationFiles & DestinationFolder were specified, only one can be provided");
                return(false);
            }

            if (this.DestinationFiles != null && (this.DestinationFiles.Length != this.SourceFiles.Length))
            {
                //# of items in source & dest don't match up
                Log.LogError("SourceFiles and DestinationFiles list have different sizes");
                return(false);
            }

            this.FileLengths = new long[this.SourceFiles.Length];

            if (this.DestinationFiles == null)
            {
                //populate from DestinationFolder
                this.DestinationFiles = new ITaskItem[this.SourceFiles.Length];

                for (int i = 0; i < this.SourceFiles.Length; i++)
                {
                    string destFile;

                    try
                    {
                        destFile = Path.Combine(this.DestinationFolder.ItemSpec,
                                                Path.GetFileName(this.SourceFiles[i].ItemSpec));
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("Unable to move files; " + ex.Message, null);
                        this.DestinationFiles = new ITaskItem[0];
                        return(false);
                    }
                    this.DestinationFiles[i] = new TaskItem(destFile);
                    this.SourceFiles[i].CopyMetadataTo(this.DestinationFiles[i]);
                    this.FileLengths[i] = new FileInfo(destFile).Length;
                }
            }

            MovedFiles = new ITaskItem[this.SourceFiles.Length];
            //now we can go through and move all the files
            for (int i = 0; i < SourceFiles.Length; i++)
            {
                string sourcePath = this.SourceFiles[i].ItemSpec;
                string destPath   = this.DestinationFiles[i].ItemSpec;
                try
                {
                    string message = string.Format("Moving file {0} to {1}",
                                                   sourcePath, destPath);
                    Log.LogMessageFromText(message, MessageImportance.Normal);
                    FileInfo      destFile  = new FileInfo(destPath);
                    DirectoryInfo parentDir = destFile.Directory;
                    if (!parentDir.Exists)
                    {
                        parentDir.Create();
                    }
                    File.Move(sourcePath, destPath);
                    MovedFiles[i]       = new TaskItem(destPath);
                    this.FileLengths[i] = destFile.Length; // chj adds this
                }
                catch (Exception ex)
                {
                    Log.LogError("Unable to move file: " + sourcePath +
                                 " to " + destPath + "\n" + ex.Message);
                    allSucceeded = false;
                }
            }

            return(allSucceeded);
        }
Example #28
0
 public TaskEntityMatchData(TaskItem task)
 {
     Subject   = task.Subject;
     StartDate = task.StartDate;
     DueDate   = task.DueDate;
 }
Example #29
0
        // private IBuildEngine buildEngine;

        /*public IBuildEngine BuildEngine
         * {
         *  get
         *  {
         *      if (this.buildEngine == null)
         *      {
         *          //this.buildEngine = new SimpleBuildEngine(LogMessageEvent);
         *          var vmb = new ViewModelBuildEngine(this.MessengerInstance);
         *          vmb.Enabled = true;
         *          this.buildEngine = vmb;
         *      }
         *      return buildEngine;
         *  }
         * }*/

        /// <summary>
        /// Prepares a task for display with an editor.
        /// </summary>
        /// <param name="taskTypeName">Name of the task type to instantiate.</param>
        /// <param name="taskAttributes">A list with the task attributes data.</param>
        /// <returns>A new task of the specified type, initialized with the data from the
        /// <paramref name="taskAttributes"/> list of Xml attributes.</returns>
        public ITask InitTaskEditor(string taskTypeName, IEnumerable <XmlAttribute> taskAttributes)
        {
            // var taskService = SimpleIoc.Default.GetInstance<ITaskService>();
            var task = this.taskService[taskTypeName];

            if (task == null)
            {
                return(null);
            }

            foreach (var item in taskAttributes)
            {
                var taskType = task.GetType();
                var property = taskType.GetProperty(item.Name);
                if (property == null)
                {
                    // Log property not found.
                    continue;
                }

                if (property.PropertyType.IsArray)
                {
                    // Log skipping array type.
                    continue;
                }

                if (property != null)
                {
                    object val = item.Value;
                    if (property.PropertyType.Name == "ITaskItem")
                    {
                        val = new TaskItem(item.Value);
                    }
                    else
                    {
                        // try
                        // {
                        val = Convert.ChangeType(item.Value, property.PropertyType);

                        // }
                        // catch (Exception ex)
                        // {
                        // }
                    }

                    property.SetValue(task, val, null);
                }
            }

            // var dst = this.Task.data.AnyAttr.Where((e) => e.Name == "DestinationFolder").FirstOrDefault();

            /*if (dst != null)
             * {
             *  var val = dst.Value;
             * }*/
            this.PrepareTask(task);
            this.taskInWork = task;
            return(task);

            // var str = XamlSerializer.Save(task);
            // SerializeTest(task);
        }
Example #30
0
        public void CreateNullNamedMetadata()
        {
            TaskItem item = new TaskItem("foo");

            item.SetMetadata(null, "x");
        }
Example #31
0
    private void PrecompileLibrary(ITaskItem assemblyItem)
    {
        string assembly    = assemblyItem.ItemSpec;
        string directory   = Path.GetDirectoryName(assembly) !;
        var    aotAssembly = new TaskItem(assembly);
        var    aotArgs     = new List <string>();
        var    processArgs = new List <string>();

        var a = assemblyItem.GetMetadata("AotArguments");

        if (a != null)
        {
            aotArgs.AddRange(a.Split(";", StringSplitOptions.RemoveEmptyEntries));
        }

        var p = assemblyItem.GetMetadata("ProcessArguments");

        if (p != null)
        {
            processArgs.AddRange(p.Split(";", StringSplitOptions.RemoveEmptyEntries));
        }

        Utils.LogInfo($"[AOT] {assembly}");

        processArgs.Add("--debug");

        // add LLVM options
        if (UseLLVM)
        {
            processArgs.Add("--llvm");

            aotArgs.Add($"nodebug"); // can't use debug symbols with LLVM
            aotArgs.Add($"llvm-path={LLVMPath}");
        }
        else
        {
            processArgs.Add("--nollvm");
        }

        // compute output mode and file names
        if (parsedAotMode == MonoAotMode.LLVMOnly)
        {
            aotArgs.Add("llvmonly");

            string llvmBitcodeFile = Path.ChangeExtension(assembly, ".dll.bc");
            aotArgs.Add($"outfile={llvmBitcodeFile}");
            aotAssembly.SetMetadata("LlvmBitcodeFile", llvmBitcodeFile);
        }
        else
        {
            if (parsedAotMode == MonoAotMode.Full)
            {
                aotArgs.Add("full");
            }

            if (parsedOutputType == MonoAotOutputType.AsmOnly)
            {
                aotArgs.Add("asmonly");

                string assemblerFile = Path.ChangeExtension(assembly, ".dll.s");
                aotArgs.Add($"outfile={assemblerFile}");
                aotAssembly.SetMetadata("AssemblerFile", assemblerFile);
            }
            else
            {
                string objectFile = Path.ChangeExtension(assembly, ".dll.o");
                aotArgs.Add($"outfile={objectFile}");
                aotAssembly.SetMetadata("ObjectFile", objectFile);
            }

            if (UseLLVM)
            {
                string llvmObjectFile = Path.ChangeExtension(assembly, ".dll-llvm.o");
                aotArgs.Add($"llvm-outfile={llvmObjectFile}");
                aotAssembly.SetMetadata("LlvmObjectFile", llvmObjectFile);
            }
        }

        // pass msym-dir if specified
        if (MsymPath != null)
        {
            aotArgs.Add($"msym-dir={MsymPath}");
        }

        string aotDataFile = Path.ChangeExtension(assembly, ".aotdata");

        aotArgs.Add($"data-outfile={aotDataFile}");
        aotAssembly.SetMetadata("AotDataFile", aotDataFile);

        // we need to quote the entire --aot arguments here to make sure it is parsed
        // on Windows as one argument. Otherwise it will be split up into multiple
        // values, which wont work.
        processArgs.Add($"\"--aot={String.Join(",", aotArgs)}\"");

        processArgs.Add(assembly);

        var envVariables = new Dictionary <string, string>
        {
            { "MONO_PATH", directory },
            { "MONO_ENV_OPTIONS", String.Empty } // we do not want options to be provided out of band to the cross compilers
        };

        // run the AOT compiler
        Utils.RunProcess(CompilerBinaryPath, String.Join(" ", processArgs), envVariables, directory);

        compiledAssemblies.Add(aotAssembly);
    }
Example #32
0
        public void VerifyAssemblyPulledOutOfFrameworkDoesntGetFrameworkFileAttribute()
        {
            MockEngine e = new MockEngine();

            string actualFrameworkDirectory      = @"c:\WINNT\Microsoft.NET\Framework\v2.0.MyVersion";
            string alternativeFrameworkDirectory = @"c:\WINNT\Microsoft.NET\Framework\v4.0.MyVersion";

            ITaskItem[] items = new TaskItem[] { new TaskItem(Path.Combine(actualFrameworkDirectory, "System.dll")) };

            // Version and directory match framework - it is a framework assembly
            string redistString1 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='2.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t1 = new ResolveAssemblyReference();

            t1.TargetFrameworkVersion     = "v4.5";
            t1.TargetFrameworkDirectories = new string[] { actualFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t1, e, items, redistString1, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t1.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Higher version than framework, but directory matches - it is a framework assembly
            string redistString2 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='1.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t2 = new ResolveAssemblyReference();

            t2.TargetFrameworkVersion     = "v4.5";
            t2.TargetFrameworkDirectories = new string[] { actualFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t2, e, items, redistString2, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t2.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Version is lower but directory does not match - it is a framework assembly
            string redistString3 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='3.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t3 = new ResolveAssemblyReference();

            t3.TargetFrameworkVersion     = "v4.5";
            t3.TargetFrameworkDirectories = new string[] { alternativeFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t3, e, items, redistString3, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t3.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Version is higher and directory does not match - this assembly has been pulled out of .NET
            string redistString4 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='1.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t4 = new ResolveAssemblyReference();

            t4.TargetFrameworkVersion     = "v4.5";
            t4.TargetFrameworkDirectories = new string[] { alternativeFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t4, e, items, redistString4, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.True(String.IsNullOrEmpty(t4.ResolvedFiles[0].GetMetadata("FrameworkFile")));
        }
Example #33
0
 /// <summary>
 /// Определение статуса PLM по статусу KS.Gantt
 // </summary>
 public NamedValue GetStatusPLM(TaskItem.TaskStates status)
 {
     return dictStatus[(int)status];
 }
 private bool UpdateTask(TaskItem taskItem, ReminderTask reminderTask)
 {
     try
     {
         taskItem.Subject = reminderTask.Title;
         taskItem.Body = reminderTask.Notes;
         taskItem.DueDate = reminderTask.Due.GetValueOrDefault();
         taskItem.StartDate = reminderTask.StartDate;
         taskItem.Complete = reminderTask.IsCompleted;
         if (reminderTask.IsCompleted)
         {
             taskItem.DateCompleted = reminderTask.CompletedOn.GetValueOrDefault();
         }
         
         taskItem.Status = reminderTask.GetOlTaskStatus();
         taskItem.Save();
         return true;
     } 
     catch (Exception exception)
     {
         Logger.Error(exception);
         return false;
     }
     
 }
		/*
		 * AddCodeTask
		 */

		/// <summary>
		/// </summary>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="taskItemToAdd"/> is <see langword="null"/>.
		/// </exception>
		public void AddCodeTask(TaskItem taskItemToAdd)
		{
			if (taskItemToAdd == null)
			{
				throw new ArgumentNullException("taskItemToAdd");
			}

			NuGenCodeTaskTreeNode codeTaskNode = new NuGenCodeTaskTreeNode(
				this.ServiceProvider
			);
			
			this.InitializeCodeTask(codeTaskNode);

			Debug.Assert(this.CodeTasks != null, "this.CodeTasks != null");
			this.CodeTasks.Add(codeTaskNode, taskItemToAdd);

			Debug.Assert(this.CommentsFolder != null, "this.CommentsFolder != null");
			this.CommentsFolder.Nodes.AddNode(codeTaskNode);

			codeTaskNode.Text = taskItemToAdd.Description;
		}
Example #36
0
 // POST api/task
 public void CreateTask([FromBody] TaskItem taskItem)
 {
     _taskService.Create(taskItem);
 }
Example #37
0
        public override bool Execute()
        {
            PDictionary plist;
            PString     value;

            try {
                plist = PDictionary.FromFile(AppManifest.ItemSpec);
            } catch (Exception ex) {
                Log.LogError(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, MSBStrings.E0055, ex.Message);
                return(false);
            }

//			deviceType = plist.GetUIDeviceFamily ();

            if (plist.TryGetValue(ManifestKeys.MinimumOSVersion, out value))
            {
                if (!IPhoneSdkVersion.TryParse(value.Value, out minimumOSVersion))
                {
                    Log.LogError(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, MSBStrings.E0011, value);
                    return(false);
                }
            }
            else
            {
                switch (Platform)
                {
                case ApplePlatform.iOS:
                    IPhoneSdkVersion sdkVersion;
                    if (!IPhoneSdkVersion.TryParse(SdkVersion, out sdkVersion))
                    {
                        Log.LogError(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, MSBStrings.E0056, SdkVersion);
                        return(false);
                    }

                    minimumOSVersion = sdkVersion;
                    break;

                case ApplePlatform.WatchOS:
                case ApplePlatform.TVOS:
                    minimumOSVersion = IPhoneSdkVersion.UseDefault;
                    break;

                default:
                    throw new InvalidOperationException(string.Format("Invalid framework: {0}", Platform));
                }
            }

            Directory.CreateDirectory(AppBundleDir);

            var executableLastWriteTime = default(DateTime);
            var executable = Path.Combine(AppBundleDir, ExecutableName);

            if (File.Exists(executable))
            {
                executableLastWriteTime = File.GetLastWriteTimeUtc(executable);
            }

            var result = base.Execute();

            CopiedFrameworks = GetCopiedFrameworks();

            if (File.Exists(executable) && File.GetLastWriteTimeUtc(executable) != executableLastWriteTime)
            {
                NativeExecutable = new TaskItem(executable);
            }

            return(result);
        }
        public override bool Execute()
        {
            if (Environment.GetEnvironmentVariable("DEBUG_NUGETIZER") == "1")
            {
                Debugger.Launch();
            }

            var packages = new ConcurrentDictionary <PackageIdentity, List <PackageIdentity> >();
            Func <string, PackageIdentity> parse = value =>
            {
                var parts = value.Split('/');
                return(new PackageIdentity(parts[0], parts[1]));
            };

            // Build the list of parent>child relationships.
            foreach (var dependency in PackageDependencies.Where(x => x.ItemSpec.Contains('/')))
            {
                var identity = parse(dependency.ItemSpec);
                var parent   = dependency.GetMetadata("ParentPackage");
                if (!string.IsNullOrEmpty(parent))
                {
                    packages.GetOrAdd(parse(parent), _ => new List <PackageIdentity>())
                    .Add(identity);
                }
                else
                {
                    // In centrally managed package versions, at this point we have
                    // the right version if the project is using centrally managed versions
                    var primaryReference = PackageReferences.FirstOrDefault(x => x.ItemSpec == identity.Id);
                    if (primaryReference != null && primaryReference.GetNullableMetadata("Version") == null)
                    {
                        primaryReference.SetMetadata("Version", identity.Version);
                    }
                }
            }

            var inferred = new Dictionary <PackageIdentity, ITaskItem>();

            foreach (var reference in PackageReferences)
            {
                var identity         = new PackageIdentity(reference.ItemSpec, reference.GetMetadata("Version"));
                var originalMetadata = (IDictionary <string, string>)reference.CloneCustomMetadata();
                foreach (var dependency in FindDependencies(identity, packages))
                {
                    if (!inferred.ContainsKey(dependency))
                    {
                        var item = new TaskItem(dependency.Id);
                        foreach (var metadata in originalMetadata)
                        {
                            item.SetMetadata(metadata.Key, metadata.Value);
                        }

                        item.SetMetadata("Version", dependency.Version);
                        inferred.Add(dependency, item);
                    }
                }
            }

            ImplicitPackageReferences = inferred.Values.ToArray();

            return(true);
        }
Example #39
0
        public override bool Execute()
        {
            var intermediate          = Path.Combine(IntermediateOutputPath, ToolName);
            var intermediateBundleDir = Path.Combine(intermediate, "bundle");
            var intermediateCloneDir  = Path.Combine(intermediate, "cloned-assets");
            var manifest        = new TaskItem(Path.Combine(intermediate, "asset-manifest.plist"));
            var bundleResources = new List <ITaskItem> ();
            var outputManifests = new List <ITaskItem> ();
            var catalogs        = new List <ITaskItem> ();
            var unique          = new HashSet <string> ();

            var knownSpecs = new HashSet <string> ();
            var clones     = new HashSet <string> ();
            var items      = new List <ITaskItem> ();
            var specs      = new PArray();

            if (AppManifest != null)
            {
                try {
                    plist = PDictionary.FromFile(AppManifest.ItemSpec);
                } catch (Exception ex) {
                    Log.LogError(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, "{0}", ex.Message);
                    return(false);
                }
            }

            for (int i = 0; i < ImageAssets.Length; i++)
            {
                var vpath = BundleResource.GetVirtualProjectPath(ProjectDir, ImageAssets[i], !string.IsNullOrEmpty(SessionId));

                // Ignore MacOS .DS_Store files...
                if (Path.GetFileName(vpath).Equals(".DS_Store", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // get the parent (which will typically be .appiconset, .launchimage, .imageset, .iconset, etc)
                var catalog = Path.GetDirectoryName(vpath);

                // keep walking up the directory structure until we get to the .xcassets directory
                while (!string.IsNullOrEmpty(catalog) && Path.GetExtension(catalog) != ".xcassets")
                {
                    catalog = Path.GetDirectoryName(catalog);
                }

                if (string.IsNullOrEmpty(catalog))
                {
                    Log.LogWarning(null, null, null, ImageAssets[i].ItemSpec, 0, 0, 0, 0, MSBStrings.W0090, ImageAssets[i].ItemSpec);
                    continue;
                }

                if (ImageAssets[i].GetMetadata("Link") != null)
                {
                    // Note: if any of the files within a catalog are linked, we'll have to clone the *entire* catalog
                    clones.Add(catalog);
                    continue;
                }

                // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these
                if (Path.GetFileName(vpath) != "Contents.json")
                {
                    continue;
                }

                items.Add(ImageAssets[i]);
            }

            // clone any *.xcassets dirs that need cloning
            if (clones.Count > 0)
            {
                if (Directory.Exists(intermediateCloneDir))
                {
                    Directory.Delete(intermediateCloneDir, true);
                }

                Directory.CreateDirectory(intermediateCloneDir);

                items.Clear();

                for (int i = 0; i < ImageAssets.Length; i++)
                {
                    var       vpath = BundleResource.GetVirtualProjectPath(ProjectDir, ImageAssets[i], !string.IsNullOrEmpty(SessionId));
                    var       clone = false;
                    ITaskItem item;

                    // Ignore MacOS .DS_Store files...
                    if (Path.GetFileName(vpath).Equals(".DS_Store", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    foreach (var catalog in clones)
                    {
                        if (vpath.Length > catalog.Length && vpath[catalog.Length] == '/' && vpath.StartsWith(catalog, StringComparison.Ordinal))
                        {
                            clone = true;
                            break;
                        }
                    }

                    if (clone)
                    {
                        var src = ImageAssets[i].GetMetadata("FullPath");

                        if (!File.Exists(src))
                        {
                            Log.LogError(null, null, null, src, 0, 0, 0, 0, MSBStrings.E0091, src);
                            return(false);
                        }

                        var dest = Path.Combine(intermediateCloneDir, vpath);
                        var dir  = Path.GetDirectoryName(dest);

                        Directory.CreateDirectory(dir);

                        File.Copy(src, dest, true);

                        // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these
                        if (Path.GetFileName(vpath) != "Contents.json")
                        {
                            continue;
                        }

                        item = new TaskItem(dest);
                        ImageAssets[i].CopyMetadataTo(item);
                        item.SetMetadata("Link", vpath);
                    }
                    else
                    {
                        // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these
                        if (Path.GetFileName(vpath) != "Contents.json")
                        {
                            continue;
                        }

                        item = ImageAssets[i];
                    }

                    items.Add(item);
                }
            }

            // Note: `items` contains only the Contents.json files at this point
            for (int i = 0; i < items.Count; i++)
            {
                var vpath = BundleResource.GetVirtualProjectPath(ProjectDir, items[i], !string.IsNullOrEmpty(SessionId));
                var path  = items[i].GetMetadata("FullPath");

                // get the parent (which will typically be .appiconset, .launchimage, .imageset, .iconset, etc)
                var catalog = Path.GetDirectoryName(vpath);
                path = Path.GetDirectoryName(path);

                // keep walking up the directory structure until we get to the .xcassets directory
                while (!string.IsNullOrEmpty(catalog) && Path.GetExtension(catalog) != ".xcassets")
                {
                    catalog = Path.GetDirectoryName(catalog);
                    path    = Path.GetDirectoryName(path);
                }

                if (unique.Add(catalog))
                {
                    var item = new TaskItem(path);
                    item.SetMetadata("Link", catalog);

                    catalogs.Add(item);
                }

                if (AppleSdkSettings.XcodeVersion.Major >= 7 && SdkPlatform != "WatchSimulator")
                {
                    var text = File.ReadAllText(items[i].ItemSpec);

                    if (string.IsNullOrEmpty(text))
                    {
                        continue;
                    }

                    JsonDocument json;
                    JsonElement  value;

                    try {
                        var options = new JsonDocumentOptions()
                        {
                            AllowTrailingCommas = true,
                        };
                        json = JsonDocument.Parse(text, options);
                    } catch (JsonException je) {
                        var line = (int)(je.LineNumber + 1 ?? 0);
                        var col  = (int)(je.BytePositionInLine + 1 ?? 0);
                        Log.LogError(null, null, null, items [i].ItemSpec, line, col, line, col, "{0}", je.Message);
                        return(false);
                    } catch (Exception e) {
                        Log.LogError(null, null, null, items[i].ItemSpec, 0, 0, 0, 0, MSBStrings.E0092, e.Message);
                        return(false);
                    }

                    if (!json.RootElement.TryGetProperty("properties", out value) || value.ValueKind != JsonValueKind.Object)
                    {
                        continue;
                    }

                    var properties = value;

                    if (!properties.TryGetProperty("on-demand-resource-tags", out value) || value.ValueKind != JsonValueKind.Array)
                    {
                        continue;
                    }

                    var    resourceTags = value;
                    var    tags         = new HashSet <string> ();
                    string hash;

                    foreach (var tag in resourceTags.EnumerateArray())
                    {
                        if (tag.ValueKind == JsonValueKind.String)
                        {
                            tags.Add(tag.GetString());
                        }
                    }

                    var tagList = tags.ToList();
                    tagList.Sort();

                    var assetDir = AssetPackUtils.GetAssetPackDirectory(intermediate, BundleIdentifier, tagList, out hash);

                    if (knownSpecs.Add(hash))
                    {
                        var assetpack = new PDictionary();
                        var ptags     = new PArray();

                        Directory.CreateDirectory(assetDir);

                        for (int j = 0; j < tagList.Count; j++)
                        {
                            ptags.Add(new PString(tagList[j]));
                        }

                        assetpack.Add("bundle-id", new PString(string.Format("{0}.asset-pack-{1}", BundleIdentifier, hash)));
                        assetpack.Add("bundle-path", new PString(Path.GetFullPath(assetDir)));
                        assetpack.Add("tags", ptags);
                        specs.Add(assetpack);
                    }
                }
            }

            if (catalogs.Count == 0)
            {
                // There are no (supported?) asset catalogs
                return(!Log.HasLoggedErrors);
            }

            partialAppManifest = new TaskItem(Path.Combine(intermediate, "partial-info.plist"));

            if (specs.Count > 0)
            {
                outputSpecs = Path.Combine(intermediate, "output-specifications.plist");
                specs.Save(outputSpecs, true);
            }

            Directory.CreateDirectory(intermediateBundleDir);

            // Note: Compile() will set the PartialAppManifest property if it is used...
            if ((Compile(catalogs.ToArray(), intermediateBundleDir, manifest)) != 0)
            {
                return(false);
            }

            if (PartialAppManifest != null && !File.Exists(PartialAppManifest.GetMetadata("FullPath")))
            {
                Log.LogError(MSBStrings.E0093, PartialAppManifest.GetMetadata("FullPath"));
            }

            try {
                var manifestOutput = PDictionary.FromFile(manifest.ItemSpec);

                LogWarningsAndErrors(manifestOutput, catalogs[0]);

                bundleResources.AddRange(GetCompiledBundleResources(manifestOutput, intermediateBundleDir));
                outputManifests.Add(manifest);
            } catch (Exception ex) {
                Log.LogError(MSBStrings.E0094, ToolName, manifest.ItemSpec, ex.Message);
            }

            foreach (var assetpack in specs.OfType <PDictionary> ())
            {
                var path       = Path.Combine(assetpack.GetString("bundle-path").Value, "Info.plist");
                var bundlePath = PathUtils.AbsoluteToRelative(intermediate, path);
                var outputPath = Path.Combine(OutputPath, bundlePath);
                var rpath      = Path.Combine(intermediate, bundlePath);
                var dict       = new PDictionary();

                dict.SetCFBundleIdentifier(assetpack.GetString("bundle-id").Value);
                dict.Add("Tags", assetpack.GetArray("tags").Clone());

                dict.Save(path, true, true);

                var item = new TaskItem(rpath);
                item.SetMetadata("LogicalName", bundlePath);
                item.SetMetadata("OutputPath", outputPath);
                item.SetMetadata("Optimize", "false");

                bundleResources.Add(item);
            }

            BundleResources = bundleResources.ToArray();
            OutputManifests = outputManifests.ToArray();

            return(!Log.HasLoggedErrors);
        }
Example #40
0
        public override bool Execute()
        {
            if (string.IsNullOrEmpty(NoSymbolStrip))
            {
                NoSymbolStrip = "false";
            }

            if (string.IsNullOrEmpty(NoDSymUtil))
            {
                NoDSymUtil = "false";
            }

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var           args         = CommandLineArgumentBuilder.Parse(ExtraArgs);
                List <string> xml          = null;
                var           envVariables = new List <ITaskItem> ();
                var           dlsyms       = new List <ITaskItem> ();

                for (int i = 0; i < args.Length; i++)
                {
                    var arg = args [i];

                    if (string.IsNullOrEmpty(arg))
                    {
                        continue;
                    }

                    var index = 1;
                    if (arg [0] == '/')
                    {
                        // nothing to do
                    }
                    else if (arg [0] == '-')
                    {
                        if (arg.Length >= 2 && arg [1] == '-')
                        {
                            index++;
                        }
                    }
                    else
                    {
                        continue;
                    }
                    arg = arg.Substring(index);

                    var separators = new char [] { ':', '=' };
                    var eq         = arg.IndexOfAny(separators);
                    var value      = string.Empty;
                    var name       = arg;
                    var nextValue  = string.Empty;
                    var hasValue   = false;
                    if (eq >= 0)
                    {
                        name     = arg.Substring(0, eq);
                        value    = arg.Substring(eq + 1);
                        hasValue = true;
                    }
                    else if (i < args.Length - 1)
                    {
                        nextValue = args [i + 1];
                    }

                    switch (name)
                    {
                    case "nosymbolstrip":
                        // There's also a version that takes symbols as arguments:
                        // --nosymbolstrip:symbol1,symbol2
                        // in that case we do want to run the SymbolStrip target, so we
                        // do not set the MtouchNoSymbolStrip property to 'true' in that case.
                        NoSymbolStrip = string.IsNullOrEmpty(value) ? "true" : "false";
                        break;

                    case "dlsym":
                        dlsyms.Add(new TaskItem(string.IsNullOrEmpty(value) ? "true" : value));
                        break;

                    case "dsym":
                        NoDSymUtil = ParseBool(value) ? "false" : "true";
                        break;

                    case "verbose":
                    case "v":
                        Verbosity++;
                        break;

                    case "quiet":
                    case "q":
                        Verbosity--;
                        break;

                    case "marshal-managed-exceptions":
                        value = hasValue ? value : nextValue;                         // requires a value, which might be the next option
                        MarshalManagedExceptionMode = value;
                        break;

                    case "marshal-objectivec-exceptions":
                        value = hasValue ? value : nextValue;                         // requires a value, which might be the next option
                        MarshalObjectiveCExceptionMode = value;
                        break;

                    case "custom_bundle_name":
                        value            = hasValue ? value : nextValue;              // requires a value, which might be the next option
                        CustomBundleName = value;
                        break;

                    case "optimize":
                        if (!string.IsNullOrEmpty(Optimize))
                        {
                            Optimize += ",";
                        }
                        Optimize += value;
                        break;

                    case "registrar":
                        value     = hasValue ? value : nextValue;                     // requires a value, which might be the next option
                        Registrar = value;
                        break;

                    case "setenv":
                        value = hasValue ? value : nextValue;                         // requires a value, which might be the next option
                        var colon = value.IndexOfAny(separators);
                        var item  = new TaskItem(value.Substring(0, colon));
                        item.SetMetadata("Value", value.Substring(colon + 1));
                        envVariables.Add(item);
                        break;

                    case "xml":
                        if (xml == null)
                        {
                            xml = new List <string> ();
                        }
                        value = hasValue ? value : nextValue;                         // requires a value, which might be the next option
                        xml.Add(value);
                        break;

                    case "nostrip":
                        // Output is EnableAssemblyILStripping so we enable if --nostrip=false and disable if true
                        NoStrip = ParseBool(value) ? "false" : "true";
                        break;

                    default:
                        Log.LogMessage(MessageImportance.Low, "Skipping unknown argument '{0}' with value '{1}'", name, value);
                        break;
                    }
                }

                if (xml != null)
                {
                    var defs = new List <ITaskItem> ();
                    if (XmlDefinitions != null)
                    {
                        defs.AddRange(XmlDefinitions);
                    }
                    foreach (var x in xml)
                    {
                        defs.Add(new TaskItem(x));
                    }
                    XmlDefinitions = defs.ToArray();
                }

                if (envVariables.Count > 0)
                {
                    if (EnvironmentVariables != null)
                    {
                        envVariables.AddRange(EnvironmentVariables);
                    }
                    EnvironmentVariables = envVariables.ToArray();
                }

                if (dlsyms.Count > 0)
                {
                    if (DlSym != null)
                    {
                        dlsyms.AddRange(DlSym);
                    }
                    DlSym = dlsyms.ToArray();
                }
            }

            return(!Log.HasLoggedErrors);
        }
Example #41
0
        public void CreateEmptyNamedMetadata()
        {
            TaskItem item = new TaskItem("foo");

            item.SetMetadata("", "x");
        }
    List <TaskItem> InitTaskItem(JsonData jd)
    {
        List <TaskItem> taskitem = new List <TaskItem> ();

        for (int i = 0; i < jd.Count; i++)
        {
            TaskItem ti = new TaskItem();
            ti._Id = int.Parse((string)jd[i]["_id"]);
            int id;
            if (jd[i]["_task"] == null)
            {
                id = 0;
            }
            else
            {
                id = int.Parse((string)jd[i]["_task"]);
            }
            Task t = null;
            if (taskList.TryGetValue(id, out t))
            {
                ti._Task = MakeNewTask(t);
            }
            switch ((string)jd[i]["_taskProgress"])
            {
            case "Accept":
                ti._TaskProgress = TaskProgress.Accept;
                break;

            case "Complete":
                ti._TaskProgress = TaskProgress.Complete;
                break;

            case "NoStart":
                ti._TaskProgress = TaskProgress.NoStart;
                break;

            case "Reward":
                ti._TaskProgress = TaskProgress.Reward;
                break;
            }
            switch ((string)jd[i]["_taskType"])
            {
            case "Main":
                ti._TaskType = TaskType.Main;
                break;

            case "Reward":
                ti._TaskType = TaskType.Reward;
                break;

            case "Daily":
                ti._TaskType = TaskType.Daily;
                break;
            }
            ti._IdTranscript = int.Parse((string)jd[i]["_idTranscript"]);
            ti._OwnName      = (string)jd[i]["_ownName"];
            if (id == 0)
            {
                ti._Name     = (string)jd[i]["_name"];
                ti._Des      = (string)jd[i]["_des"];
                ti._Coin     = int.Parse((string)jd[i]["_coin"]);
                ti._Diamond  = int.Parse((string)jd[i]["_diamond"]);
                ti._Mine     = int.Parse((string)jd[i]["_mine"]);
                ti._Ruby     = int.Parse((string)jd[i]["_ruby"]);
                ti._Treasure = int.Parse((string)jd[i]["_treasure"]);
                ti._Power    = int.Parse((string)jd[i]["_power"]);
                ti._Feats    = int.Parse((string)jd[i]["_feats"]);
            }
            taskitem.Add(ti);
        }
        return(taskitem);
    }
Example #43
0
        /// <summary>
        /// Prepares the 'SourceFiles', etc., <see cref="TaskItem"/> data.
        /// </summary>
        /// <param name="task">The task to prepare.</param>
        /// <remarks>
        /// This is experimental. Uncommenting the "cr.Execute()" line below, fills the
        /// SourceFiles property of a Backup-Task in the editor with the evaluated path data.
        /// A <see cref="CreateItem"/> task is used to mimic the work of a project build engine.
        /// </remarks>
        private void PrepareTask(ITask task)
        {
            // Todo: put this task generation extra.

            /*for (int index = 0; index < this.Paths.Count; index++)
             * {
             *  var item = this.Paths[index];
             * }*/
            // int xasd = 0;
            var result = this.Paths.Select(
                e =>
            {
                var cr = new CreateItem();
                if (e.Inclusion.Count > 0)
                {
                    cr.Include = e.Inclusion.Select(
                        t =>
                    {
                        if (e.Path.EndsWith("\\"))
                        {
                            return(new TaskItem(e.Path + t.Pattern));
                        }
                        else
                        {
                            return(new TaskItem(e.Path + "\\" + t.Pattern));
                        }
                    }

                        ).ToArray();
                }
                else
                {
                    ITaskItem taskItem;
                    var finfo = new FileInfo(e.Path);
                    if (Directory.Exists(e.Path))
                    {
                        // a directory
                        taskItem = new TaskItem(e.Path + "\\" + recursivePattern);
                    }
                    else
                    {
                        // a file
                        taskItem = new TaskItem(e.Path);
                    }

                    cr.Include = new[] { taskItem };
                }

                cr.Exclude =
                    e.Exclusion.Select((t) => { return(new TaskItem(e.Path + "\\" + t.Pattern)); }).ToArray();

                // at the moment, do not execute the items.
                // cr.Execute();
                return(cr);
            }

                );

            if (task is Backup)
            {
                var btask = (Backup)task;

                // var res = result.ToArray();
                var includes = result.SelectMany((e) => e.Include);
                btask.SourceFiles = includes.ToArray();

                // btask.DestinationFolder = new TaskItem(@"C:\tmp\%(RecursiveDir)");
                // var itemsByType = new Hashtable();
                // foreach (var item in btask.SourceFiles)
                // {
                // itemsByType.Add(
                // }
                // var bla = ItemExpander.ItemizeItemVector(@"@(File)", null, itemsByType);
                // Todo: do i need the build engine ?
                // btask.BuildEngine = this.BuildEngine;
            }
        }
Example #44
0
 public TaskItem Create(TaskItem taskItem)
 {
     taskItem.Id = Tasks.Count() + 1;
     Tasks.Add(taskItem);
     return(taskItem);
 }
Example #45
0
        /// <summary>
        /// Returns a string with those switches and other information that can't go into a response file and
        /// must go directly onto the command line.
        /// Called after ValidateParameters and SkipTaskExecution
        /// </summary>
        override protected string GenerateCommandLineCommands()
        {
            CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
            bool serializationAssemblyPathExists           = false;

            try
            {
                if (SerializationAssembly == null)
                {
                    Debug.Assert(ShouldGenerateSerializer, "GenerateCommandLineCommands() should not be called if ShouldGenerateSerializer is true and SerializationAssembly is null.");

                    SerializationAssembly = new TaskItem[] { new TaskItem(SerializationAssemblyPath) };
                }

                // Add the assembly switch
                commandLineBuilder.AppendSwitchIfNotNull("/assembly:", AssemblyFullPath);

                commandLineBuilder.AppendWhenTrue("/proxytypes", Bag, "UseProxyTypes");

                //add the keep switch
                commandLineBuilder.AppendWhenTrue("/keep", Bag, "UseKeep");

                // Append the references, if any.
                if (References != null)
                {
                    foreach (string reference in References)
                    {
                        commandLineBuilder.AppendSwitchIfNotNull("/reference:", reference);
                    }
                }

                //Append the Types to the command line, if any.
                if (Types != null)
                {
                    foreach (string type in Types)
                    {
                        commandLineBuilder.AppendSwitchIfNotNull("/type:", type);
                    }
                }

                // The arguments to the "/compiler" switch are themselves switches to be passed to
                // the compiler when generating the serialization assembly.

                // Add the compiler command switches for strong naming on the serialization assembly
                if (KeyFile != null)
                {
                    commandLineBuilder.AppendNestedSwitch("/compiler:", "/keyfile:", KeyFile);
                }
                else if (KeyContainer != null)
                {
                    commandLineBuilder.AppendNestedSwitch("/compiler:", "/keycontainer:", KeyContainer);
                }

                commandLineBuilder.AppendPlusOrMinusSwitch("/compiler:/delaysign", Bag, "DelaySign");

                // Add the Platform switch to the compiler.
                if (Platform != null)
                {
                    commandLineBuilder.AppendNestedSwitch("/compiler:", "/platform:", Platform);
                }

                serializationAssemblyPathExists = File.Exists(SerializationAssemblyPath);
            }
            catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
            {
                // Ignore the expected exceptions because they have already been logged
            }

            // Delete the assembly if it already exists.
            if (serializationAssemblyPathExists)
            {
                try
                {
                    File.Delete(SerializationAssemblyPath);
                }
                // Of all of the exceptions that can be thrown on a File.Delete, the only ones we need to
                // be immediately concerned with are the UnauthorizedAccessException and the IOException
                // (file is in use exception).  We need to make sure that the assembly is gone before we
                // try to produce a new one because it is possible that after some changes were made to the
                // base assembly, there will, in fact, not be a serialization assembly produced.  We cannot
                // leave the earlier produced assembly around to be propagated by later processes.
                catch (UnauthorizedAccessException e)
                {
                    Log.LogErrorWithCodeFromResources("SGen.CouldNotDeleteSerializer", SerializationAssemblyPath, e.Message);
                }
                catch (IOException e)
                {
                    Log.LogErrorWithCodeFromResources("SGen.CouldNotDeleteSerializer", SerializationAssemblyPath, e.Message);
                }
                // The DirectoryNotFoundException is safely ignorable since that means that there is no
                // existing serialization assembly.  This would be extremely unlikely anyway because we
                // found the serializer just a couple of milliseconds ago.
            }

            return(commandLineBuilder.ToString());
        }
 public TaskItemWrapper(TaskItem inner, Func <string, TaskItem> load)
 {
     _load = load;
     Inner = inner;
 }
Example #47
0
        private async Task DeleteAsync(MusicDb db, PathData pd)
        {
            db.ChangeTracker.AutoDetectChangesEnabled = false;
            taskItem = await db.TaskItems.FindAsync(taskId);

            IEnumerable <MusicFile> musicFileList = null;
            string path = "";

            if (pd.GetFullOpusPath() != null)
            {
                path          = pd.IsCollections ? pd.OpusPath : $"{pd.ArtistPath}\\{pd.OpusPath}";
                musicFileList = db.MusicFiles
                                .Where(f => (f.DiskRoot.ToLower() == pd.DiskRoot.ToLower()) &&
                                       (f.StylePath.ToLower() == pd.StylePath.ToLower()) &&
                                       (f.OpusPath.ToLower() == path.ToLower()))
                                .OrderBy(f => f.File)
                ;
            }
            else
            {
                if (pd.IsCollections)
                {
                    musicFileList = db.MusicFiles
                                    .Where(f => (f.DiskRoot.ToLower() == pd.DiskRoot.ToLower()) &&
                                           (f.StylePath.ToLower() == pd.StylePath.ToLower()) &&
                                           f.Musician.ToLower() == "collections")
                                    .OrderBy(f => f.File)
                    ;
                }
                else
                {
                    musicFileList = db.MusicFiles
                                    .Where(f => (f.DiskRoot.ToLower() == pd.DiskRoot.ToLower()) &&
                                           (f.StylePath.ToLower() == pd.StylePath.ToLower()) &&
                                           f.OpusPath.StartsWith(pd.ArtistPath))
                                    .OrderBy(f => f.File)
                    ;
                }
            }

            log.Information($"Deleting {musicFileList.Count()} music files");
            var dc = new DeleteContext(taskItem);

            foreach (var mf in musicFileList)
            {
                db.Delete(mf, dc);
            }
            taskItem.Status     = Music.Core.TaskStatus.Finished;
            taskItem.FinishedAt = DateTimeOffset.Now;
            await db.SaveChangesAsync();

            if (dc.DeletedArtistId.HasValue)
            {
                await this.playManager.SendArtistDeleted(dc.DeletedArtistId.Value);
            }
            else if (dc.ModifiedArtistId.HasValue)
            {
                var shouldSend = true;
                var artist     = await db.Artists.FindAsync(dc.ModifiedArtistId.Value);

                if (artist != null)
                {
                    shouldSend = artist.Type != ArtistType.Various;
                }
                if (shouldSend)
                {
                    await this.playManager.SendArtistNewOrModified(dc.ModifiedArtistId.Value);
                }
            }
            //if (dc.DeletedArtistId.HasValue || dc.ModifiedArtistId.HasValue)
            //{
            //    var shouldSend = true;
            //    var id = dc.ModifiedArtistId ?? 0;
            //    if (id > 0)
            //    {
            //        var artist = await db.Artists.FindAsync(id);
            //        shouldSend = artist.Type != ArtistType.Various;
            //    }
            //    if (shouldSend)
            //    {
            //        if (dc.DeletedArtistId.HasValue)
            //        {
            //            await this.playManager.SendArtistDeleted(dc.DeletedArtistId.Value);
            //        }
            //        else if (dc.ModifiedArtistId.HasValue)
            //        {
            //            await this.playManager.SendArtistNewOrModified(dc.ModifiedArtistId.Value);
            //        }
            //    }
            //}
            // send artist modified/deleted - info is in dc
        }
Example #48
0
        // Resolves by looking dependency_search_paths
        // which is dir of parent reference file, and
        // SearchPaths
        ResolvedReference ResolveDependencyByAssemblyName(AssemblyName aname, string parent_asm_name,
                                                          string parent_copy_local)
        {
            // This will check for compatible assembly name/version
            ResolvedReference resolved_ref;

            if (TryGetResolvedReferenceByAssemblyName(aname, false, out resolved_ref))
            {
                return(resolved_ref);
            }

            LogWithPrecedingNewLine(MessageImportance.Low, "Dependency {0}", aname);
            Log.LogMessage(MessageImportance.Low, "\tRequired by {0}", parent_asm_name);

            ITaskItem item = new TaskItem(aname.FullName);

            item.SetMetadata("SpecificVersion", "false");
            resolved_ref = ResolveReference(item, dependency_search_paths, false);

            if (resolved_ref != null)
            {
                if (Environment.GetEnvironmentVariable("XBUILD_LOG_REFERENCE_RESOLVER") != null)
                {
                    assembly_resolver.LogSearchLoggerMessages(MessageImportance.Low);
                }

                Log.LogMessage(MessageImportance.Low, "\tReference {0} resolved to {1}.",
                               aname, resolved_ref.TaskItem.ItemSpec);

                Log.LogMessage(MessageImportance.Low,
                               "\tReference found at search path {0}",
                               resolved_ref.FoundInSearchPathAsString);

                if (resolved_ref.FoundInSearchPath == SearchPath.Directory)
                {
                    // override CopyLocal with parent's val
                    SetCopyLocal(resolved_ref.TaskItem, parent_copy_local);

                    Log.LogMessage(MessageImportance.Low,
                                   "\tThis is CopyLocal {0} as parent item has this value",
                                   parent_copy_local);

                    if (TryAddNewReference(tempResolvedFiles, resolved_ref))
                    {
                        FindAndAddRelatedFiles(resolved_ref.TaskItem.ItemSpec, parent_copy_local);
                        FindAndAddSatellites(resolved_ref.TaskItem.ItemSpec, parent_copy_local);
                    }
                }
                else
                {
                    //gac or tgtfmwk
                    Log.LogMessage(MessageImportance.Low,
                                   "\tThis is CopyLocal false as it is in the gac," +
                                   "target framework directory or provided by a package.");

                    TryAddNewReference(tempResolvedFiles, resolved_ref);
                }
            }
            else
            {
                Log.LogWarning("Reference '{0}' not resolved", aname);
                assembly_resolver.LogSearchLoggerMessages(MessageImportance.Normal);
            }

            return(resolved_ref);
        }
        // get library and file definitions
        private void GetPackageAndFileDefinitions()
        {
            TaskItem item;

            foreach (var package in LockFile.Libraries)
            {
                var    packageName    = package.Name;
                var    packageVersion = package.Version.ToNormalizedString();
                string packageId      = $"{packageName}/{packageVersion}";
                item = new TaskItem(packageId);
                item.SetMetadata(MetadataKeys.Name, packageName);
                item.SetMetadata(MetadataKeys.Type, package.Type);
                item.SetMetadata(MetadataKeys.Version, packageVersion);

                item.SetMetadata(MetadataKeys.Path, package.Path ?? string.Empty);

                string resolvedPackagePath = ResolvePackagePath(package);
                item.SetMetadata(MetadataKeys.ResolvedPath, resolvedPackagePath ?? string.Empty);

                _packageDefinitions.Add(item);

                foreach (var file in package.Files)
                {
                    if (NuGetUtils.IsPlaceholderFile(file))
                    {
                        continue;
                    }

                    var fileKey  = $"{packageId}/{file}";
                    var fileItem = new TaskItem(fileKey);
                    fileItem.SetMetadata(MetadataKeys.Path, file);
                    fileItem.SetMetadata(MetadataKeys.PackageName, packageName);
                    fileItem.SetMetadata(MetadataKeys.PackageVersion, packageVersion);

                    string resolvedPath = ResolveFilePath(file, resolvedPackagePath);
                    fileItem.SetMetadata(MetadataKeys.ResolvedPath, resolvedPath ?? string.Empty);

                    if (NuGetUtils.IsApplicableAnalyzer(file, ProjectLanguage))
                    {
                        fileItem.SetMetadata(MetadataKeys.Analyzer, "true");
                        fileItem.SetMetadata(MetadataKeys.Type, "AnalyzerAssembly");

                        // get targets that contain this package
                        var parentTargets = LockFile.Targets
                                            .Where(t => t.Libraries.Any(lib => lib.Name == package.Name));

                        foreach (var target in parentTargets)
                        {
                            var fileDepsItem = new TaskItem(fileKey);
                            fileDepsItem.SetMetadata(MetadataKeys.ParentTarget, target.Name); // Foreign Key
                            fileDepsItem.SetMetadata(MetadataKeys.ParentPackage, packageId);  // Foreign Key

                            _fileDependencies.Add(fileDepsItem);
                        }
                    }
                    else
                    {
                        // get a type for the file if one is available
                        string fileType;
                        if (!_fileTypes.TryGetValue(fileKey, out fileType))
                        {
                            fileType = "unknown";
                        }
                        fileItem.SetMetadata(MetadataKeys.Type, fileType);
                    }

                    _fileDefinitions.Add(fileItem);
                }
            }
        }
Example #50
0
        private void ProcessInputFileList(
            ITaskItem[] inputFiles,
            List <ITaskItem> imageCompilationList,
            List <ITaskItem> symbolsCompilationList,
            List <ITaskItem> r2rFilesPublishList,
            List <ITaskItem> r2rReferenceList,
            List <ITaskItem> r2rCompositeReferenceList,
            List <ITaskItem> r2rCompositeInputList,
            bool hasValidDiaSymReaderLib)
        {
            if (inputFiles == null)
            {
                return;
            }

            var exclusionSet          = ExcludeList == null || Crossgen2Composite ? null : new HashSet <string>(ExcludeList, StringComparer.OrdinalIgnoreCase);
            var compositeExclusionSet = PublishReadyToRunCompositeExclusions == null || !Crossgen2Composite ? null : new HashSet <string>(PublishReadyToRunCompositeExclusions, StringComparer.OrdinalIgnoreCase);

            foreach (var file in inputFiles)
            {
                var eligibility = GetInputFileEligibility(file, Crossgen2Composite, exclusionSet, compositeExclusionSet);

                if (eligibility.NoEligibility)
                {
                    continue;
                }

                if (eligibility.IsReference)
                {
                    r2rReferenceList.Add(file);
                }

                if (eligibility.IsReference && !eligibility.ReferenceHiddenFromCompositeBuild && !eligibility.Compile)
                {
                    r2rCompositeReferenceList.Add(file);
                }

                if (!eligibility.Compile)
                {
                    continue;
                }

                var outputR2RImageRelativePath = file.GetMetadata(MetadataKeys.RelativePath);
                var outputR2RImage             = Path.Combine(OutputPath, outputR2RImageRelativePath);

                string outputPDBImage             = null;
                string outputPDBImageRelativePath = null;
                string crossgen1CreatePDBCommand  = null;

                if (EmitSymbols)
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && hasValidDiaSymReaderLib)
                    {
                        outputPDBImage             = Path.ChangeExtension(outputR2RImage, "ni.pdb");
                        outputPDBImageRelativePath = Path.ChangeExtension(outputR2RImageRelativePath, "ni.pdb");
                        crossgen1CreatePDBCommand  = $"/CreatePDB \"{Path.GetDirectoryName(outputPDBImage)}\"";
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        using (FileStream fs = new FileStream(file.ItemSpec, FileMode.Open, FileAccess.Read))
                        {
                            PEReader       pereader = new PEReader(fs);
                            MetadataReader mdReader = pereader.GetMetadataReader();
                            Guid           mvid     = mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid);

                            outputPDBImage             = Path.ChangeExtension(outputR2RImage, "ni.{" + mvid + "}.map");
                            outputPDBImageRelativePath = Path.ChangeExtension(outputR2RImageRelativePath, "ni.{" + mvid + "}.map");
                            crossgen1CreatePDBCommand  = $"/CreatePerfMap \"{Path.GetDirectoryName(outputPDBImage)}\"";
                        }
                    }
                }

                if (eligibility.CompileSeparately)
                {
                    // This TaskItem is the IL->R2R entry, for an input assembly that needs to be compiled into a R2R image. This will be used as
                    // an input to the ReadyToRunCompiler task
                    TaskItem r2rCompilationEntry = new TaskItem(file);
                    r2rCompilationEntry.SetMetadata(MetadataKeys.OutputR2RImage, outputR2RImage);
                    if (outputPDBImage != null && ReadyToRunUseCrossgen2 && !_crossgen2IsVersion5)
                    {
                        r2rCompilationEntry.SetMetadata(MetadataKeys.EmitSymbols, "true");
                        r2rCompilationEntry.SetMetadata(MetadataKeys.OutputPDBImage, outputPDBImage);
                    }
                    r2rCompilationEntry.RemoveMetadata(MetadataKeys.OriginalItemSpec);
                    imageCompilationList.Add(r2rCompilationEntry);
                }
                else if (eligibility.CompileIntoCompositeImage)
                {
                    r2rCompositeInputList.Add(file);
                }

                // This TaskItem corresponds to the output R2R image. It is equivalent to the input TaskItem, only the ItemSpec for it points to the new path
                // for the newly created R2R image
                TaskItem r2rFileToPublish = new TaskItem(file);
                r2rFileToPublish.ItemSpec = outputR2RImage;
                r2rFileToPublish.RemoveMetadata(MetadataKeys.OriginalItemSpec);
                r2rFilesPublishList.Add(r2rFileToPublish);

                // Note: ReadyToRun PDB/Map files are not needed for debugging. They are only used for profiling, therefore the default behavior is to not generate them
                // unless an explicit PublishReadyToRunEmitSymbols flag is enabled by the app developer. There is also another way to profile that the runtime supports, which does
                // not rely on the native PDBs/Map files, so creating them is really an opt-in option, typically used by advanced users.
                // For debugging, only the IL PDBs are required.
                if (eligibility.CompileSeparately && outputPDBImage != null)
                {
                    if (!ReadyToRunUseCrossgen2 || _crossgen2IsVersion5)
                    {
                        // This TaskItem is the R2R->R2RPDB entry, for a R2R image that was just created, and for which we need to create native PDBs. This will be used as
                        // an input to the ReadyToRunCompiler task
                        TaskItem pdbCompilationEntry = new TaskItem(file);
                        pdbCompilationEntry.ItemSpec = outputR2RImage;
                        pdbCompilationEntry.SetMetadata(MetadataKeys.OutputPDBImage, outputPDBImage);
                        pdbCompilationEntry.SetMetadata(MetadataKeys.CreatePDBCommand, crossgen1CreatePDBCommand);
                        symbolsCompilationList.Add(pdbCompilationEntry);
                    }

                    // This TaskItem corresponds to the output PDB image. It is equivalent to the input TaskItem, only the ItemSpec for it points to the new path
                    // for the newly created PDB image.
                    TaskItem r2rSymbolsFileToPublish = new TaskItem(file);
                    r2rSymbolsFileToPublish.ItemSpec = outputPDBImage;
                    r2rSymbolsFileToPublish.SetMetadata(MetadataKeys.RelativePath, outputPDBImageRelativePath);
                    r2rSymbolsFileToPublish.RemoveMetadata(MetadataKeys.OriginalItemSpec);
                    if (!IncludeSymbolsInSingleFile)
                    {
                        r2rSymbolsFileToPublish.SetMetadata(MetadataKeys.ExcludeFromSingleFile, "true");
                    }

                    r2rFilesPublishList.Add(r2rSymbolsFileToPublish);
                }
            }

            if (Crossgen2Composite)
            {
                MainAssembly.SetMetadata(MetadataKeys.RelativePath, Path.GetFileName(MainAssembly.ItemSpec));

                var compositeR2RImageRelativePath = MainAssembly.GetMetadata(MetadataKeys.RelativePath);
                compositeR2RImageRelativePath = Path.ChangeExtension(compositeR2RImageRelativePath, "r2r" + Path.GetExtension(compositeR2RImageRelativePath));
                var compositeR2RImage = Path.Combine(OutputPath, compositeR2RImageRelativePath);

                TaskItem r2rCompilationEntry = new TaskItem(MainAssembly);
                r2rCompilationEntry.ItemSpec = r2rCompositeInputList[0].ItemSpec;
                r2rCompilationEntry.SetMetadata(MetadataKeys.OutputR2RImage, compositeR2RImage);
                r2rCompilationEntry.SetMetadata(MetadataKeys.CreateCompositeImage, "true");
                r2rCompilationEntry.RemoveMetadata(MetadataKeys.OriginalItemSpec);

                if (EmitSymbols)
                {
                    string compositePDBImage        = null;
                    string compositePDBRelativePath = null;
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && hasValidDiaSymReaderLib)
                    {
                        compositePDBImage        = Path.ChangeExtension(compositeR2RImage, ".ni.pdb");
                        compositePDBRelativePath = Path.ChangeExtension(compositeR2RImageRelativePath, ".ni.pdb");
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        compositePDBImage        = Path.ChangeExtension(compositeR2RImage, ".ni.{composite}.map");
                        compositePDBRelativePath = Path.ChangeExtension(compositeR2RImageRelativePath, ".ni.{composite}.map");
                    }

                    if (compositePDBImage != null && ReadyToRunUseCrossgen2 && !_crossgen2IsVersion5)
                    {
                        r2rCompilationEntry.SetMetadata(MetadataKeys.EmitSymbols, "true");
                        r2rCompilationEntry.SetMetadata(MetadataKeys.OutputPDBImage, compositePDBImage);

                        // Publish composite PDB file
                        TaskItem r2rSymbolsFileToPublish = new TaskItem(MainAssembly);
                        r2rSymbolsFileToPublish.ItemSpec = compositePDBImage;
                        r2rSymbolsFileToPublish.SetMetadata(MetadataKeys.RelativePath, compositePDBRelativePath);
                        r2rSymbolsFileToPublish.RemoveMetadata(MetadataKeys.OriginalItemSpec);
                        if (!IncludeSymbolsInSingleFile)
                        {
                            r2rSymbolsFileToPublish.SetMetadata(MetadataKeys.ExcludeFromSingleFile, "true");
                        }

                        r2rFilesPublishList.Add(r2rSymbolsFileToPublish);
                    }
                }

                imageCompilationList.Add(r2rCompilationEntry);

                // Publish it
                TaskItem compositeR2RFileToPublish = new TaskItem(MainAssembly);
                compositeR2RFileToPublish.ItemSpec = compositeR2RImage;
                compositeR2RFileToPublish.RemoveMetadata(MetadataKeys.OriginalItemSpec);
                compositeR2RFileToPublish.SetMetadata(MetadataKeys.RelativePath, compositeR2RImageRelativePath);
                r2rFilesPublishList.Add(compositeR2RFileToPublish);
            }
        }
Example #51
0
        /// <summary>
        /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
        /// </summary>
        protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
        {
            // If outputAssembly is not specified, then an "/out: <name>" option won't be added to
            // overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
            // In that case, we should set the outputAssembly member based on the first source file.
            if (
                (OutputAssembly == null) &&
                (Sources != null) &&
                (Sources.Length > 0) &&
                (this.ResponseFiles == null)        // The response file may already have a /out: switch in it, so don't try to be smart here.
                )
            {
                try
                {
                    OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
                }
                catch (ArgumentException e)
                {
                    throw new ArgumentException(e.Message, "Sources");
                }
                if (String.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    OutputAssembly.ItemSpec += ".dll";
                }
                else if (String.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    OutputAssembly.ItemSpec += ".netmodule";
                }
                else
                {
                    OutputAssembly.ItemSpec += ".exe";
                }
            }

            commandLine.AppendSwitchIfNotNull("/addmodule:", this.AddModules, ",");
            commandLine.AppendSwitchWithInteger("/codepage:", this._store, "CodePage");

            ConfigureDebugProperties();

            // The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
            // because it's more specific.  Order matters on the command-line, and the last one wins.
            // /debug+ is just a shorthand for /debug:full.  And /debug- is just a shorthand for /debug:none.

            commandLine.AppendPlusOrMinusSwitch("/debug", this._store, "EmitDebugInformation");
            commandLine.AppendSwitchIfNotNull("/debug:", this.DebugType);

            commandLine.AppendPlusOrMinusSwitch("/delaysign", this._store, "DelaySign");

            commandLine.AppendSwitchWithInteger("/filealign:", this._store, "FileAlignment");
            commandLine.AppendSwitchIfNotNull("/keycontainer:", this.KeyContainer);
            commandLine.AppendSwitchIfNotNull("/keyfile:", this.KeyFile);
            // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
            commandLine.AppendSwitchIfNotNull("/linkresource:", this.LinkResources, new string[] { "LogicalName", "Access" });
            commandLine.AppendWhenTrue("/nologo", this._store, "NoLogo");
            commandLine.AppendWhenTrue("/nowin32manifest", this._store, "NoWin32Manifest");
            commandLine.AppendPlusOrMinusSwitch("/optimize", this._store, "Optimize");
            commandLine.AppendSwitchIfNotNull("/out:", this.OutputAssembly);
            commandLine.AppendSwitchIfNotNull("/ruleset:", this.CodeAnalysisRuleSet);
            commandLine.AppendSwitchIfNotNull("/errorlog:", this.ErrorLog);
            commandLine.AppendSwitchIfNotNull("/subsystemversion:", this.SubsystemVersion);
            // TODO: uncomment the below line once "/reportanalyzer" switch is added to compiler.
            //commandLine.AppendWhenTrue("/reportanalyzer", this._store, "ReportAnalyzer");
            // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
            commandLine.AppendSwitchIfNotNull("/resource:", this.Resources, new string[] { "LogicalName", "Access" });
            commandLine.AppendSwitchIfNotNull("/target:", this.TargetType);
            commandLine.AppendPlusOrMinusSwitch("/warnaserror", this._store, "TreatWarningsAsErrors");
            commandLine.AppendWhenTrue("/utf8output", this._store, "Utf8Output");
            commandLine.AppendSwitchIfNotNull("/win32icon:", this.Win32Icon);
            commandLine.AppendSwitchIfNotNull("/win32manifest:", this.Win32Manifest);

            // Append the analyzers.
            this.AddAnalyzersToCommandLine(commandLine);

            // Append additional files.
            this.AddAdditionalFilesToCommandLine(commandLine);

            // Append the sources.
            commandLine.AppendFileNamesIfNotNull(Sources, " ");
        }
Example #52
0
 // PUT api/task/5
 public void UpdateTask(int id, [FromBody] TaskItem taskItem)
 {
     _taskService.Update(taskItem);
 }
Example #53
0
        public override bool Execute()
        {
            if (NativeReferences == null || NativeReferences.Length == 0)
            {
                return(!Log.HasLoggedErrors);
            }

            var embeddedResources = new List <ITaskItem> ();
            var nativeFrameworks  = new List <ITaskItem> ();
            var text = new StringBuilder();

            for (int i = 0; i < NativeReferences.Length; i++)
            {
                NativeReferenceKind kind;
                string value;

                value = NativeReferences[i].GetMetadata("Kind") ?? string.Empty;
                if (!Enum.TryParse(value, out kind))
                {
                    Log.LogError(null, null, null, NativeReferences[i].ItemSpec, 0, 0, 0, 0, MSBStrings.W0051, value);
                    continue;
                }

                var path        = NativeReferences[i].ItemSpec;
                var logicalName = Path.GetFileName(path);

                var item = new TaskItem(path);

                if (kind == NativeReferenceKind.Framework)
                {
                    nativeFrameworks.Add(item);
                }
                else
                {
                    item.SetMetadata("LogicalName", logicalName);
                    item.SetMetadata("WithCulture", "false");
                    item.SetMetadata("Type", "Non-Resx");
                    embeddedResources.Add(item);
                }

                text.AppendFormat("[assembly: ObjCRuntime.LinkWith (\"{0}\"", logicalName);
                AppendLinkTargetProperty(text, NativeReferences[i]);
                AppendBooleanProperty(text, NativeReferences[i], "IsCxx");
                AppendBooleanProperty(text, NativeReferences[i], "NeedsGccExceptionHandling");
                AppendBooleanProperty(text, NativeReferences[i], "SmartLink", true);
                AppendBooleanProperty(text, NativeReferences[i], "ForceLoad");
                AppendStringProperty(text, NativeReferences[i], "Frameworks");
                AppendStringProperty(text, NativeReferences[i], "WeakFrameworks");
                AppendStringProperty(text, NativeReferences[i], "LinkerFlags");
                text.Append(")]");
                text.AppendLine();
            }

            bool   skipLinkWithGeneration = false;
            string linkWithText           = text.ToString();
            var    linkWithPath           = Path.Combine(IntermediateOutputPath, "LinkWithAttributes.cs");

            if (File.Exists(linkWithPath))
            {
                string existingLinkWithText = File.ReadAllText(linkWithPath);
                skipLinkWithGeneration = String.Equals(existingLinkWithText, linkWithText, StringComparison.Ordinal);
            }
            if (!skipLinkWithGeneration)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(linkWithPath));
                File.WriteAllText(linkWithPath, linkWithText);
            }

            EmbeddedResources  = embeddedResources.ToArray();
            NativeFrameworks   = nativeFrameworks.ToArray();
            LinkWithAttributes = new TaskItem(linkWithPath);

            return(!Log.HasLoggedErrors);
        }
 public TaskItemWrapper(TaskItem inner, LoadTaskItemDelegate load)
 {
     _load  = load;
     _inner = inner;
 }
 /// <summary>
 /// </summary>
 /// <param name="id"></param>
 /// <param name="taskItem"></param>
 /// <returns>
 /// </returns>
 private ReminderTask GetTaskFromItem(string id, TaskItem taskItem)
 {
     var reminderTask = new ReminderTask(taskItem.EntryID,taskItem.Subject,taskItem.Body, taskItem.DueDate);
     reminderTask.IsCompleted = taskItem.Complete;
     reminderTask.CreatedOn = taskItem.CreationTime;
     reminderTask.UpdatedOn = taskItem.LastModificationTime;
     reminderTask.CompletedOn = taskItem.DateCompleted;
     reminderTask.StartDate = taskItem.StartDate;
     reminderTask.StatusEnum = taskItem.GetTaskStatus();
     return reminderTask;
 }
 private void DisposeInner()
 {
     Marshal.FinalReleaseComObject(Inner);
     _inner = null;
 }
Example #57
0
		internal ITaskItem ConvertToITaskItem (Expression transform, ExpressionOptions options)
		{
			TaskItem taskItem;
			taskItem = new TaskItem (GetItemSpecFromTransform (transform, options), evaluatedMetadata);
			return taskItem;
		}
Example #58
0
        protected override void ExecuteCore()
        {
            //  Perf optimization: If there are no FrameworkReference items, then don't do anything
            //  (This means that if you don't have any direct framework references, you won't get any transitive ones either
            if (FrameworkReferences == null || FrameworkReferences.Length == 0)
            {
                return;
            }

            var normalizedTargetFrameworkVersion = NormalizeVersion(new Version(TargetFrameworkVersion));

            var knownFrameworkReferencesForTargetFramework = KnownFrameworkReferences.Select(item => new KnownFrameworkReference(item))
                                                             .Where(kfr => kfr.TargetFramework.Framework.Equals(TargetFrameworkIdentifier, StringComparison.OrdinalIgnoreCase) &&
                                                                    NormalizeVersion(kfr.TargetFramework.Version) == normalizedTargetFrameworkVersion)
                                                             .ToList();

            var frameworkReferenceMap = FrameworkReferences.ToDictionary(fr => fr.ItemSpec, StringComparer.OrdinalIgnoreCase);

            List <ITaskItem> packagesToDownload      = new List <ITaskItem>();
            List <ITaskItem> runtimeFrameworks       = new List <ITaskItem>();
            List <ITaskItem> targetingPacks          = new List <ITaskItem>();
            List <ITaskItem> runtimePacks            = new List <ITaskItem>();
            List <ITaskItem> unavailableRuntimePacks = new List <ITaskItem>();

            HashSet <string> unrecognizedRuntimeIdentifiers = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            bool windowsOnlyErrorLogged = false;

            foreach (var knownFrameworkReference in knownFrameworkReferencesForTargetFramework)
            {
                frameworkReferenceMap.TryGetValue(knownFrameworkReference.Name, out ITaskItem frameworkReference);

                // Handle Windows-only frameworks on non-Windows platforms
                if (knownFrameworkReference.IsWindowsOnly &&
                    !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // It is an error to reference the framework from non-Windows
                    if (!windowsOnlyErrorLogged && frameworkReference != null)
                    {
                        Log.LogError(Strings.WindowsDesktopFrameworkRequiresWindows);
                        windowsOnlyErrorLogged = true;
                    }

                    // Ignore (and don't download) this known framework reference as it requires Windows
                    continue;
                }

                List <string> preferredPackages = new List <string>();
                preferredPackages.Add(knownFrameworkReference.TargetingPackName);

                var knownFrameworkReferenceRuntimePackRuntimeIdentifiers = knownFrameworkReference.RuntimePackRuntimeIdentifiers.Split(';');
                foreach (var runtimeIdentifier in knownFrameworkReferenceRuntimePackRuntimeIdentifiers)
                {
                    foreach (var runtimePackNamePattern in knownFrameworkReference.RuntimePackNamePatterns.Split(';'))
                    {
                        string runtimePackName = runtimePackNamePattern.Replace("**RID**", runtimeIdentifier);
                        preferredPackages.Add(runtimePackName);
                    }
                }

                //  Get the path of the targeting pack in the targeting pack root (e.g. dotnet/ref)
                TaskItem targetingPack = new TaskItem(knownFrameworkReference.Name);
                targetingPack.SetMetadata(MetadataKeys.PackageName, knownFrameworkReference.TargetingPackName);
                targetingPack.SetMetadata(MetadataKeys.PackageConflictPreferredPackages, string.Join(";", preferredPackages));

                string targetingPackVersion = null;
                if (frameworkReference != null)
                {
                    //  Allow targeting pack version to be overridden via metadata on FrameworkReference
                    targetingPackVersion = frameworkReference.GetMetadata("TargetingPackVersion");
                }
                if (string.IsNullOrEmpty(targetingPackVersion))
                {
                    targetingPackVersion = knownFrameworkReference.TargetingPackVersion;
                }
                targetingPack.SetMetadata(MetadataKeys.PackageVersion, targetingPackVersion);
                targetingPack.SetMetadata("TargetingPackFormat", knownFrameworkReference.TargetingPackFormat);
                targetingPack.SetMetadata("TargetFramework", knownFrameworkReference.TargetFramework.GetShortFolderName());
                targetingPack.SetMetadata(MetadataKeys.RuntimeFrameworkName, knownFrameworkReference.RuntimeFrameworkName);
                targetingPack.SetMetadata(MetadataKeys.RuntimePackRuntimeIdentifiers, knownFrameworkReference.RuntimePackRuntimeIdentifiers);

                if (!string.IsNullOrEmpty(knownFrameworkReference.Profile))
                {
                    targetingPack.SetMetadata("Profile", knownFrameworkReference.Profile);
                }

                string targetingPackPath = null;
                if (!string.IsNullOrEmpty(TargetingPackRoot))
                {
                    targetingPackPath = Path.Combine(TargetingPackRoot, knownFrameworkReference.TargetingPackName, targetingPackVersion);
                }
                if (targetingPackPath != null && Directory.Exists(targetingPackPath))
                {
                    // Use targeting pack from packs folder
                    targetingPack.SetMetadata(MetadataKeys.PackageDirectory, targetingPackPath);
                    targetingPack.SetMetadata(MetadataKeys.Path, targetingPackPath);
                }
                else
                {
                    if (EnableTargetingPackDownload)
                    {
                        //  Download targeting pack
                        TaskItem packageToDownload = new TaskItem(knownFrameworkReference.TargetingPackName);
                        packageToDownload.SetMetadata(MetadataKeys.Version, targetingPackVersion);

                        packagesToDownload.Add(packageToDownload);
                    }
                }

                targetingPacks.Add(targetingPack);

                var runtimeFrameworkVersion = GetRuntimeFrameworkVersion(
                    frameworkReference,
                    knownFrameworkReference,
                    out string runtimePackVersion);

                string isTrimmable = null;
                if (frameworkReference != null)
                {
                    // Allow IsTrimmable to be overridden via metadata on FrameworkReference
                    isTrimmable = frameworkReference.GetMetadata(MetadataKeys.IsTrimmable);
                }
                if (string.IsNullOrEmpty(isTrimmable))
                {
                    isTrimmable = knownFrameworkReference.IsTrimmable;
                }

                bool processedPrimaryRuntimeIdentifier = false;

                if ((SelfContained || ReadyToRunEnabled) &&
                    !string.IsNullOrEmpty(RuntimeIdentifier) &&
                    !string.IsNullOrEmpty(knownFrameworkReference.RuntimePackNamePatterns))
                {
                    ProcessRuntimeIdentifier(RuntimeIdentifier, knownFrameworkReference, runtimePackVersion,
                                             unrecognizedRuntimeIdentifiers, unavailableRuntimePacks, runtimePacks, packagesToDownload, isTrimmable);

                    processedPrimaryRuntimeIdentifier = true;
                }

                if (RuntimeIdentifiers != null)
                {
                    foreach (var runtimeIdentifier in RuntimeIdentifiers)
                    {
                        if (processedPrimaryRuntimeIdentifier && runtimeIdentifier == this.RuntimeIdentifier)
                        {
                            //  We've already processed this RID
                            continue;
                        }

                        //  Pass in null for the runtimePacks list, as for these runtime identifiers we only want to
                        //  download the runtime packs, but not use the assets from them
                        ProcessRuntimeIdentifier(runtimeIdentifier, knownFrameworkReference, runtimePackVersion,
                                                 unrecognizedRuntimeIdentifiers, unavailableRuntimePacks, runtimePacks: null, packagesToDownload, isTrimmable);
                    }
                }

                if (!string.IsNullOrEmpty(knownFrameworkReference.RuntimeFrameworkName))
                {
                    TaskItem runtimeFramework = new TaskItem(knownFrameworkReference.RuntimeFrameworkName);

                    runtimeFramework.SetMetadata(MetadataKeys.Version, runtimeFrameworkVersion);
                    runtimeFramework.SetMetadata(MetadataKeys.FrameworkName, knownFrameworkReference.Name);

                    runtimeFrameworks.Add(runtimeFramework);
                }
            }

            if (packagesToDownload.Any())
            {
                PackagesToDownload = packagesToDownload.ToArray();
            }

            if (runtimeFrameworks.Any())
            {
                RuntimeFrameworks = runtimeFrameworks.ToArray();
            }

            if (targetingPacks.Any())
            {
                TargetingPacks = targetingPacks.ToArray();
            }

            if (runtimePacks.Any())
            {
                RuntimePacks = runtimePacks.ToArray();
            }

            if (unavailableRuntimePacks.Any())
            {
                UnavailableRuntimePacks = unavailableRuntimePacks.ToArray();
            }
        }
Example #59
0
		internal ITaskItem[] ConvertToITaskItemArray (Project project, ExpressionOptions options)
		{
			if (converting) {
				// found ref to @this while trying to ConvertToITaskItemArray
				// for @this!
				ITaskItem []items = new ITaskItem [1];
				items [0] = new TaskItem (FinalValue);
				return items;
			}

			converting = true;
			try {
				Expression exp = new Expression ();

				// in non-evaluation phase, properties are always expanded
				exp.Parse (FinalValue, ParseOptions.Split | (options == ExpressionOptions.ExpandItemRefs ?
							ParseOptions.AllowItems : ParseOptions.None));
				return (ITaskItem[]) exp.ConvertTo (project, typeof (ITaskItem[]), options);
			} finally {
				converting = false;
			}
		}
Example #60
0
 public async Task UpdateTaskItem(TaskItem taskItem)
 {
     _db.Entry(taskItem).State = EntityState.Modified;
     await SaveAsync();
 }