specify build action of content - Nuget - c#

What is the simplest way to tell Nuget package to add all css files as an embedded resource (ie build action is embedded resource).
I am trying to do it through install.ps1 in the tools folder but still cant get anywhere
Note: I am creating the package from the directory structure(tools\content\lib)
This is my install.ps1 which does not work.
param($installPath, $toolsPath, $package, $project)
$MsbNS = #{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'}
function EmbeddContent($ProjectLink, [string]$XPath)
{
$nodes = #(Select-Xml $XPath $ProjectLink -Namespace $MsbNS | Foreach {$_.Node})
foreach ($node in $nodes)
{
if($node.Include.StartsWith("Content\css"))
{
$cet = $node.ownerdocument.CreateElement("EmbeddedResource")
$cet.setAttribute("Include", $node.Include)
$parent = $node.ParentNode
[void]$parent.RemoveChild($node)
[void]$parent.Appendchild($cet)
}
}
}
$project.Save()
$fileLocation = $project.FileName
$dte.ExecuteCommand("Project.UnloadProject");
$proj = [xml](gc $fileLocation)
Embeddcontent $fileLocation '//msb:Project/msb:ItemGroup/msb:Content'
$proj.Save($fileLocation)
Help Please ..

You can use DTE instead of messing with xml to change the BuildAction. From http://nuget.codeplex.com/discussions/227696:
$item = $project.ProjectItems | where-object {$_.Name -eq "ReleaseNotes.txt"}
$item.Properties.Item("BuildAction").Value = [int]3
This link shows the enumeration values:
http://msdn.microsoft.com/en-us/library/aa983962(VS.71).aspx

Related

How to get Build Id from tfs during the build in C#

To get a log link i need the id of current build, I tried to use this in my C# code, but it didn't return Build Id:
var envVars;
envVars = Environment.GetEnvironmentVariables();
To get the Build.Id during the build with C# you can sue this line:
string buildId = Environment.GetEnvironmentVariable("Build_BuildId",Environment.VariableTarget.Process);
You can get the build Id from this variable
$(Build.BuildId)
Pass it as parameter(exactly as it written here) to the tool(console app?) that you are building.
You can check other variables from this link
https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
The solution is to put this var in txt file via PowerShell script, and than get it by C#
PS:
if(!(Test-Path -Path C:\BuildVariables)){
New-Item -ItemType directory -Path C:\BuildVariables
}
Out-File -FilePath C:\BuildVariables\buildId.txt -Force -InputObject $(Build.Buildid)
C#:
public static string ShowEnvironmentVariables()
{
string var = File.ReadAllText("C:\\BuildVariables\\buildId.txt");
return var;
}

Cannot Associate Test Case in Visual Studio

