Razor Views in C# MVC – C# Code and HTML Coexisting Together

Razor Views in C# MVC

How C# Code and HTML Coexist Together

Tonight’s study topic is Razor Views in C# MVC 5.

Here are two good resources for this topic.

Paid access to Mosh Hamedani’s Complete ASP.net MVC 5 Course. This is covered in video 16 of his course.

Also helpful, was this YouTube video that is part of a larger MVC tutorial that I really like and refer to often

VIDEO: Razor View Syntax

What are Razor Views and What Do They Do?

Specific to C# MVC, Razor Views are code snippets with special syntax made up of C# code and HTML/CSS. The C# logic can interact with and output HTML and CSS elements/attributes dynamically.

With Razor Views, we use the @ symbol to switch between C# code and HTML. 

A simple example of printing numbers from 1 to 10 using Razor.

@for {int i = 1; i <=10; i++)
{
 <b>@i</b>
}

The Output would be: 1 2 3 4 5 6 7 8 9 10
Inside the brackets, Razor sees the <b>@i</b> and knows to render the C# variable i when its proceeded with an @ character then Razor sees the angle brackets and switches back in to HTML parsing mode.

If we didn’t want to use HTML we could change the <b> tag to <text> and output would just be text without the HTML.

The most important thing to understand and remember about Razor Views is the context switching in the parser is based on detection of specific characters.

@ character starts the C# parser but HTML & text won’t parse until Razor see a tag wrapped in angle brackets. We are just switching back and forth between to parsing modes. Make sense?

The loop is C# code but the output is HTML.
In ASP Classic and .Net, the Response Object would handle the HTML output to the browser from inside the loop.

Here are two more examples to help us cement the idea in our brains.

1. A simple date:
@{
   int day = 24;
   int month = 08;
   int year = 2020;
}
Date is @day-@month-@year
Output = Date is 24-08-2020


2. Loop thru images in folder
@for (int i = 1; i <= 5; i++)
{
  <img src="~/Images/@(i).png" />
}

Notice how in the sample above, we put the variable inside the parenthesis. Why, when we didn’t do this for the date example above?

Because if we don’t C# will try and read i. and an object with a property so we have to wrap it in parenthesis. This tell the Razor syntax that we are just trying to concatenate the values.

Razor View Code Blocks

In Razor Views we define code blocks using @{}.

@{
 int SumOfEvenNumbers = 0;
 int SumOfOddNumbers = 0;

 for(int i=1; i<=10; i++)
 {
  if(i %2==0)
  {
    SumOfEvenNumbers = SumOfEvenNumber + 1;
  }
  else
  {
    SumOfOddNumbers = SumOfOddNumbers + 1;
  }
 }
}

<h3>Sum of Even Numbers = @SumOfEvenNumbers</h3>
<h3>Sum of Odd Numbers = @SumOfOddNumbers</h3>

Razor View Comments

Razor View multi-line code comments are very similar to JavaScript and CSS that use the asterisk and forward slash, /*  */, to wrap comments.

Razor View multi-line comments use ampersand and asterisk in same way. @* to start a multi-line comment and *@ to end it. (See code example below)

What’s in the Razor View Example Below?

H2 tag class name is dynamically selected based on  logic, if Model.Customers.Count is greater than 5 then change the CSS class of the H2 element to “popular”.

Also, inside the <ul> tags, Razor View code loops through the list of customers and outputs the name.  

Sample C# Razor Code Example:

@model  Vidly.ViewModels.RandomMovieViewModel
@{
    ViewBag.Title = "Random";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
@*
    This is a comment
    on multiple lines
*@
 
@{
    var className = Model.Customers.Count > 5? "popular": null;
}
 
<h2 class="@className">@Model.Movie.Name</h2>
 
@if (Model.Customers.Count == 0)
{
    <text>No one has rented the movie before.</text>
}
 
else 
{
    <ul>
        @foreach (var cusomter in Model.Customers)
        {
            <li>@cusomter.Name</li>
        }
     </ul>
}

How to Extract Text from a PDF Using GhostScript (Command Line)

Extract text from PDF files using Ghost Script

This is a re-post from one of my favorite articles that I originally posted on 7/23/2018 on my old Blogger blog.

I think I would really like to revisit automating the extraction of text from PDF files. There is a lot of untapped value many companies could be leveraging but aren’t.

Recently, I received a request from a team member to find a way to:

  1. Extract a large amount of text from a large PDF file. 
  2. Once I get the text out I’ll need to parse and get specific elements in to an excel file.
  3. Format the Excel file in to specific tabs for each type of report I extract and add column headers
  4. Create validation code where I connect to a data warehouse using an Ajax web service and Ajax call in the Excel macro to validate the data based on an ID in one of the columns 

Pretty cool right? Just finished the prototype today! 7/31/2018.

In this article I’ll be covering the first step of this task where I use a free tool called Ghostscript to extract text from a PDF file. 

What is Ghostscript?

Ghostscript is a high-performance Postscript and PDF interpreter and rendering engine with the most comprehensive set of page description languages (PDL’s) on the market today and technology conversion capabilities covering PDF, PostScript, PCL and XPS languages.

Ghostscript has been under active development for over 20 years, and offers an extremely versatile feature set and can be deployed across a wide range of platforms, modules, end uses (embedding in hardware, as an engine in document management systems, providing cloud solution integration and as an engine in leading PDF generators and tools).

How to extract text from a PDF using GhostScript – Step by Step

Please note that the PDF file must be formatted correctly (text not image only).

  1. – Download Ghostscript
  2. – Install Ghostscript
  3. – Copy your pdf file to the bin directory where you installed Ghostscript
  4. – Open a command line window at the bin directory (as Administrator if you get access error when running).
  5.  – Sample Command: gswin64 -sDEVICE=txtwrite -o[Output File Name] [Input File Name]
  6. – Sample ghostscript command: gswin64 -sDEVICE=txtwrite -ooutput2.txt test.pdf

Sample Ghostscript from Command Line

c:>Program Files/gs/gs9.23/gswin64 -sDEVICE=txtwrite -ooutput2.txt test.pdf

Automating GhostScript using Excel Macro

In an earlier blog post I discussed and gave an example of how to extract text from a PDF file using a free software tool called GhostScript from the command line.

Now I want to use an Excel macro to pass the PDF file name to a batch file which will execute GhostScript on that specific PDF.

Using the batch file also allows me to push an argument to the batch file when calling it so we’ll use this to pass the file name from a cell in the Excel macro (“A4”).

For this solution to work, you will need:

  1. Excel Macro and batch file located in the working directory
  2. A copy of the GhostScript executables and DLL files in the working directory

Excel Macro code:

Sub RunGhostScriptExtract()
       Dim folderPath As String
    Dim shellCommand As String
    Dim ghostCommand As String
    Dim PDFFileName As String
    
    Worksheets("Master").Activate
    PDFFileName = Range("A4").Value
    folderPath = Application.ActiveWorkbook.Path
    ghostCommand = "run-ghostscript.bat " & PDFFileName
    '/S      Modifies the treatment of string after /C or /K (see below)    
    '/C      Carries out the command specified by string and then terminates
    '/K      Carries out the command specified by string but remains       

    shellCommand = "cmd /k " & folderPath & "\" & ghostCommand    Call 
    Shell(shellCommand, vbNormalFocus)       
End Sub

Batch file code:

pushd %~dp0REM startstart gswin32 -sDEVICE=txtwrite -ooutput.txt test.pdfstart gswin32 -sDEVICE=txtwrite -ooutput.txt %~1exit 

I hope this helps someone!

~ Cyber Abyss