CSharp

CSharp is a multi-paradigm programming language encompassing strong typing, imperative, declarative, functional, procedural, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the programming languages designed for the Common Language Infrastructure. From Wikipedia

Compile code based on csc (CSharp compiler)

Look for the compiler in c:\windows\Microsoft.NET\Framework\<version>\csc.exe

Hello world sample code:

   1 using System;
   2 
   3 namespace org.bitarus.allowed
   4 {
   5   public class Program
   6   {
   7     public static void Main(string[] args)
   8     {
   9       System.Console.WriteLine("Hello world");
  10     }
  11   }
  12 }

Compile HelloWorld.cs:

   1 csc /t:exe /out:HelloWorld.exe HelloWorld.cs

Build batch file example .NET 4.0

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /t:library /out:libx.dll src\_Default.cs src\DALSql.cs src\Global.cs

app.config sample

   1 <?xml version="1.0" encoding="utf-8" ?>
   2 <configuration>
   3   <appSettings>
   4     <add key="keyx" value="valuex"/>
   5   </appSettings>
   6 </configuration>

   1 using System.Configuration;
   2 //.....
   3 string valuex = ConfigurationManager.AppSettings["keyx"];
   4 System.Console.WriteLine(valuex);

Copy src/app.config to AppX.exe.config.

JSON library several .net version

http://james.newtonking.com/json

