skip to Main Content

I want to detect specific word or pattern in the all source code files. For ex. if I want to restrict DateTime.Now to be used in the project but if some team member has used this in the source code, I want to fail build operation.

I don’t know what is the proper way to do it but can I use VS Pre-Build event for the same? If no then can someone guide me on the correct path to fulfill my requirement?

2

Answers


  1. It’s a manual approach but could you do like global search by using Ctrl+Shift+F
    and put your regex or as in your example DateTime.Now in the search bar and alter whatever the things you need

    Login or Signup to reply.
  2. You can execute PowerShell scripts by entering a command like PowerShell MyPowerShellScript.ps1 in PreBuildEvent.The scripts include searching specific word or pattern in the all source code files.

    Please follow the steps below.(example)

    1. Powershell script
    $results = Get-ChildItem -Path {your project path} -Recurse | Select-String -Pattern "DateTime.Now";
    if([string]::IsNullOrEmpty($results)){
      Write-Host "not found specific word DateTime.Now"
    }else{
      Write-Host " found specific word DateTime.Now"
      #other than zero (0)
      exit 1
    }
    

    Note:

    Have your event action exit with a code other than zero (0). A zero exit code indicates a successful action; any other exit code is considered an error.

    2.Enter a command like PowerShell MyPowerShellScript.ps1.
    On the Project menu->click {ProjectName} Properties (or from Solution Explorer, press Alt+Enter)->Select Build > Events.
    enter image description here

    Visual Studio modifies your project file by adding the PreBuildtarget and the necessary MSBuild code to execute the steps you provided.

    <Target Name="PreBuild" BeforeTargets="PreBuildEvent">
      <Exec Command="PowerShell {your project path}pw.ps1" />
    </Target>
    

    3.Build the project and watch the output window. If it finds the specific world(DateTime.Now) in your source code files, the script exits with code 1 and the build fails.
    enter image description here

    Hope it can help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search