codehutch.com

Online Code Repository

C#: Reverse a String

Reversing a string in C# is quite easy. The main concept is to treat the string as an array of characters, which is already built-in in C#, and transfer each character to new container in reverse order. Here are the samples of simple and straightforward functions on how to reverse a string in C#.

Manual reverse transfer using for-loop

public static string ReverseByTransfer(string str)
{
int strlen = str.Length;
char[] arr = new char[strlen];

for (int i = 1; i <= strlen ; i++)
{
arr[i-1] = str[strlen - i];
}

return new string(arr);
}

Convert string to character-array and use Array’s Reverse function

public static string ReverseByConvert(string str)
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}

DOWNLOAD REVERSE STRING CODE

===================



Tags:

XOR Encryption

XOR (Exclusive OR, EOR, EXOR) is a logical operation which results to a true value if exactly one of the two operands has a value of true.

Sample XOR Table

INPUT OUTPUT
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Using this knowledge we can encrypt characters using their binary values. Take for example the string “ENCRYPT”. First, we take the ASCII Code of each character in this string and convert each to their respective binary value.

E - 69 - 1000101
N - 78 - 1001110
C - 67 - 1000011
R - 82 - 1010010
Y - 89 - 1011001
P - 80 - 1010000
T - 84 - 1010100

Note: Small letters have different ASCII values.

Choose a random encryption key, say “X”. X has an ASCII Code of 88 and binary value of 1011000. If we perform XOR on “ENCRYPT” against “X”, we get:

1000101 ^ 1011000 = 0001101 [29]
1001110 ^ 1011000 = 0010110 [22]
1000011 ^ 1011000 = 0011011 [27]
1010010 ^ 1011000 = 0001010 [10]
1011001 ^ 1011000 = 0000001 [1]
1010000 ^ 1011000 = 0001000 [8]
1010100 ^ 1011000 = 0001100 [12]

Looking up these numbers in ASCII Code Table, we get:

Thus, the string “ENCRYPT” will be encrypted to:

Putting it in Codes [C#]

Encrypt:

public static string Encrypt(string orgStr, char keyChar)
{
string encrypted = “”;
for (int i = 0; i < orgStr.Length; i++)
{
encrypted += (char)(orgStr[i] ^ keyChar);
}

return encrypted;
}

Decrypt:

public static string Decrypt(string orgStr, char keyChar)
{
string decrypted = “”;
foreach (char encChar in orgStr.ToCharArray())
{
decrypted += (char)(encChar ^ keyChar);
}

return decrypted;
}

Usage:

string encStr = Encrypt(”TEST”, ‘X’);
Console.WriteLine(”Original String: TEST”);
Console.WriteLine(”Encrypted String: ” + encStr);
Console.WriteLine(”Decrypted String: ” + Decrypt(encStr, ‘X’));

Result:

DOWNLOAD XOR ENCRYPTION CODE

===================



Here is a sample source code on how to read and load xml file via LINQ, extract the data [using a query] and export it to a CSV file.

The XML file (employee.xml)

<xml>
<Employee id=”1″>
<Name>John Doe</Name>
<Position>President</Position>
<Salary>$500,000</Salary>
</Employee>
<Employee id=”2″>
<Name>Jane Doe</Name>
<Position>Vice President</Position>
<Salary>$250,000</Salary>
</Employee>
<Employee id=”3″>
<Name>Jen Doe</Name>
<Position>Manager</Position>
<Salary>$50,000</Salary>
</Employee>
</xml>


The code

‘Libraries
Imports System
Imports System.IO
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.VisualBasic.FileIO

‘=====================================

‘Read/Load xml file
Dim employees As XElement = XElement.Load(”employee.xml”)
Dim outputData As New StringBuilder

‘query on loaded xml data and output as String Enumeration
Dim xmlData = _
From emp In employees.<Employee> _
Select String.Format(”"”{0}”",”"{1}”",”"{2}”",”"{3}”"”, _
emp.@id, _
emp.<Name>.Value, _
emp.<Position>.Value, _
emp.<Salary>.Value)

‘Traverse enum and append extracted data
For Each row In xmlData
outputData.AppendLine(row)
Next

‘Output as .txt file
File.WriteAllText(”ParsedData.csv”, outputData.ToString)

The output as CSV file (ParsedData.csv)

“1″,”John Doe”,”President”,”$500,000″
“2″,”Jane Doe”,”Vice President”,”$250,000″
“3″,”Jen Doe”,”Manager”,”$50,000″



Tags:

There are cases where using Cursor would do you more harm than good. It uses considerably large amount of resources in your server and not to mention that it can cause leaks if not used correctly (Eg. Open without corresponding Close). That’s why most T-SQL developer often suggest to avoid it whenever possible. Here is a sample code on how to travese a result set and get values of each row using a While Loop instead of a Cursor.

–identity INT (1,1) - surrogate PRIMARY KEY
declare @tempTable table(id int identity(1,1),employeeName varchar(25),employeePosition varchar(25))

insert into @tempTable
select ‘John’,'Manager’

insert into @tempTable
select ‘Joe’,'Vice President’

insert into @tempTable
select ‘Mary’,'Secretary’

declare @rowCount int
select @rowCount = count(*) from @tempTable

declare @counter int
select @counter = 1

while @counter <= @rowCount
begin

select * from @tempTable where id = @counter

select @counter = @counter + 1
end



Tags:

This source code shows how to lock a certain routine so it cannot be accessed/used by another process. To demonstrate this, we will use Threads.

using System;
using System.Threading;

class ThreadLock
{

private int Tests = 0;

public void TestRun()
{
Thread t1 = new Thread(new ThreadStart(Exec));
t1.Name = “thread 1″;
Thread t2 = new Thread(new ThreadStart(Exec));
t2.Name = “thread 2″;
t1.Start();
t2.Start();
}

public void Exec()
{
while (Tests < 5)
{
lock (this)
{
int count = Tests;
count++;
Console.WriteLine(count + “: ” + Thread.CurrentThread.Name);
Thread.Sleep(1000);
Tests = count;
}
}
}

static void Main(string[] args)
{
ThreadLock test = new ThreadLock();
test.TestRun();
}
}

Result
How to Lock a Routine in C#



Tags:

« Previous Entries