I have a standard MSTest unit test in a unit test C# project file. The project is running .NET Framework 4.7.2, and has version 1.3.2 of the MSTest adapter and framework installed. I am running Visual Studio 2017 Enterprise 15.7.6, and have a VSTS workspace with some random manually-created test cases in it.
When I right-click on my unit test in the Test Explorer, and select "Associate to Test Case", I am able to enter the test case ID, add the association, and click "Save". Upon save, I get an error message, below.
I have tried to save the association using different versions of MSTest, and different .NET Framework versions for the project file, neither of which solved the issue. I also tried running Visual Studio as an administrator, which did not work. Has anyone else had this issue, or know of any workarounds?
I test it in my side using two VS2017 versions, they all works well.
For example, I add a simple test case manually in one test plan in VSTS, and then I create a simple unit test project with .net 4.7.2 in my side using VS2017 15.7.6, I could a associate to Test Case in my side.
If possible, you could test it in your side with the following steps:
(1) Test it with other VS machines(The same VS version but not in the same machine if you have).
(2) Clean the VSTS cache. Clean and rebuild your test project in solution explorer window, test it again.
(3) Tools->Options->Work Items, select "Visual Studio(Compatibility mode)" there.
(4) If still no help, add a new test simple unit test project in your VS, uremove the nuget packages: MSTest.TestAdapter and MSTest.TestFramework, and then add a local reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework, view the result again.
Update:
I update my VS2017 to the 15.8.1 version, I got the same issue, that option was disable in default. It would be a real feedback.
https://developercommunity.visualstudio.com/content/problem/309413/cannot-associate-test-case-in-visual-studio.html?childToView=311392#comment-311392
Other members who get the same issue could vote it.
A work around I put together and now use exclusively instead of manual association is to supply the test case id in the test method name and automatically update the case in TFS via the rest API by adding the following PowerShell script to run on a successful build in TFS.
A GUID for each test is generated using the full namespace for the test method and needs to be added to "/fields/Microsoft.VSTS.TCM.AutomatedTestId"
This would need adjusted to your own TFS authentication methods and possibly TFS version (I'm using 2017.2) along with the type of tests you need to read in. This is supporting Coded UI and xUnit. The LoadFrom at the top can be removed if you are not using Coded UI at all.
param (
[string]$Dll = $(throw "-path to test Dll is required.")
)
Write-Warning "$Dll will be locked until this powershell session closes"
#Load for CodedUi Support
[Reflection.Assembly]::LoadFrom(("C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.TestTools.UITesting.dll"))
[Reflection.Assembly]::LoadFrom(("C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"))
try {
$tests = ([Reflection.Assembly]::LoadFrom(($Dll)).GetTypes().GetMethods() | Where-Object { $_.GetCustomAttributes($false) | Where-Object {$_.TypeId.Name -icontains 'TestMethodAttribute' -or $_.TypeId.Name -icontains 'FactAttribute' -or $_.TypeId.Name -icontains 'SkippableFactAttribute' -or $_.TypeId.Name -icontains 'TheoryAttribute'}} | ForEach-Object { #{ Class = $_.DeclaringType.Name; Name = $_.Name; FullName = $_.DeclaringType.FullName + "." + $_.Name; }})
}
catch {
Write-Error "Could not load or read $dll" -ErrorAction Stop
}
foreach ($test in $tests)
{
$sha1 = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider;
$nameHash = $sha1.ComputeHash([System.Text.Encoding]::Unicode.GetBytes($test.FullName));
[byte[]]$toGuid = [System.Byte[]]::CreateInstance([System.Byte],16);
[System.Array]::Copy($nameHash, $toGuid, 16);
$guid = [guid]::new($toGuid);
$id = ([Regex]::Match($test.Name, "(\d+)(?!.*\d)").Value)
try {
if ($psversiontable.PSVersion.Major -lt 6) {
$currentGUID = (Invoke-RestMethod "http://{instance}[/{team-project}]/_apis/wit/workitems/$($id)?api-version=3.0-preview" -Method Get -UseBasicParsing -UseDefaultCredentials).Fields.'Microsoft.VSTS.TCM.AutomatedTestId'
}
else {
$currentGUID = (Invoke-RestMethod "http://{instance}[/{team-project}]/_apis/wit/workitems/$($id)?api-version=3.0-preview" -Method Get -UseBasicParsing -UseDefaultCredentials -AllowUnencryptedAuthentication).Fields.'Microsoft.VSTS.TCM.AutomatedTestId'
}
}
catch {
$currentGUID = $null;
}
if($currentGUID -ne $guid)
{
Write-Host "Updating $id."
[array]$hash = #{
op = "add";
path = "/fields/Microsoft.VSTS.TCM.AutomatedTestName";
from = $null;
value = $test.FullName;
},#{
op = "add";
path = "/fields/Microsoft.VSTS.TCM.AutomatedTestStorage";
from = $null;
value = (Split-Path $DLL -leaf);
},#{
op = "add";
path = "/fields/Microsoft.VSTS.TCM.AutomatedTestId";
from = $null;
value = $guid;
},#{
op = "add";
path = "/fields/Microsoft.VSTS.TCM.AutomationStatus";
from = $null;
value = "Automated";
},#{
op = "add";
path = "/fields/System.Reason";
from = $null;
value = "Completed";
},#{
op = "add";
path = "/fields/System.State";
from = $null;
value = "Ready";
}
$patch = Convertto-json $hash -Compress
write-host $test.Name
write-host "http://{instance}[/{team-project}]/_apis/wit/workitems/$($id)?api-version=3.0-preview"
if ($psversiontable.PSVersion.Major -lt 6) {
$result = Invoke-RestMethod "http://{instance}[/{team-project}]/_apis/wit/workitems/$($id)?api-version=3.0-preview" -Method Patch -UseBasicParsing -UseDefaultCredentials -Body $patch -ContentType "application/json-patch+json"
}
else {
$result = Invoke-RestMethod "http://{instance}[/{team-project}]/_apis/wit/workitems/$($id)?api-version=3.0-preview" -Method Patch -UseBasicParsing -UseDefaultCredentials -Body $patch -ContentType "application/json-patch+json" -AllowUnencryptedAuthentication
}
}
else {
Write-Host "No changes to $id."
}
}

