Basic information for c#

6 minute read

URL encoder/decoder

base64 encode

base64 decode

Encoding/Decoding, base64

You can send parameters to a url using URL-encoded base64 string. I would recommend to use both encodings in order to pass url with GET parameters. URL Encoded string can include “.” and base64 encoded string can include “/”, “+”, “=”. If you want to convert both “/” and “.” from url you can use both encodings together.

plain text -> base64 string -> encoded string

string plainstr = "http://testurl.com";
byte[] byarr = System.Text.Encoding.ASCII.GetBytes(plainstr); // aHR0cDovL3Rlc3R1cmwuY29t
string base64str = Convert.ToBase64String(byarr);
string encodedstr = Server.UrlEncode(base64str); // aHR0cDovL3Rlc3R1cmwuY29t

encoded base64 string -> decoding -> ascii string

string encodedstr = "aHR0cDovL3Rlc3R1cmwuY29t";
string base64str = Server.UrlDecode(encodedstr); // http://testurl.com
byte[] byarr = System.Convert.FromBase64String(base64str);
string plainstr = System.Text.ASCIIEncoding.ASCII.GetString(byarr); // http://testurl.com

How to get random string

/// <summary>
/// Get random string
/// </summary>
/// <remarks></remarks>
public static string getRandomStr(int strlen)
{
    string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= strlen; i++)
    {
        int idx = r.Next(0, s.Length - 1);
        sb.Append(s.Substring(idx, 1));
    }
    return sb.ToString();
}

Basic grammars of C#

Switch/case, while, do while, for statement

switch (e.ConnectionStatus)
{
    case 1: { SetStatusBarText("Logon failed.."); } break;
    case 2: { SetStatusBarText("Forced logout.."); } break;
    case 3: { SetStatusBarText("Obsolete version.."); } break;
    case 4: { SetStatusBarText("Wrong Environment.."); } break;
    case 5: { SetStatusBarText("Database Error.."); } break;
    case 6: { SetStatusBarText("Logon invalid user name.."); } break;
    case 7: { SetStatusBarText("Logon rejected.."); } break;
}

String vs string

There is no difference between them. string is an alias in C# for System.String. It’s like int vs. System.Int32. It’s generally recommended to use String if you need to refer specifically to the class.

string place = "world";
string greet = String.Format("Hello {0}!", place);

C# data types

  • object: System.Object
  • string: System.String
  • bool: System.Boolean
  • byte: System.Byte
  • sbyte: System.SByte
  • short: System.Int16
  • ushort: System.UInt16
  • int: System.Int32
  • uint: System.UInt32
  • long: System.Int64
  • ulong: System.UInt64
  • float: System.Single
  • double: System.Double
  • decimal: System.Decimal
  • char: System.Char

Region

#Region "Your_region_name_here"
    // Your codes are here
#End Region

Exception handling

try {

}
catch(Exception e) {
	Console.WriteLine(e.Message + e.StackTrace);
	throw (e);
}

finally {

}

String format

string str = string.Format("ERROR:{0}", se.Message)
e.DisplayText = string.Format("{0:#,##0}", e.Value);

string statmsg = String.Format("[{0}][{1,-15}]:{2}", pLogMod, ClassName, logmsg);
string FullLogMsg = String.Format("[{0}][{1}][{2,-23}][{3,-15}][{4,4}]:{5}", pLogMod, Utils.GetDateTime(), execName, ClassName, CallStack.GetFileLineNumber(), logmsg);

// String.Format
string str = String.Format("MktCd{0}GrpNo{1}ReqCd{2}DatCls{3}", sMktCode, sProdGroup, sDataType, sDataClass);

