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:

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:

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:

This is a sample function on how to move a file from one folder/directory to another while considering some factors such as:

  • Is the file available? Or is it being used by another process?
  • Does the file exists?
  • Does a file with the same filename exists in the destination folder?

Move File Function

‘fromFile and toFile parameters consist of directory-path+filename+extension
Public Function MoveFile(ByVal fromFile As String, ByVal toFile As String) As Boolean

‘Check if File do exists
Dim fileExists As Boolean = System.IO.File.Exists(fromFile)

‘Check if File is being use by other process
Dim fileIsLock As Boolean = IsFileLocked(fromFile)

‘If file do exists and is not lock, begin transfer
If fileExists AndAlso Not fileIsLock Then

‘Check if file already exists in the destination folder
If System.IO.File.Exists(toFile) Then

‘delete file from destination folder and move new file [overwrite]
System.IO.File.Delete(toFile)
System.IO.File.Move(fromFile, toFile)
Return True

‘Of course you can always check the destination file information,
‘and maybe decide whether to delete it or not and just rename the new file
‘Example by getting file information
Dim destFile As New FileInfo(toFile)

‘Get size [in bytes]
If destFile.Length > 0 Then
‘decide what to do here if the destination file has some contents
‘you might not want to overwrite it if it contains important data
End If

Else
‘If the file does not exists in the destination folder, just move
System.IO.File.Move(fromFile, toFile)
Return True
End If
Else
Return False
End If

End Function

Simple Function to check if file is locked

Public Function IsFileLocked(ByVal strFullFileName As String) As Boolean
Dim returnVal As Boolean = False
Dim fs As System.IO.FileStream = Nothing

Try
fs = System.IO.File.Open(strFullFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.None)
Catch ex As Exception
returnVal = True
Finally
If fs IsNot Nothing Then
fs.Close()
End If
End Try

Return returnVal
End Function



Tags:

I’m currently using Telerik Treeview and I’m fascinated on how great its features are.  I have an example on NodeClick event.

Highlight parent/s when a node is clicked

The Treeview

<telerik:RadTreeView ID=”MyTreeview” MultipleSelect=”true” OnNodeClick=”MyTreeviewClick” />

Note: MultipleSelect must be set to True

The Click routine

Protected Sub MyTreeviewClick(sender As Object, e As RadTreeNodeEventArgs)
SelectParent(e.Node)
End Sub

Highlight parent function

Protected Sub SelectParent(node As RadTreeNode)
If node.ParentNode IsNot Nothing Then
node.ParentNode.Selected = True
End If
End Sub

If you want to highlight all parents of selected node, you can always call it recursively

Protected Sub SelectParent(node As RadTreeNode)
If node.ParentNode IsNot Nothing Then
node.ParentNode.Selected = True
SelectParents(node.ParentNode)
End If
End Sub

Calling a routine on selected node

You can use a variety of Nodes properties and functions. In this example I use node’s level property which returns the level [integer] of the the current node. This is helpful if you have static node levels. I’m calling my function ONLY on specific node level.

Protected Sub MyTreeviewClick(sender As Object, e As RadTreeNodeEventArgs)
If e.Node.Level = 2 Then
//Do something here when any of the 2nd level node is clicked
End If
End Sub

You can also use this to highlight parents only on selected node levels.

Protected Sub MyTreeviewClick(sender As Object, e As RadTreeNodeEventArgs)
If e.Node.Level = 2 Then
SelectParent(e.Node)
End If
End Sub

Hope this helps :)



Tags:

« Previous Entries