C# How To Run C# Code Inside Sublime Text

Hey folks, I want to share a tip. Sublime Text is my favorite for quick scripts, text editing and doing other scripting things or anything which doesn’t require a whole IDE. I love the speed too much and it is super-fast. In the process, I found that you can run C# scripts too, right from inside the Sublime Text, like you can run JavaScript. This is what I will brief you about:
Sometime back, I wrote on configuring Sublime Text for JavaScript too. Here’s the link, if you want to learn:
Ok, let’s start. The process is simple. You need to have an executable file, which Sublime Text will use to execute the scripts.
For C#, we will use scriptcs. Like NodeJS can run JavaScript, scriptcs runs C#. You can write and execute an Application with only one line of code.

Steps to configure Sublime Text for executing C# codes
Step 1: Install scriptcs

In order to install scriptcs, you need to have chocolatey. Chocolatey is a package manager for Windows.

You can install it in two ways:
  1. Using the command prompt (cmd.exe): Run the command, given below in the console:
    1. @powershell -NoProfile -ExecutionPolicy Bypass -Command “iex ((new-object net.webclient).DownloadString(‘https://chocolatey.org/install.ps1’))” && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
  2. Using Powershell : Run either of the following commands
    1. iex ((newobject net.webclient).DownloadString(‘https://chocolatey.org/install.ps1’))
    2. iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex  

    There’s a chance you will get an error while running the script due to a Powershell Execution policy. By default, it is set to “Restricted” to prevent the harmful scripts from running. You can check the current execution policy by running “Get-ExecutionPolicy” command in Powershell.

If you encounter this error, set the execution policy to “RemoteSigned” and run the installation command again. Use the command given below:
  1. Set-ExecutionPolicy RemoteSigned
 Make sure you start the Powershell console in Administrator mode, otherwise the change will not take place.



Read full article here on C# Corner:


Happy learning 🙂

How to use RailPNRAPI to get PNR Status?

Here I’m sharing the sample code on How to consume API provided by railpnrapi.com to query Indian Railway PNR status:

Register yourself on http://www.railpnrapi.com/ and get/generate API Key & API Secret.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace RailPnrAPI_SampleCode
    class Program
        static void Main(string[] args)
            //set your credentials
            var apiCreds = new Dictionary
                {“Key”, “”},
                {“Secret”, “”}

            var pnr = “1234567890”; //test pnr
            var requestUrlTemplate = “http://railpnrapi.com/api/check_pnr/pnr/”+pnr+”/format/json/pbapikey/” +
                                   apiCreds[“Key”] + “/pbapisign/{0}”;

            //Get All the request parameter
            var paramsSet = new Dictionary
                {“pnr”, pnr},
                {“format”, “json”},
                {“pbapikey”, apiCreds[“Key”]}

            //sort the keys and concat their values
            var inputString = paramsSet.OrderBy(x => x.Key).Select(x => x.Value).Aggregate((a, b) => a + b).ToLower();
            //var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);
            var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);

            // compute hash
            var signature = ComputeHMACSHA1(inputString, keyBytes);

            var request = WebRequest.CreateHttp(string.Format(requestUrlTemplate, signature));
            var response = request.GetResponse();
            // parse JSON response using Newtonsoft.Json
            dynamic json = JsonConvert.DeserializeObject(new StreamReader(response.GetResponseStream()).ReadToEnd());

            // process/display response

            Console.WriteLine(“Response Code: {0}”,json.response_code);
            Console.WriteLine(“PNR: {0}”, json.pnr);
            Console.WriteLine(“Train No.: {0}”, json.train_num);
            Console.WriteLine(“Train Name: {0}”, json.train_name);
            Console.WriteLine(“DOJ: {0}”, json.doj);
            Console.WriteLine(“From Station (Code/Name): {0}/{1}”, json.from_station.code, json.from_station.name);
            Console.WriteLine(“To Station (Code/Name): {0}/{1}”, json.to_station.code, json.to_station.name);
            Console.WriteLine(“Reservation Upto (Code/Name): {0}/{1}”, json.reservation_upto.code, json.reservation_upto.name);
            Console.WriteLine(“Boarding Point (Code/Name): {0}/{1}”, json.boarding_point.code, json.boarding_point.name);
            Console.WriteLine(“Class: {0}”, [email protected]);
            Console.WriteLine(“No. of Passengers: {0}”, json.no_of_passengers);
            Console.WriteLine(“Chart Status: {0}”, json.chart_prepared);
            Console.WriteLine(“Passengers: n********************************”);
            foreach (var passenger in json.passengers)
                Console.WriteLine(“Passenger #:{0}, Booking Status:{1}, Current Status:{2}”, passenger.sr, passenger.passengers, passenger.current_status);



        private static string ComputeHMACSHA1(string input, byte[] key)
            var myHmacSha1 = new HMACSHA1(key);
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            var stream = new MemoryStream(byteArray);
            byte[] hashValue = myHmacSha1.ComputeHash(stream);
            return string.Join(“”, Array.ConvertAll(hashValue, b => b.ToString(“x2”)));

     Here’s the sample console output:

Sample Code Output

Sample Code in VB

Imports Newtonsoft.Json
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text

Public Class PnrResponse
    Public response_code As String = Nothing
    Public pnr As String = Nothing
    Public train_num As String = Nothing
    Public train_name As String = Nothing
    Public doj As String = Nothing
    Public from_station As Station = Nothing
    Public to_station As Station = Nothing
    Public reservation_upto As Station = Nothing
    Public boarding_point As Station = Nothing
    Public [class] As String = Nothing
    Public no_of_passengers As String = Nothing
    Public chart_prepared As String = Nothing
    Public passengers As List(Of Passenger) = Nothing
    Public [error] As String = Nothing
End Class

Public Class Station
    Public code As String = Nothing
    Public name As String = Nothing
End Class

Public Class Passenger
    Public sr As String = Nothing
    Public booking_status As String = Nothing
    Public current_status As String = Nothing
End Class

Module Module1
    Sub Main(args As String())
        ‘set your credentials
        Dim apiCreds = New Dictionary(Of String, String)() From {
            {“Key”, “”}, _
            {“Secret”, “”} _
        Dim pnr = “1234567890”
        ‘test pnr
        Dim requestUrlTemplate = “http://railpnrapi.com/api/check_pnr/pnr/” + pnr + “/format/json/pbapikey/” + apiCreds(“Key”) + “/pbapisign/{0}”

        ‘Get All the request parameter
        Dim paramsSet = New Dictionary(Of String, String)() From { _
            {“pnr”, pnr}, _
            {“format”, “json”}, _
            {“pbapikey”, apiCreds(“Key”)} _

        ‘sort the keys and concat their values
        Dim inputString = paramsSet.OrderBy(Function(x) x.Key).[Select](Function(x) x.Value).Aggregate(Function(a, b) a + b).ToLower()

        ‘var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);
        Dim keyBytes = Encoding.ASCII.GetBytes(apiCreds(“Secret”))

        ‘ compute hash
        Dim signature = ComputeHMACSHA1(inputString, keyBytes)

        Dim request = WebRequest.CreateHttp(String.Format(requestUrlTemplate, signature))
        Dim response = request.GetResponse()

        ‘ parse JSON response using Newtonsoft.Json
        Dim responseText = New StreamReader(response.GetResponseStream()).ReadToEnd()
        Dim json As PnrResponse = JsonConvert.DeserializeObject(Of PnrResponse)(responseText)

        ‘ process/display response

        Console.WriteLine(“Response Code: {0}”, json.response_code)
        Console.WriteLine(“PNR: {0}”, json.pnr)
        Console.WriteLine(“Train No.: {0}”, json.train_num)
        Console.WriteLine(“Train Name: {0}”, json.train_name)
        Console.WriteLine(“DOJ: {0}”, json.doj)
        Console.WriteLine(“From Station (Code/Name): {0}/{1}”, json.from_station.code, json.from_station.name)
        Console.WriteLine(“To Station (Code/Name): {0}/{1}”, json.to_station.code, json.to_station.name)
        Console.WriteLine(“Reservation Upto (Code/Name): {0}/{1}”, json.reservation_upto.code, json.reservation_upto.name)
        Console.WriteLine(“Boarding Point (Code/Name): {0}/{1}”, json.boarding_point.code, json.boarding_point.name)

        Console.WriteLine(“Class: {0}”, json.[class])
        Console.WriteLine(“No. of Passengers: {0}”, json.no_of_passengers)
        Console.WriteLine(“Chart Status: {0}”, json.chart_prepared)
        Console.WriteLine(“Passengers: ” & vbLf & “********************************”)
        For Each passenger In json.passengers
            Console.WriteLine(“Passenger #:{0}, Booking Status:{1}, Current Status:{2}”, passenger.sr, passenger.booking_status, passenger.current_status)

    End Sub

    Private Function ComputeHMACSHA1(input As String, key As Byte()) As String
        Dim myHmacSha1 = New HMACSHA1(key)
        Dim byteArray As Byte() = Encoding.ASCII.GetBytes(input)
        Dim stream = New MemoryStream(byteArray)
        Dim hashValue As Byte() = myHmacSha1.ComputeHash(stream)
        Return String.Join(“”, Array.ConvertAll(hashValue, Function(b) b.ToString(“x2”)))
    End Function

End Module


Download Sample Code for C# & VB Here: Sample Codes Rail PNR API