Type conversion

    double d = 123456790.10;
    textBox.Text = d.ToString("#,#0.00");
    double d = Convert.ToDouble(textBox.Text);
    char arrC = (char)67;

    // byte ---> string
    arr = 67;
    char ch = (char)arr;
    string = ch.ToString();
    Result: C

    arr = 67;
    string = arr.ToString();
    Result: 67

    // byte[] ---> string
    string recvdatatmp = Encoding.Default.GetString(arrData, 0, arrData.Length);

    // string ---> byte[]
    byte[] arrMsgID;
    arrMsgID = System.Text.Encoding.ASCII.GetBytes(MsgCode);

    // char ---> string
    string = "a";
    char = char.Parse(str);

    // char ---> string
    char ch = 'a';
    string = ch.ToString();

    // char[] ---> string

    // A. 15 character array.
    char[] cArr = new char[4];
    cArr[0] = 'O';
    cArr[1] = 'n';
    cArr[2] = 'l';
    cArr[3] = 'y';

    // B. 15 character string.
    string StrTmp = new string(cArr);
    Console.WriteLine(StrTmp);
    
    // string ---> char[]

    // string ---> int
    Int32.TryParse(lvi.SubItems[index].Text, out count) ? (++count).ToString() : "1";
    RecvMsgLen = int.Parse(Encoding.Default.GetString(arrTemp, 0, MSG_LEN_SIZE));

    // int ---> string
    int iWaitingCnt = dtTemp.Select("TRIM(AGT_STAT) = 'W'").Length;
    lblEmployeeWaitValue.Text = iWaitingCnt.ToString();
    
    int.Parse(arrRow[0]["WAIT"].ToString())
    
    Convert.ToString()
    
    //--------------------------------------------------------
    // string => hex number
    //--------------------------------------------------------
    byte []tmpArr = new byte[256];
    tmpArr[0] = byte.Parse("36", System.Globalization.NumberStyles.HexNumber);
    tmpArr[1] = byte.Parse("37", System.Globalization.NumberStyles.HexNumber);
    string str = Encoding.Default.GetString(tmpArr, 0, 2);
            
    //--------------------------------------------------------
    // enum
    //--------------------------------------------------------
    enum Colors 
    { 
        None = 0, 
        Red = 1, 
        Green = 2, 
        Blue = 4, 
        Yellow = 8, 
        Black = 16 
    };

Functions