Deserialization example

   1 // mcs test.cs /r:Newtonsoft.Json.dll  
   2 // mono test.exe 
   3 
   4 using Newtonsoft.Json;
   5 using System;
   6 
   7 public class Reply{
   8   public int mnr {get;set;}
   9   public int fnr {get;set;}
  10   public MSG[] msg {get;set;}
  11 }
  12 
  13 public class MSG{
  14   public DateX date {get;set;}
  15   public string msg {get;set;}
  16 
  17 }
  18 
  19 public class DateX{
  20   [JsonProperty("$date")]
  21   public long datex { get;set; }  
  22 }
  23 
  24 public class Program{
  25   public static void Main(string[] args){
  26     string json = @"{\"mnr\": 1, \"fnr\": 777, \"msg\": [
  27 {\"date\": {\"$date\": 1388679281000}, \"msg\": \"AAAAA\"}, 
  28 {\"date\": {\"$date\": 1388678779000}, \"msg\": \"BBBBB\"}, 
  29 {\"date\": {\"$date\": 1388676003000}, \"msg\": \"CCCCC\"}
  30 ]}";
  31 
  32     Reply r = JsonConvert.DeserializeObject<Reply>(json);
  33     System.Console.WriteLine(String.Format("Fnumber:{0} MNumber:{1}",r.fnr,r.mnr));
  34 
  35     foreach(MSG msg in r.msg) {
  36       System.Console.WriteLine(String.Format("MSG:{0} Date:{1} ",msg.msg, msg.date.datex ));
  37     }      
  38   }
  39 }

String format examples

   1 using System;
   2 
   3 public class Test{
   4   public static void Main(String[] args)  {
   5     int a=123;
   6     System.Console.WriteLine( String.Format("{0}",a) ); // 123
   7     System.Console.WriteLine( String.Format("{0:D2}",a) ); //123
   8     System.Console.WriteLine( String.Format("{0:D5}",a) ); // 00123
   9   }                       
  10 }

IL sample code

IL (Intermediate Language) code from C# build with Mono.

   1 /*
   2 Compile code
   3 mcs -sdk:4.5 testeILAsm.cs 
   4 
   5 Get IL code
   6 monodis testeILAsm.exe > testeILAsm.il
   7 */
   8 
   9 using System;
  10 using System.IO;
  11 
  12 namespace org.bitarus.allowed
  13 {
  14   public class Program
  15   {
  16     private static void dummy(int a,int b)    {
  17       int res=sum(a,b);
  18       log(a,b);
  19       log(a,b);
  20     }
  21     
  22     private static void log(int skey,int salt)    {
  23       string line=String.Format("skey:{0:X8} Salt:{1:X8}",skey,salt);
  24       
  25       using (StreamWriter w =File.AppendText("logx.txt"))       {
  26         w.WriteLine(line);        
  27       }
  28       
  29       System.Console.WriteLine(line);
  30     }
  31 
  32     private static int sum(int a,int b)
  33     {
  34       return a+b;
  35     }
  36     
  37     public static void Main(string[] args)
  38     {
  39       System.Console.WriteLine("Hello world");      
  40       int x1=1234;
  41       int x2=5678;
  42       dummy(x1,x2);
  43     }
  44   }
  45 }

   1 .assembly extern mscorlib
   2 {
   3   .ver 4:0:0:0
   4   .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
   5 }
   6 .assembly 'testeILAsm'
   7 {
   8   .custom instance void class [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() =  (
   9                 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
  10                 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01       ) // ceptionThrows.
  11 
  12   .hash algorithm 0x00008004
  13   .ver  0:0:0:0
  14 }
  15 .module testeILAsm.exe // GUID = {6FFBF541-A6EC-4419-8CA6-549A5A6E2EA7}
  16 
  17 
  18 .namespace org.bitarus.allowed
  19 {
  20   .class public auto ansi beforefieldinit Program
  21         extends [mscorlib]System.Object
  22   {
  23 
  24     // method line 1
  25     .method private static hidebysig 
  26            default void dummy (int32 a, int32 b)  cil managed 
  27     {
  28         // Method begins at RVA 0x2050
  29         // Code size 23 (0x17)
  30         .maxstack 2
  31         .locals init (
  32                 int32   V_0)
  33         IL_0000:  ldarg.0 
  34         IL_0001:  ldarg.1 
  35         IL_0002:  call int32 class org.bitarus.allowed.Program::sum(int32, int32)
  36         IL_0007:  stloc.0 
  37         IL_0008:  ldarg.0 
  38         IL_0009:  ldarg.1 
  39         IL_000a:  call void class org.bitarus.allowed.Program::log(int32, int32)
  40         IL_000f:  ldarg.0 
  41         IL_0010:  ldarg.1 
  42         IL_0011:  call void class org.bitarus.allowed.Program::log(int32, int32)
  43         IL_0016:  ret 
  44     } // end of method Program::dummy
  45 
  46     // method line 2
  47     .method private static hidebysig 
  48            default void log (int32 skey, int32 salt)  cil managed 
  49     {
  50         // Method begins at RVA 0x2074
  51         // Code size 66 (0x42)
  52         .maxstack 3
  53         .locals init (
  54                 string  V_0,
  55                 class [mscorlib]System.IO.StreamWriter  V_1)
  56         IL_0000:  ldstr "skey:{0:X8} Salt:{1:X8}"
  57         IL_0005:  ldarg.0 
  58         IL_0006:  box [mscorlib]System.Int32
  59         IL_000b:  ldarg.1 
  60         IL_000c:  box [mscorlib]System.Int32
  61         IL_0011:  call string string::Format(string, object, object)
  62         IL_0016:  stloc.0 
  63         IL_0017:  ldstr "logx.txt"
  64         IL_001c:  call class [mscorlib]System.IO.StreamWriter class [mscorlib]System.IO.File::AppendText(string)
  65         IL_0021:  stloc.1 
  66         .try { // 0
  67           IL_0022:  ldloc.1 
  68           IL_0023:  ldloc.0 
  69           IL_0024:  callvirt instance void class [mscorlib]System.IO.TextWriter::WriteLine(string)
  70           IL_0029:  leave IL_003b
  71 
  72         } // end .try 0
  73         finally  { // 0
  74           IL_002e:  ldloc.1 
  75           IL_002f:  brfalse IL_003a
  76 
  77           IL_0034:  ldloc.1 
  78           IL_0035:  callvirt instance void class [mscorlib]System.IDisposable::Dispose()
  79           IL_003a:  endfinally 
  80         } // end handler 0
  81         IL_003b:  ldloc.0 
  82         IL_003c:  call void class [mscorlib]System.Console::WriteLine(string)
  83         IL_0041:  ret 
  84     } // end of method Program::log
  85 
  86     // method line 3
  87     .method private static hidebysig 
  88            default int32 sum (int32 a, int32 b)  cil managed 
  89     {
  90         // Method begins at RVA 0x20d4
  91         // Code size 4 (0x4)
  92         .maxstack 8
  93         IL_0000:  ldarg.0 
  94         IL_0001:  ldarg.1 
  95         IL_0002:  add 
  96         IL_0003:  ret 
  97     } // end of method Program::sum
  98 
  99     // method line 4
 100     .method public static hidebysig 
 101            default void Main (string[] args)  cil managed 
 102     {
 103         // Method begins at RVA 0x20dc
 104         .entrypoint
 105         // Code size 30 (0x1e)
 106         .maxstack 2
 107         .locals init (
 108                 int32   V_0,
 109                 int32   V_1)
 110         IL_0000:  ldstr "Hello world"
 111         IL_0005:  call void class [mscorlib]System.Console::WriteLine(string)
 112         IL_000a:  ldc.i4 1234
 113         IL_000f:  stloc.0 
 114         IL_0010:  ldc.i4 5678
 115         IL_0015:  stloc.1 
 116         IL_0016:  ldloc.0 
 117         IL_0017:  ldloc.1 
 118         IL_0018:  call void class org.bitarus.allowed.Program::dummy(int32, int32)
 119         IL_001d:  ret 
 120     } // end of method Program::Main
 121 
 122     // method line 5
 123     .method public hidebysig specialname rtspecialname 
 124            instance default void '.ctor' ()  cil managed 
 125     {
 126         // Method begins at RVA 0x2106
 127         // Code size 7 (0x7)
 128         .maxstack 8
 129         IL_0000:  ldarg.0 
 130         IL_0001:  call instance void object::'.ctor'()
 131         IL_0006:  ret 
 132     } // end of method Program::.ctor
 133 
 134   } // end of class org.bitarus.allowed.Program
 135 }

CIL (Common Intermediate Language) instructions

Adapted from http://en.wikipedia.org/wiki/List_of_CIL_instructions

Opcode

Instruction

Description

0x00

nop

do nothing

0x2A

ret

return from method possibly with value

0x28

call <method>

Call method described by method

0x72

ldstr <string>

Push a string object for the literal string

0x02

ldarg.0

Load argument 0 onto the stack

0x03

ldarg.1

Load argument 1 onto the stack

0x16

ldc.i4.0

Push 0 onto the stack as int32

0x17

ldc.i4.1

Push 1 onto the stack as int32

0x20

ldc.i4 <int32 (num)>

Push num of type int32 onto the stack as int32

0x0A

stloc.0

Pop a value from stack into local variable 0

0x0B

stloc.1

Pop a value from stack into local variable 1

0x06

ldloc.0

Load local variable 0 onto stack

0x07

ldloc.1

Load local variable 1 onto stack

IL code usually resides before string 'BSJB' 0x45534A42.

Simple TCP server

   1 using System;
   2 using System.Net;
   3 using System.Net.Sockets;
   4 using System.Threading;
   5 using System.Text;
   6 
   7 public class Server
   8 {
   9   public static void ConnectionHandler(object socket)
  10   {
  11     if( socket is Socket )
  12       {
  13         var s=(Socket)socket;
  14         bool exit=false;
  15         while(!exit)
  16           {
  17             byte[] rxbuffer = new byte[8192];
  18             int nrRx =  s.Receive(rxbuffer,rxbuffer.Length,0);
  19             string rx = Encoding.ASCII.GetString(rxbuffer, 0, nrRx);
  20             System.Console.Write(rx.ToUpper());
  21             if(rx=="exit\n") {
  22               exit=true;
  23             }
  24             Byte[] tx = Encoding.ASCII.GetBytes(rx.ToUpper());
  25             s.Send(tx,tx.Length,0);
  26           }
  27         s.Close();
  28       }
  29   }
  30   
  31   public static void Main(string[] args)
  32   {
  33     Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
  34     IPEndPoint ep = new IPEndPoint( new IPAddress(new byte[]{0,0,0,0 }) ,9090);
  35     var handlerCallback = new WaitCallback(ConnectionHandler);
  36     s.Bind(ep);
  37     s.Listen(0);
  38 
  39     while(true)
  40       {
  41         Socket rx = s.Accept(); 
  42         ThreadPool.QueueUserWorkItem(handlerCallback,   rx );
  43       }    
  44   }
  45 }

Sample Web Service with Mono + IIS 6

web.config

   1 <configuration>
   2     <system.web>
   3         <customErrors mode="Off"/>
   4     </system.web>
   5 </configuration>

ws.asmx

   1 <%@ WebService Class="WS.RemoteWebService" %> 

ws.cs

   1 //gmcs /r:System,System.Web,System.Web.Services ws.cs /t:library
   2 using System;
   3 using System.Web;
   4 using System.Web.Services;
   5  
   6 namespace WS
   7 {
   8     [WebService (Description="Our first web service")]
   9     public class RemoteWebService : System.Web.Services.WebService
  10     {
  11         [WebMethod (Description="Adds two numbers")]
  12         public int Add (int firstNumber, int secondNumber)
  13         {
  14                 return firstNumber + secondNumber;
  15         }
  16     }
  17 }

Deploy the DLL inside a bin folder

Linq example

   1 using System;
   2 using System.Collections.Generic;
   3 using System.Linq; 
   4 
   5 interface Filter{
   6   List<int> filterNumbers(List<int> numbers);
   7 }
   8 
   9 class NormalFilter:Filter{
  10   public List<int> filterNumbers(List<int> numbers){
  11     var oddNumbers = new List<int>();
  12     foreach(var nr in numbers){
  13       if( nr%2==0){
  14         oddNumbers.Add(nr);
  15       }
  16     }
  17     return oddNumbers;
  18   }
  19 } 
  20 
  21 class LinqFilter:Filter{
  22   public List<int> filterNumbers(List<int> numbers){
  23    var oddNumbersLinq = numbers.Where( x => x%2==0).ToList();
  24    return oddNumbersLinq;     
  25   }
  26 } 
  27 
  28 class MainClass {
  29   public static void Main (string[] args) {
  30     var numbers = new List<int>();
  31     
  32     for(int i=1;i<=10;i++){
  33       numbers.Add(i);
  34     }
  35 
  36     var oddNumbers = new List<int>();
  37     foreach(var nr in numbers){
  38       if( nr%2==0){
  39         oddNumbers.Add(nr);
  40       }
  41     }
  42 
  43    var oddNumbersLinq = numbers.Where( x => x%2==0).ToList();
  44    
  45    var fromNormal = new NormalFilter().filterNumbers(numbers);
  46    var fromLinq =  new LinqFilter().filterNumbers(numbers);
  47 
  48    fromNormal.ForEach(x => Console.WriteLine(x) );
  49    fromLinq.ForEach(x => Console.WriteLine(x) );
  50   }
  51 }

Other implementation

   1 using System;
   2 using System.Collections.Generic;
   3 using System.Linq;
   4 
   5 namespace Even{
   6   public interface IFilter{
   7     IEnumerable<int> FilterEven(IList<int> data);
   8   }
   9 
  10   public class NormalLoop : IFilter {
  11     public IEnumerable<int> FilterEven(IList<int> data){
  12       List<int> ret = new List<int>();
  13       for(var i=0; i<data.Count; i++){
  14         if( data[i]%2 ==0 ){
  15           ret.Add(data[i]);
  16         }
  17       }
  18 
  19       return ret;
  20     }
  21   }
  22 
  23   public class LinqLoop : IFilter {
  24     public IEnumerable<int> FilterEven(IList<int> data){
  25       return data.Where(nr => nr % 2 == 0); 
  26     }
  27   }
  28 
  29   public class MainClass {
  30     public static void Main (string[] args) {
  31       int[] i={1,2,3,4,5,6,7,8,9,10};
  32       IFilter loop = new NormalLoop();
  33       IFilter loopLinq= new LinqLoop();
  34 
  35       Console.WriteLine("Normal impl");
  36       foreach(var item in loop.FilterEven(i) ){
  37         Console.WriteLine(item);
  38       }
  39       Console.WriteLine("Linq impl");
  40       foreach(var item in loopLinq.FilterEven(i) ){
  41         Console.WriteLine(item);
  42       }
  43     }
  44   }
  45 }

CSharp (last edited 2025-02-28 15:32:19 by vitor)