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:

http://www.c-sharpcorner.com/article/how-to-run-c-sharp-code-inside-sublime-text/

Happy learning 🙂

(31)

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}”, json.@class);
            Console.WriteLine(“No. of Passengers: {0}”, json.no_of_passengers);
            Console.WriteLine(“Chart Status: {0}”, json.chart_prepared);
            Console.WriteLine();
            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);
            }
            Console.WriteLine();
            Console.WriteLine(“********************************”);

            Console.ReadLine();

        }

        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()
        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)
        Next
        Console.WriteLine()
        Console.WriteLine(“********************************”)

        Console.ReadLine()
    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


(89)

Use of Coding Standards in Programming

If you’re working in a team and use Visual Studio for development then here are few guideline tips on how you could improve the pace and maintain the uniformity among all your team champs. Even if you’re working alone, it will help you to stay on a track rather moving on different track as you go further hence allow you to focus on your programming. 


Before beginning any application development, consider implementing programming and database standards with your team. Using development standards allows all programmers to know what is expected of them and how to create new applications from scratch. Standards help developers move from one project to another without having to learn a different style of programming because it was created by another programmer.

Microsoft has published a set of programming standards for C# and Visual Basic. These are an excellent place to start, and you’re always encouraged to adopt some sort of standards as an important first step in application development. 

Creating standards doesn’t limit your creativity, as many programmers seem to think. Programming standards help you focus your creativity where it is really needed. You can concentrate on the business problem you are trying to solve, instead of always having to think about what name to give a method or variable. As a corollary, consider the Windows and Mac operating environments, where most programs written have a consistent look and feel. This is why users like using Windows or Macs, because they don’t have to learn everything about how a new program works. They already know how to use most of the features in each program. Using standards in your programming keeps the programmer’s “look and feel” consistent. You spend less time figuring out what the variables are or how many indents a programmer used and focus on the logic of the program.

The use of standards leads to reduced maintenance costs due to consistency in each program. You can move from one project to another very easily, even one someone else wrote, and immediately read and understand the code. Programming standards help programmers create a consistent structure, code style, variable names, and method names within all applications. Standards create code that is unambiguous, easy to read, and easy to maintain by other developers.

The standards documents you should have in place at your shop are:

  1. Visual Studio Setup 
  2. C# or Visual Basic Programming Standards
  3. SQL Server Object Naming Standards, and 
  4. Database Development Standards. 
  5. Any other framework(s) involved in your project (if any)


The Visual Studio Setup document ensures that each programmer configures his or her Visual Studio the same as everyone else in the shop. Especially important is the Tab setting, which forces everyone to use the same tab indent. Consider what happens if you have your tab stops set at three spaces and you check a file into your source control system. Then your co-worker sets her tab stop at two spaces, checks out your file, reformats the document to two spaces, and checks that version into source control. 
If you want to see the changes made by your co-worker, the source control system shows that every line has been changed because reformatting changes every line to use two spaces instead of the three spaces that you’d set.

The C# or Visual Basic Programming Standards document sets forth variable and method naming, class naming, file naming, and control naming. Naming each of these items consistently greatly aids readability between all programmers in your shop.

The SQL Server Object Naming Standards document describes how to name tables, stored procedures, views, and other database objects. You should also describe how SQL keywords and functions in your SQL statements are cased.

The Database Development Standards document describes your database design approach. Your approach may include things such as how you create primary keys, the use of clustered indexes, standard fields for each table, how to handle concurrency, and whether or not to use dynamic SQL or stored procedures.
Along with the above documents, if you’ve planned to involve any other Framework / Tool in your project, it is advised to have one for that also.

Despite mentioned above you’re always free to customize the style of standards you’re going to create before you start the project. 

I hope you enjoyed this post… thank you for reading!!

(8)

A new guard page for stack cannot be created- ASP.NET MVC4 Error

