Using PowerShell in nuget package to edit Global.asax - c#

Using a Install.ps1 script with a Nuget Package, I'm attempting to add code to the Global.asax.cs file for customization purposes. With my Install.ps1 script the -replace command is not working. Infact I'm not able to assign any text to the variable $a I'm using with -replace and have it written to the "Global.asax.cs" file. The 3 lines of script involving -replace and the clipboard do work with "Windows PowerShell" outside of nuget. I know that the variable $a is passing along content from the clipboard since commenting out "#$customGlobalAsax.Document.Selection.Copy()" will write whatever happens to be in the clipboard into the Global.asax.cs file.
Any Suggestions? Thanks.
param($installPath, $toolsPath, $package, $project)
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
$customGlobalAsax.Open()
$customGlobalAsax.Document.Activate()
$customGlobalAsax.Document.Selection.SelectAll()
$customGlobalAsax.Document.Selection.Copy()
$a = [System.Windows.Forms.Clipboard]::GetText()
$a = $a -replace "using Company.Web.Mvc.ViewBase;","using Company.Web.Mvc.ViewBase;`r`nusing Company.Web.Address;"
[System.Windows.Forms.Clipboard]::SetText($a)
$customGlobalAsax.Document.Selection.Delete()
$customGlobalAsax.Document.Selection.Paste()

from what I can see, there is some problem with this line since it will return nothing:
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
The following is my test:
$directory = dir *
$directory | foreach {$_.name}
The above run successfully.
But the following returns nothing:
$directory = dir *
$directory.name | foreach {$_.name}
I believe in the latter case $_.name represents $directory.name.name which doesn't exist.
So it seems like this line in your script
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
should be changed to:
$customGlobalAsax = $project | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }

Related

Get CPU use/temp using PowerShell and the lib OpenHardwareMonitorLib

