Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Mixing C# source code with PowerShell script code to speed your development

I had some C# code ready but needed to use it inside a PowerShell script.

At StackOverflow I found some code that put me in the right path. So here's a practical example when mixing codes inside a PowerShell script file:

. ".\Invoke-Parallel.ps1" # Importing another script into this PowerShell script file

$csharpSource = @"

using System;
using System.Collections.Generic;
using System.Linq;

public class DateExtensions
{
     public static List<Tuple<DateTime, DateTime>> GetWeeksBetweenDates(DateTime startDate, DateTime endDate)
     {
        var weeks = new List<Tuple<DateTime, DateTime>>();
        
    
         for (DateTime date = startDate; date <= endDate; date = date.AddDays(8))
         {
            var weekEnd = date.AddDays(7);
                            
            weeks.Add(new Tuple<DateTime, DateTime>(date, weekEnd <= endDate ? weekEnd : endDate));
         }

        return weeks;
    }
}
"@

Add-Type -TypeDefinition $csharpSource # Includes the C# code defined above to be called through the PowerShell script

$appPath = "C:\SomeFolder"
$startDate = [datetime]'6/1/2017'
$endDate = [datetime]'5/5/2018'

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

#Calls MyApp in batches, that is, for each week...
$weeks | Invoke-Parallel -ImportVariables -ScriptBlock {   
    Set-Location -Path $appPath
           
    $date = [string]::Format("{0:yyyyMMdd},{1:yyyyMMdd}", $_.Item1, $_.Item2)

    #Write-Host $date

    dotnet MyApp.dll budat=$date cpudt=$date # Calls .NET Core "executable" DLL for each week
}

pause #Keeps PowerShell window open to see the results

As we see in the code above, the variable $csharpSource holds the C# source code that later will called in the PowerShell script.

We then add\mix the C# code to\with PowerShell with the command Add-Type passing to it the $csharpSource variable that holds the source code. Simple as that.

Inside PowerShell script code we call the method defined in C# code with:

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

This is pretty useful because we don't need to convert our C# code to PowerShell idiom.

Hope it helps.

Reference:
How to convert C# code to a PowerShell Script?

Updated PowerShell script to insert copyright notice/banner/header in all source code files

In a recent post I described how one could insert a copyright banner in all source code files located on a given path. You can read all the details about it here: Inserting copyright notice/banner/header in all source code files with PowerShell script

During the past month or so I updated that PowerShell script to give it even more power. In the Notes section of that post I mentioned this point:


  • Beware that if you run the script twice it'll add the copyright notice twice in each file

With this updated version (see the highlighted parts) I’ve overcome such limitation.