Get commands behind windows explorer context menu verbs

I would like to get the list of windows explorer context menu entitites (verbs) and commands behind it. Something like this:
Open with notepad++ | C:\Program Files\NOtepad++\NppShell_06.dll
Add to archive | C:\Program Files\WinRAR\rarext.dll
Play with VLC | "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"
--started-from-file --no-playlist-enqueue "%1"
and so on.
I've wrote PS script to get all commands from context menu (all the same I can do via C#):
$ErrorActionPreference= 'silentlycontinue'
Set-Location -LiteralPath HKLM:\SOFTWARE\Classes\*\shellex\ContextMenuHandlers;
$o = Get-ChildItem -LiteralPath HKLM:\SOFTWARE\Classes\*\shellex\ContextMenuHandlers;
foreach($obj in $o)
{
$prop = (Get-ItemProperty $obj.PSChildName).'(default)';
"-------------------------------------------------------------";
try
{
$obj.PSChildName;
$sub = (Get-Item -LiteralPath ("HKLM:\SOFTWARE\Classes\CLSID\" + $prop.ToString())).GetSubKeyNames();
foreach($s in $sub)
{
(Get-ItemProperty -LiteralPath ("HKLM:\SOFTWARE\Classes\CLSID\" + $prop.ToString() + "\" + $s)).'(default)';
}
}
catch
{}
}
Output:
-------------------------------------------------------------
ANotepad++64
C:\Program Files\Notepad++\NppShell_06.dll
-------------------------------------------------------------
EPP
C:\Program Files\Windows Defender\shellext.dll
10.0.14393.1198
-------------------------------------------------------------
Open With
C:\Windows\system32\shell32.dll
-------------------------------------------------------------
WinRAR
C:\Program Files\WinRAR\rarext.dll
........
There is script to get verbs for specific file:
$o = new-object -com Shell.Application
$folder = $o.NameSpace("C:\Users\User\Documents")
$file=$folder.ParseName("file.txt")
$file.Verbs() | select *
Output:
Application Parent Name
&Open
&Print
&Edit
Edit with &Notepad++
Check with Windows Defender...
&Add to archive...
Add &to "file.rar"
Compress and email...
Compress to "file.rar" and email
.....
So, I do not know how to combine these solutions. Is there some command/elegant way to do what I want?

Programmatically Merging using TeamFoundationClient TFS2008 and VS2010

I have Addin VS (maybe in future VSIX) for VS 2010.
I want to do branch of any single files (sql files) and later do merge programmatically.
I have seen several options:
GetStatus status = workspace.Merge
How to merge TFS change sets programmatically?
http://blogs.microsoft.co.il/shair/2009/04/20/tfs-api-part-19-merge/
MergeContent(Conflict, true);
workspace.Merge can show dialog modal for merge (diffmerge.exe I think) and show results (resolveing conflicts) ? Note: in my case, now, I want show merge tool.
TFS API MergeContent returns false without showing merge tool
There are tf commands (command line, not C##
tf diff[erence] itemspec [/version:versionspec]
tf merge [/recursive] [/force] [/candidate] [/discard]
[/version:versionspec] [/lock:none|checkin|checkout] [/preview]
[/baseless] [/nosummary] [/noimplicitbaseless] [/conservative]
[/format:(brief|detailed)] [/noprompt] [/login:username,[password]]
source destination
tf resolve [itemspec]
[/auto:(AutoMerge|TakeTheirs|KeepYours|
OverwriteLocal|DeleteConflict
|KeepYoursRenameTheirs)]
[/preview] [(/overridetype:overridetype | /converttotype:converttype]
[/recursive]
[/newname:path] [/noprompt]
[/login:username, [password]]
any suggestions for do merging of files, and have to options:
1) show dialog for merging (diffmerge)
2) auto, without show dialog for merging (diffmerge or another?) and resolving conflicts.
copy vsDiffMerge.exe from visual studio installation dir C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE inside App Exe file
var mergetool = new ThirdPartyToolDefinition(".*",ToolOperations.Merge,"vsDiffMerge.exe","","/m %1 %2 %3 %4");
var toolcol= ThirdPartyToolDefinitionCollection.Instance.FindTool(".*",ToolOperations.Merge);
if (toolcol == null)
{
ThirdPartyToolDefinitionCollection.Instance.AddTool(mergetool);
ThirdPartyToolDefinitionCollection.Instance.PersistAllToRegistry();
}
var controlsAssembly = Assembly.GetAssembly(typeof(ControlAddItemsExclude));
var vcResolveCoinflictsDialogType = controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.DialogResolveConflicts");
var ci = vcResolveCoinflictsDialogType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(Workspace), typeof(string[]), typeof(bool) }, null);
var resolveCoinflictsDialog = (Form)ci.Invoke(new object[] { workspace, null, true });
resolveCoinflictsDialog.ShowDialog(parent);
ThirdPartyToolDefinitionCollection.Instance.Remove(mergetool);
ThirdPartyToolDefinitionCollection.Instance.PersistAllToRegistry();

Accessing Sharepoint document library list using Windows PowerShell script

Task: I need to loop thru all files on Sharepoint site and download them to local folder.
Script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$s = Get-SPSite “https://abc.abctools.consumer.abc.net/sites/rtc/report/SitePages/Forms/AllPages.aspx”
$files = $s.RootWeb.GetFolder("Shared Documents").Files
foreach ($file in $files) {
Write-host $file.Name
$b = $file.OpenBinary()
$fs = New-Object System.IO.FileStream(("C:\SP Document Library files\"+$file.Name), [System.IO.FileMode]::Create)
$bw = New-Object System.IO.BinaryWriter($fs)
$bw.Write($b)
$bw.Close()
}
Errors: I get when i try to run/execute above script.
1. "You cannot call a method on a null-valued expression."
New-Object: Exception calling ".ctor" with "2" agrument(s): "Could not find a part of the path 'C:\SP Document Library files\'
New-Object: Constructor not found. Cannot find an appropriate constructor for the type system.IO.BinaryWrite.
The term 'Get-SPSite' is not recognized as a cmdlet, function, operable program or script file. verify the term and try again.
Response on Error #2: I have created the folder & named "SP Document Library files" so that path is correct C:\SP Document Library files not sure why i see that msg.
Library files (.csv,.xls) exists in a folder.
Folder name : 2014-01-31.
1. What to do to in order resolve above error message(s).
2. I'm not sure if i need to use whole sharepoint url or part of it.Educate me on that.
Thanks!!
Try by giving ReadWrite FileAccess.
And you can get the root web directly if you know the Url instead of using SPSite.
Here's my script I use and has always worked
$siteUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc”'
$listUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc/Shared Documents”'
$folderPath = 'C:\\....'
$web = Get-SPWeb -Identity $siteUrl
$list = $web.GetList($listUrl)
$items = $list.Items
ForEach ($item in $items)
{
$binary = $item.File.OpenBinary();
$folderPathToSave = $folderPath + "\\" + $item.Name;
if ($binary -ne $null)
{
$stream = New-Object System.IO.FileStream($folderPathToSave,[System.IO.FileMode]::Create,[System.IO.FileAccess]::ReadWrite);
$writer = New-Object System.IO.BinaryWriter($stream);
$writer.Write($binary);
$writer.Close();
}
}
$web.Dispose()
The original post:
http://naimmurati.wordpress.com/2012/06/07/backup-documents-from-document-library-with-powershell-script/

Categories