I have compiled the source of openhardwaremonitor (C#) it generates a DLL OpenHardwareMonitorLib.dll
Using the PowerShell script below, I was able to get my CPU temp, would like to ask for help in also getting CPU use, RAM use/ RAM left, and if possible GPU temp
Add-Type -Path .\OpenHardwareMonitorLib.dll
$cmptr = New-Object -TypeName OpenHardwareMonitor.Hardware.Computer
$cmptr.CPUEnabled= 1;
$cmptr.Open();
foreach ($hardwareItem in $cmptr.Hardware)
{
if($hardwareItem.HardwareType -eq [OpenHardwareMonitor.Hardware.HardwareType]::CPU){
$hardwareItem.Update()
foreach ($sensor in $hardwareItem.Sensors)
{
if ($sensor.SensorType -eq [OpenHardwareMonitor.Hardware.SensorType]::Temperature)
{
Write-Output $sensor.Name
Write-Output $sensor.Value.ToString()
}
}
}
}
$cmptr.Close();

What is the best way to change the solution name programmatically in asp.net core?

I'm looking for a way to provide a changing solution/project name functionality to ASP.NET Core Projects. My first idea is to do it programmatically in an installer feature where the developer would write the project name. Is it possible in .NET Framework or via Powershell?
Thanks!
You can use the below function which will help you in changing:
Here are the reference links:
1) Link 1
2) Link 2
function Rename-Project
{
# designed to run from the src folder
param(
[string]$projectName=$(throw "projectName required."),
[string]$newProjectName=$(throw "newProjectName required.")
)
if(!(Test-Path $projectName)){
Write-Error "No project folder '$projectName' found"
return
}
if(!(Test-Path $projectName\$projectName.csproj)){
Write-Error "No project '$projectName\$projectName.dll' found"
return
}
if((Test-Path $newProjectName)){
Write-Error "Project '$newProjectName' already exists"
return
}
# project
hg rename $projectName\$projectName.csproj $projectName\$newProjectName.csproj
# folder
hg rename $projectName $newProjectName
# assembly title
$assemblyInfoPath = "$newProjectName\Properties\AssemblyInfo.cs"
(gc $assemblyInfoPath) -replace """$projectName""","""$newProjectName""" | sc $assemblyInfoPath
# root namespace
$projectFile = "$newProjectName\$newProjectName.csproj"
(gc $projectFile) -replace "<RootNamespace>$projectName</RootNamespace>","<RootNamespace>$newProjectName</RootNamespace>" | sc $projectFile
# assembly name
(gc $projectFile) -replace "<AssemblyName>$projectName</AssemblyName>","<AssemblyName>$newProjectName</AssemblyName>" | sc $projectFile
# other project references
gci -Recurse -Include *.csproj |% { (gc $_) -replace "..\\$projectName\\$projectName.csproj", "..\$newProjectName\$newProjectName.csproj" | sc $_ }
gci -Recurse -Include *.csproj |% { (gc $_) -replace "<Name>$projectName</Name>", "<Name>$newProjectName</Name>" | sc $_ }
# solution
gci -Recurse -Include *.sln |% { (gc $_) -replace "\""$projectName\""", """$newProjectName""" | sc $_ }
gci -Recurse -Include *.sln |% { (gc $_) -replace "\""$projectName\\$projectName.csproj\""", """$newProjectName\$newProjectName.csproj""" | sc $_ }
}

Powershell [WMI] type methods

using WMI with PowerShell I found something I don't understand:
gwmi -class MIIS_ManagementAgent -namespace "root/MicrosoftIdentityIntegrationServer" | foreach
If ($_.Name -eq "contoso.com") {
$foo= $_
}
else {
$boo= $_
}
}
$state= $foo.ResumeState("FullSync")
$res = $foo.execute("FullSync")
$details = $foo.RunDetails()
$RunStatus = $foo.RunStatus()
I know that $foo contains [WMI] type accelerator but I cannot find any documentation of what are the methods of this type. I have no idea what ResumeState, execute, RunDetails and RunStatus methods are doing. I want to transfer this calls to C# but I have to understand what those calls are.

How do I get SonarQube to ignore the GlobalSuppressions.cs file?

I want to exclude the GlobalSuppressions.cs file from SonarQube analysis so that it doesn't look at the System.Diagnostics.CodeAnalysis.SuppressMessage directives in there.
These are in the root of each project, but not in the root where the solution is: E.g.
I set this in the admin:
Namely, **/GlobalSuppressions.cs.
There are many projects in each solution, so I would like to avoid referencing each individually if possible.
My solution to this problem was to use a Powershell script to clear the globalsupressions.cs file and alter the ruleset from one that errored (CodeAnalysisRulesErrors.ruleset or CodeAnalysisRulesUnitTestsErrors.ruleset) to one that threw warnings (CodeAnalysisRules.ruleset or CodeAnalysisRulesUnitTests.ruleset), that way SonarQube correctly reported on the technical debt.
[CmdletBinding()]
param (
[string]$localWorkspace
)
begin{}
process
{
try
{
$localWorkspace = "$($env:SYSTEM_DEFAULTWORKINGDIRECTORY)\$($localWorkspace)"
$localWorkspace = $localWorkspace -replace "/" , "\"
$localWorkspace = $localWorkspace -replace "\\" , "\"
Write-Verbose $localWorkspace
#Work out top level directories, excluding system dirs
[System.Collections.ArrayList]$topLevelDirs = #()
$topLevelItem = Get-ChildItem $localWorkspace -Exclude #("node_modules", "packages", "Common", ".nuget", ".vs", "_Resharper.Caches", "Javascript")
foreach ($item in $topLevelItem)
{
if (Test-Path $item -PathType Container) {
Write-Verbose $item
$topLevelDirs.Add($item)
}
}
foreach ($topLevelFolder in $topLevelDirs)
{
Write-Verbose $topLevelFolder
$ServiceDirs = Get-ChildItem -Path $topLevelFolder -Filter GlobalSuppressions.cs -Recurse
foreach ($sd in $ServiceDirs)
{
Write-Verbose $sd
Clear-Content $sd.FullName
}
Get-ChildItem -Path $topLevelFolder -Filter *.csproj -Recurse | ForEach {
Write-Verbose $_.FullName
(Get-Content $_.FullName | ForEach { $_ -replace 'CodeAnalysisRulesErrors.ruleset', 'CodeAnalysisRules.ruleset' }) | Set-Content $_.FullName
(Get-Content $_.FullName | ForEach { $_ -replace 'CodeAnalysisRulesUnitTestsErrors.ruleset', 'CodeAnalysisRulesUnitTests.ruleset' }) | Set-Content $_.FullName
}
}
}
catch
{
write-host "Caught an exception:"
write-host "Exception Type: $($_.Exception.GetType().FullName)"
write-host "Exception Message: $($_.Exception.Message)"
}
}
end{}

could not able to copy the proxy file using vs2008 powershell

Hi I have written new functionality in the existing webservice.
I am copying the proxy file when rebuilding and copying to the specific location
i am using powershell but its not working .i get the following error.
**The term 'wsdl.exe' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was in
cluded, verify that the path is correct and try again.
At C:\[path edited for security]\RebuildProxy.ps1:30 char:9
+ wsdl.exe <<<< /fields "/l:CS" "/n:$namespace" "/out:$outCSFile" "/urlkey:Tes
tEndpoint" "$wsdlUrl";
+ CategoryInfo : ObjectNotFound: (wsdl.exe:String) [], CommandNot
FoundException
+ FullyQualifiedErrorId : CommandNotFoundException**
After rebuild i get the message the file has been modified outside the source editor[ the generated proxy file already there in the location]
could you please help me on this
posted below the powershell code
param (
[string]$webServiceProjFile = $(throw "webServiceProjFile paramter is required." ),
[string]$serviceFile = $(throw "serviceFile parameter is required."),
[string]$outCSFile = $(throw "outCSFile paramter is required." )
)
if (! [IO.File]::Exists($webServiceProjFile))
{
throw "$webServiceProjFile note found.";
}
if (! [IO.File]::Exists($outCSFile))
{
throw "$outCSFile note found.";
}
# read the project file into an XML document.
$projectFileXml = [xml] (Get-Content $webServiceProjFile );
# access the configured IIS URL
$serviceWsdlUrl = [string]::Concat($projectFileXml.Project.ProjectExtensions.VisualStudio.FlavorProperties.WebProjectProperties.IISUrl.Trim(), '/', $serviceFile);
$namespace = "";
# Read the namespace for the proxy from the proxy C# file
Get-Content $outCSFile | ForEach-Object { if ($_ -match "^\s*namespace\s+([A-Za-z._]+)\s+{\s*$") { $namespace = $matches[1] }};
$wsdlUrl = [string]::Concat("$serviceWsdlUrl", '?wsdl');
# Regenerate the proxy using WSDL.exe
wsdl.exe /fields "/l:CS" "/n:$namespace" "/out:$outCSFile" "/urlkey:TestEndpoint" "$wsdlUrl";
# Update the generated C# file so the proxy class interits from WSE2 base class.
(Get-Content $outCSFile) |
ForEach-Object { $_ -replace "\s+\:\s+System\.Web\.Services\.Protocols\.SoapHttpClientProtocol", " : Microsoft.Web.Services2.WebServicesClientProtocol" } |
Set-Content $outCSFile ;
$projectDirectory = [IO.Path]::GetDirectoryName($outCSFile);
$appConfigFilePath = [IO.Path]::Combine($projectDirectory, "App.config");
(Get-Content $appConfigFilePath) |
ForEach-Object { $_ -replace '<add\s+key="TestEndpoint"\s+value="[^"]*"\s+/>', "<add key=""TestEndpoint"" value=""$serviceWsdlUrl"" />" } |
Set-Content $appConfigFilePath ;
WSDL.EXE is not in the path. On my computer it comes with the visual studio.
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\x64\wsdl.exe

Categories