An hour back I was working with ASP.NET and encountered with this pretty error. I kept wandering for about ten minutes what really has happened. My iisexpress.exe was automatically shut down and it didn’t work when I kept hitting CTRL+F5.


How I solved it:

Later i the process I came to know that I had the name for an Action was “View” that you can see in the picture below. 


I renamed it to View1 and it worked again. Hope this helps somebody. Thanks!

(55)

“object does not contain a definition for get_Range” in Excel C#


Error:
‘object’ does not contain a definition for ‘get_Range’

Line of Code:
Excel.Range header = wks.get_Range(wks.Cells[1, 1], wks.Cells[1, 10]);
Solution:
Cast the cells as "object" in get_Range()

Excel.Range header = wks.get_Range((object)wks.Cells[1, 1],(object) wks.Cells[1, 10]);

Thanks!

(250)

How to convert Visual FoxPro DBF file to Excel in C#

The very first thing as you go start doing this stuff, make sure you’ve downloaded and installed Visual FoxPro Driver on your host machine. Here the link for download:
http://www.microsoft.com/en-us/download/confirmation.aspx?id=14839

Use OleDbConnection to get the records into DataTable and later export/write the DataTable to Excel.

Here are the complete codes:

using System;
using System.Data;
using System.Data.OleDb;
using System.IO; 

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace Convert_DBF_to_Excel {     
       class Program    {         
                static Missing mv = Missing.Value; 
         static void Main(string[] args) {
         string dbfFileName =@"D:mydata.dbf";
         string constr = "Provider=VFPOLEDB.1;Data Source=" + Directory.GetParent(dbfFileName).FullName;
         string ExcelFileName = AppDomain.CurrentDomain.BaseDirectory+"converted_file_" + DateTime.Now.ToString("yyyy-MM-dd") +"_"+DateTime.Now.Ticks.ToString() +".xls";
         using (OleDbConnection con = new OleDbConnection(constr)){
           var sql = "select * from "+Path.GetFileName(dbfFileName)+";";
           OleDbCommand cmd = new OleDbCommand(sql, con);
           DataTable dt = new DataTable(); 
            try{
                con.Open();
               }
            catch(Exception ex){
               Console.WriteLine("Error connecting database: "+ex.Message);
               return;
               }
            if (con.State == ConnectionState.Open){
              OleDbDataAdapter da = new OleDbDataAdapter(cmd);
               Console.Write("Reading database...  ");
               da.Fill(dt);
               Console.WriteLine("Completed.");
             }
            if (con.State == ConnectionState.Open){
             try{
                con.Close();
               }
             catch { }
           }
           if (dt != null && dt.Rows.Count > 0){
            GenerateExcel(dt,ExcelFileName);
            }
          }
        }
   static void GenerateExcel(DataTable sourceDataTable, string ExcelFileName)
        {
            Console.Write("Generating Excel File...");
 
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook wkb = excelApp.Workbooks.Add(mv);
            Excel.Worksheet wks = wkb.Sheets[1];
 
            for (int i = 0; i < sourceDataTable.Columns.Count; ++i)
            {
                ((Excel.Range)wks.Cells[1, i + 1]).Value = sourceDataTable.Columns[i].ColumnName;
 
            }
            Excel.Range header = wks.get_Range((object)wks.Cells[1, 1], (object)wks.Cells[1, sourceDataTable.Columns.Count]);
            header.EntireColumn.NumberFormat = "@";
 
            object[,] sourceDataTableObjectArray = new object[sourceDataTable.Rows.Count, sourceDataTable.Columns.Count];
            for(int row=0;row<sourceDataTable.Rows.Count;++row)
            {
                for (int col = 0; col < sourceDataTable.Columns.Count; ++col)
                {
                    sourceDataTableObjectArray[row, col] = sourceDataTable.Rows[row][col].ToString();
                }
            }
 
 
          ((Excel.Range)  wks.get_Range((object)wks.Cells[2, 1],(object)wks.Cells[sourceDataTable.Rows.Count, sourceDataTable.Columns.Count])).Value2 = sourceDataTableObjectArray;
 
            header.EntireColumn.AutoFit();
            header.Font.Bold = true;
            wks.Application.ActiveWindow.SplitRow = 1;
            wks.Application.ActiveWindow.FreezePanes = true;
 
            wks.SaveAs(ExcelFileName, Excel.XlFileFormat.xlExcel8, mv, mv, mv, mv, mv, mv, mv, mv);            
            wks = null;
            wkb = null;
            excelApp.Quit();
 
            Console.WriteLine("Completed.");
        }
   } }