I’m now also using the built-in Powershell Filter keyword to filter the files, that is, processing only .cs files (C# code files) excluding some other files that have the .cs extension but that have a given naming pattern. I exclude those files because it doesn’t make sense to add copyright to them and because in some cases it would break the build.

Here’s the updated PowerShell script with comments to help you understand what’s going on in each line:

param($target = "C:\MyProject\trunk", $companyname = "Leniel’s Software House")

#[System.Globalization.CultureInfo] $ci = [System.Globalization.CultureInfo]::GetCultureInfo("pt-BR")

[System.Globalization.CultureInfo] $ci = [System.Globalization.CultureInfo]::GetCurrentCulture

# Full date pattern with a given CultureInfo
# Look here for available String date patterns: http://www.csharp-examples.net/string-format-datetime/
$date = (Get-Date).ToString("F", $ci);

# Header template
$header = "//-----------------------------------------------------------------------

// <copyright file=""{0}"" company=""{1}"">

// Copyright (c) {1}. All rights reserved.

// <author>Leniel Macaferi</author>

// <date>{2}</date>

// </copyright>

//-----------------------------------------------------------------------`r`n"

function Write-Header ($file)
{
    # Get the file content as as Array object that contains the file lines
    $content = Get-Content $file
    
    # Getting the content as a String
    $contentAsString =  $content | Out-String
    
    <# If content starts with // then the file has a copyright notice already
       Let's Skip the first 14 lines of the copyright notice template... #>
    if($contentAsString.StartsWith("//"))
    {
       $content = $content | Select-Object -skip 14
    }

    # Splitting the file path and getting the leaf/last part, that is, the file name
    $filename = Split-Path -Leaf $file

    # $fileheader is assigned the value of $header with dynamic values passed as parameters after -f
    $fileheader = $header -f $filename, $companyname, $date

    # Writing the header to the file
    Set-Content $file $fileheader -encoding UTF8

    # Append the content to the file
    Add-Content $file $content
}

#Filter files getting only .cs ones and exclude specific file extensions
Get-ChildItem $target -Filter *.cs -Exclude *.Designer.cs,T4MVC.cs,*.generated.cs,*.ModelUnbinder.cs -Recurse | % `
{
    <# For each file on the $target directory that matches the filter,
       let's call the Write-Header function defined above passing the file as parameter #>
    Write-Header $_.PSPath.Split(":", 3)[2]
}
Hope you make even better use of such a pearl that comes in handy from time to time.

Inserting copyright notice/banner/header in all source code files with PowerShell script

I have a better version of this PowerShell script if you’re interested.
I suggest you read this post first (there’s a bonus point) then go take a look at the new one here:
Updated PowerShell script to insert copyright notice/banner/header in all source code files

Today my client asked for the source code of a project we worked together. He wants to submit it to patent review and he wanted to include a copyright notice in each C# code file (.cs).

I googled about a way of accomplishing this and found this post:

Use a Visual Studio Macro to Insert Copyright Headers into Source Files

It looked promising but as I’m working with Visual Studio 2012 I just hit a road block because it dropped the support for Macros. So I had to find some other way… in the meantime I asked a question at StackOverflow to see if someone had any good advice regarding this. Right now there’s one nice answer but it requires manual work. I’m really interested in an automated process (do the work in a batch fashion) because there are lots of .cs files in the Visual Studio solution comprised of 7 projects.

Some more Googling with the right words (read PowerShell) and I was able to find something that could do the work. Kishor Aher wrote about it Powershell – Copyright header generator script. Oh God, the internet is really amazing thingy! Remember to just search for the right words…

Now it was just a matter of adapting the PowerShell script to my needs. Here is it:

param($target = "C:\MyProject", $companyname = "My Company", $date = (Get-Date))

$header = "//-----------------------------------------------------------------------

// <copyright file=""{0}"" company=""{1}"">

// Copyright (c) {1}. All rights reserved.

// <author>Leniel Macaferi</author>

// <date>{2}</date>

// </copyright>

//-----------------------------------------------------------------------`r`n"

function Write-Header ($file)
{
    $content = Get-Content $file

    $filename = Split-Path -Leaf $file

    $fileheader = $header -f $filename,$companyname,$date

    Set-Content $file $fileheader

    Add-Content $file $content
}

Get-ChildItem $target -Recurse | ? { $_.Extension -like ".cs" } | % `
{
    Write-Header $_.PSPath.Split(":", 3)[2]
}

As you see above, the script will place the copyright notice in every .cs file that lies within the folder C:\MyProject. So let’s say you have a Visual Studio solution with various projects – the script will traverse all files placing the notice in every .cs file it finds along the way…

I named the script Copyright.ps1.

To make this work I just opened PowerShell command line, navigated to the folder where I placed the script file and typed .\Copyright.ps1 to run the script:

Executing Copyright PowerShell script using PowerShell command line toolFigure 1 - Executing Copyright PowerShell script using PowerShell command line tool

You’re done!

Enjoy.

Notes

  • Close Visual Studio solution before running the PowerShell script. Otherwise you may get some error message telling you that some file is in use.
  • Be sure to have your source code files commited in a source control repository before running the scripts so that if anything goes wrong you can just revert to the previous state.
  • Beware that if you run the script twice it'll add the copyright notice twice in each file.

A big thank you to Kishor for providing us the PowerShell script. I’m not that experienced with PowerShell but adapting existing scripts is something easy to do IMHO.

Bonus
To get support for PowerShell scripting in Visual Studio with syntax highlighting and IntelliSense, there’s an awesome and free product out there. It’s called PowerGUI. In order to use it, download PowerGUI here and then install its accompanying Visual Studio extension available here. As I’m using Visual Studio 2012 I had to install the alpha release available here.

See for yourself the awesomeness:

PowerGUI editing PowerShell script with full IntelliSense support and Code Highlighting
Figure 2 - PowerGUI editing PowerShell script with full IntelliSense support and Code Highlighting