String.Format

  1. zero padding : {0,0#} 01 02 03…

  2. separate by comma {0,10:#,##0} 123456 => [ 123,456]

Padding

sr.WriteLine(GetDateTime().PadRight(16));

Split

string[] result = lsStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

Array

private byte[] STX = new byte[] { 2, 2 };
private byte[] ETX = new byte[] { 3, 3 };

byte []tmpArr = new byte[256];

// Copy
Array.Copy(RecvByte, 0, RecvByteFull, 0, liRtn);
Array.Copy(src, src_idx, desc, dest_idx, len);

IEnumerator vs IEnumerable

IEnumerator

  • MoveNext()
  • Reset()

IEnumerable

  • GetEumerator()
class Program
{
    static void Main(string[] args)
    {
        /// <summary>
        /// Using IEnumerable interface
        /// </summary>
        string[] strList = { "jeong", "kang", "won", "lee", "hee" };
 
        IEnumerator e = strList.GetEnumerator();
 
        while (e.MoveNext())
        {
            Console.WriteLine(e.Current);
        }
 
        //Console.WriteLine(e.Current);
             
        e.Reset();
        e.MoveNext();
        Console.WriteLine(e.Current);  // Output: "jeong"
 
        Console.ReadLine();
    }
}


class Program
{
    static void Main(string[] args)
    {
        // Linq
 
        /// <summary>
        /// using IEnumerable interface
        /// </summary>
        string[] strList = { "jeong", "kang", "won", "lee", "hee" };
 
        //IEnumerable<string> enumerable = strList.Where(str => str.Length <= 3);
        IEnumerable<string> enumerable = from str in strList where str.Length <= 3 select str;
 
        IEnumerator<string> e = enumerable.GetEnumerator();
 
        while (e.MoveNext())
        {
            Console.WriteLine(e.Current);
        }
 
        Console.ReadLine();
 
    }
}

String array

// Add check items to the control’s dropdown. string[] itemValues = new string[] { “Circle”, “Rectangle”, “Ellipse”, “Triangle”, “Square” }; foreach (string value in itemValues) checkedComboBoxEdit1.Properties.Items.Add(value, CheckState.Unchecked, true);

// Specify the separator character. checkedComboBoxEdit1.Properties.SeparatorChar = ‘;’;

// Set the edit value. checkedComboBoxEdit1.SetEditValue(“Circle; Ellipse”);

// Disable the Circle item. checkedComboBoxEdit1.Properties.Items[“Circle”].Enabled = false;

//——————————————————– // Structure Array //——————————————————–

public static DWS_DATA []data = new DWS_DATA[4096];

//——————————————————– // Structure //——————————————————–

 [StructLayout(LayoutKind.Sequential)]
    public struct ReqFoStock
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
        public char[] rcvd_time; /* YYYYMMDDHHMMSSss */

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public char[] data_type;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public char[] data_class;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public char[] mkt_code;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public char[] prod_group;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public char[] num_stock;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
        public char[] glid;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
        public char[] stock_code;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public char[] proc_type;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public char[] data_seqno;
    }
   
using fo_feed_sender;
using System.Runtime.InteropServices;   
   
            int liRtn = 0;
            FileStream fr;

            ReqFoStock symbol = new ReqFoStock();
            int StcSize = Marshal.SizeOf(symbol);
            byte[] bStrData = new byte[StcSize];

            string FileFullName = "E:\\Sym\\fo.sym_1023";

            fr = new FileStream(FileFullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            liRtn = fr.Read(bStrData, 0, bStrData.Length);

            //Console.WriteLine(Encoding.Default.GetString(bStrData, 0, liRtn));
            memoEdit1.Text = Encoding.Default.GetString(bStrData, 0, liRtn);

            fr.Close();

byte to structure

    ReqFoStock symbol = new ReqFoStock();
    int StcSize = Marshal.SizeOf(symbol);
    byte[] bStrData = new byte[StcSize];
                
    symbol = (ReqFoStock)ByteToStructure(bStrData, typeof(ReqFoStock));

    /// <summary>
    /// Byte to Structure
    /// </summary>
    /// <param name="data">byte array</param>
    /// <param name="type">Structure type</param>
    /// <returns>structure</returns>
    public object ByteToStructure(byte[] data, Type type)
    {
        IntPtr buff = Marshal.AllocHGlobal(data.Length);

        Marshal.Copy(data, 0, buff, data.Length);
        object obj = Marshal.PtrToStructure(buff, type);
        Marshal.FreeHGlobal(buff);

        return obj;
    }

    /// <summary>
    /// Structure to byte
    /// </summary>
    /// <param name="obj">struture</param>
    /// <returns>byte</returns>
    public byte[] StructureToByte(object obj)
    {
        int datasize = Marshal.SizeOf(obj);

        IntPtr Buff = Marshal.AllocHGlobal(datasize);

        Marshal.StructureToPtr(obj, Buff, true);
        byte[] data = new byte[datasize];
        Marshal.Copy(Buff, data, 0, datasize);
        Marshal.FreeHGlobal(Buff);
        return data;
    }
// Read from structure
string str = new string(symbol.mkt_code);

Etc

//--------------------------------------------------------
// Call by reference
//--------------------------------------------------------
ClientAPIMethods.DoCountTraders(ref traderCount);

//--------------------------------------------------------
// MessageBox
//--------------------------------------------------------
MessageBox.Show("ERROR : " + ex.Message, "Error Message");

//--------------------------------------------------------
// Color and font
//--------------------------------------------------------
lcTemp.BackColor = Color.Transparent;
lcTemp.ForeColor = Color.FromArgb(0, 0, 64);

xxx.Font = new Font("Tahoma", 8f);
e.Appearance.Font = new Font("FixedSys", 10f, FontStyle.Bold);

//--------------------------------------------------------
// TCP/UDP carriage return
//--------------------------------------------------------
cf. vbCr, vbLf, vbCrLf
Encoding.Default.GetString(buffer, 0, charLen).Replace("\n", "\r\n");

//--------------------------------------------------------
// Performance
//--------------------------------------------------------
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
for (int idx = 0; idx < 1000000; idx++)
{
    WriteSnapData2(idx.ToString() + " cccc");
}
MessageBox.Show("watch2:" + watch.Elapsed);

Autoscroll

//----------------------------------
// autoscroll
//----------------------------------

<TextBox>
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();

<ListBox>
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.SelectedIndex = -1;

<ListView>
listView1.EnsureVisible(listView1.Items.Count - 1);

<TreeView>
treeView1.Nodes[treeView1.Nodes.Count - 1].EnsureVisible();

<DataGridView>
dataGridView1.FirstDisplayedCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];

<enXpert GridView>
// Move scroll to the end of the grid
gridView1.FocusedRowHandle = gridView1.RowCount -1;

Tags:

Categories:

Updated:

Leave a comment