(109)

How to handle negative TimeSpan value in C#?


I had problems with casting TimeSpan object to DateTime. Error occured: FormatException (“the input string was not in proper format”).

Code I tried:
DateTime.Parse(record.Field(“Hours”)); // raised error

Here record is a DataRow object and I’m using Linq to Objects to parse the Date.

//Field actual value :”{-06:25:00}”

How did I overcome?
I used .Duration() method of TimeSpan object.

DateTime.Parse(record.Field(“Hours”).Duration()); 


HTH 🙂








(114)

What is CLR (Common Language Runtime)?


CLR is a part of .NET Framework which manages the execution of several supported .NET languages, allowing them to share Common Object-Oriented Classes. CLR is somewhat comparable to Java Virtual Machine. Microsoft refers to its Common Language Runtime as “Managed Execution Environment“. 

CLR held responsible for these important activities:

  1. Garbage Collection: CLR automatically manages memory, thus eliminating memory leaks. When objects are not referred, GC (Garbage Collector) automatically releases those memory thus providing efficient memory management.
  2. CAS (Code Access Security): CAS grants rights to program depending on the security configuration of the machine. For instance, if the program has rights to edit or create a new file but not  to delete a file. CAS ensures that the code runs under the environment of machines security configuration.
  3. CV (Code Verification): This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
  4. IL to Native code Translation/Optimization: CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.

(3)

What is Native Image Generator (Ngen.exe) and how does it work?


Ngen.exe (Native Image Generator) is a tool that creates native images, which are files containing compiled Processor-Specific machine code, and installs them into the native image cache on the local computer. It’s a tool that improves the performance of managed applications. In other words, rather than compiling the code dynamically using JIT on runtime, a full image of native compiled code is stored in cache while installing the application which leads to better performance as the assembly loads and execute faster.

The runtime can use native images from the cache instead of using JIT to compile the original assembly.
It not always necessary that Ngen.exe produces optimized code because it uses the current environments parameters which can change over a period of time. For instance, a code compiled in Windows XP environment will not be optimized to run under Windows 2008 server.
The following command is used in Visual Studio command line to install a full compiled native code in cache:
<input disabled="" style="font-size: 20px; width: 100%;" type="text" value=" ngen.exe install ” />

(2)

What is API and How to use it?

Have you ever used a library in C#? Yes, that’s an API. An API (Application Programming Interface is something that let’s you interact with something or with an interface.

They are just a set of functions you can call. They have their documentation on what they do, how they behave, what input(s) they need to perform as intended.

For example, using Win32 API you can interact with Windows, using Twitter API you can interact with Twitter… etc. They could be Interacting with Windows as well as Web both.

Its a doorway into the programming model that a company exposes so you can enhance or extend some capability they provide. For example, Facebook wants to help programmers develop applications that work with their platform. So they offer a library that you include with your application to access data in the Facebook system.

Basically you start using an API by downloading it’s library or development kit (SDK), reading it’s Manual (Documentation). Let’s take Facebook for an example. Go to developers.facebook.com. Search for “SDK”. Download the version for your platform. Look at the samples. Try them. Change them to do something slightly different.

Refer to this link for example: https://developers.google.com/maps/documentation/javascript/demogalleryThis demonstrates to the various use of Google Maps API.


(10)