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

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



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:

Scenario:
When an application starts, a new instance of object [class] is being created.

Scenario translated to code:

<%@ Application Language=”C#” %>
<%@ Import Namespace=”MyCustomClasses” %>

<script runat=”server”>

public CustomClass _myClass = null;

void Application_Start(object sender, EventArgs e)
{
if (_myClass == null)
_myClass = new CustomClass();
}

</script>

Problem:
1) How to access this very instance in other classes inside the same Solution?
2) How do you access it from an external Solution?

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

1) How to access this very instance in other classes inside the same Solution?

We can have two possible solutions to this problem.

First, we use the Application variable and put our object’s instance to it.

When application starts, we use:

void Application_Start(object sender, EventArgs e)
{
if (_myClass == null)
_myClass = new CustomClass();

Application["myClass"] = _myClass;
}

And then we access it as:

(CustomClass) Application["myClass"]

We can also use Singleton Design Pattern where we are hiding the constructor of the class. With this, we can be sure that we are only using a single instance of the class within the scope of our application.

using System;

namespace MyCustomClasses
{
public class CustomClass
{

private static CustomClass instance;
private static object sync = new object();

private CustomClass()
{
// put your current constructor logic here, you will notcie the constuctor is marked private,
// this will stop this class being able to be instantiated directly.
}

// ** only provide one copy of this class for the system, synchronized access
public static CustomClass GetInstance()
{
// handle concurrent access.
lock (sync)
{
if (instance == null)
{
instance = new CustomClass(); // this is were the single instance of the class is  created
}
return instance;
}
}

We can then access it as:

CustomerClass.GetInstance()

2) How do you access it from an external Solution?

We can add WebService inside our Application and return the class instance inside a webmethod

Using the first approach above:

[WebMethod]
public CustomClass GetMyClassInstance()
{
return ((CustomClass) Application["myClass"]);
}

Using the second approach:

[WebMethod]
public CustomClass GetMyClassInstance()
{
CustomClass.GetInstance();
}

We can then consume this Web Service from a different Solution and call it as:

CustomClass.MyWebService MyWS = new CustomClass.MyWebService
MyWS.GetMyClassInstance()



Tags: