Random Noise

cat /dev/random >> /dev/dsp

Archive for the ‘.NET’ Category

Print TRX Header (Router Firmware)

leave a comment »


[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TRXHeader
{
    public UInt32 Magic;                 /* "HDR0" */
    public UInt32 Len;                   /* Length of file including header */
    public UInt32 CRC32;                 /* 32-bit CRC from flag_version to end of file */
    public UInt16 Flag;                  /* flags */
    public UInt16 Version;               /* version */
    
    public UInt32 LzmaLoaderOffset;
    public UInt32 KernelOffset;
    public UInt32 RootFSOffset;
    public UInt32 BinHeaderOffset;       /* Only valid for V2 */
};

void Main()
{
    PrintTRXHeader(@"ea9500.img");
}

public static void PrintTRXHeader(string path)
{
    using (FileStream fileStream = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read))
    {
        Console.WriteLine("\r\n************ {0} ***************\r\n", path);

        var header = fileStream.ReadStruct<TRXHeader>();
        Console.WriteLine("TRX Magic = 0x{0:X}", header.Magic);
        Console.WriteLine("File Length = {0}", header.Len);
        Console.WriteLine("CRC = 0x{0:X}", header.CRC32);
        Console.WriteLine("Flag = {0}", Convert.ToString(header.Flag, 2));
        Console.WriteLine("Version = {0}", header.Version);
        Console.WriteLine("LzmaLoaderOffset = 0x{0:X}", header.LzmaLoaderOffset);
        Console.WriteLine("KernelOffset = 0x{0:X}", header.KernelOffset);
        Console.WriteLine("RootFSOffset = 0x{0:X}", header.RootFSOffset);
        Console.WriteLine("BinHeaderOffset = 0x{0:X}\r\n", header.BinHeaderOffset);
    }
}

public static class StreamExtensions
{
    public static T ReadStruct<T>(this Stream stream) where T : struct
    {
        var sz = Marshal.SizeOf(typeof(T));
        var buffer = new byte[sz];
        stream.Read(buffer, 0, sz);
        var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
        var structure = (T)Marshal.PtrToStructure(
            pinnedBuffer.AddrOfPinnedObject(), typeof(T));
        pinnedBuffer.Free();
        return structure;
    }
}

Advertisements

Written by Vivek Unune

February 1, 2017 at 8:34 pm

Posted in .NET, Hardware, openwrt

Tagged with , ,

MSBuild Task: Solution and Project dependencies

leave a comment »

Few months ago I needed to use MSbuild to build solution. Sounds simple right? Yeah, but not quite.
Somehow, my msbuild failed with project dependency issues. It turns out that MSBuild doesn’t respect project dependencies in a solution. Google “msbuild solution dependencies” and you’ll find various post complaining about the problem with MSBuild.

I modified the MSBuild task found here to get projects in a solution file in dependency order.

You can then call the task to get the projects and compile them in order:

<Target Name="BuildProjects">
		<GetProjecsInOrder Solution="$(MSBuildProjectDirectory)\MySolution.sln">
		  <Output ItemName="ProjectFiles" TaskParameter="Output"/>
		</GetProjecsInOrder>

		<MSBuild Projects="%(ProjectFiles.FullPath)"
				 Targets="Build"
				 Properties="Configuration=Release"/>
</Target>

You can download the modified source from http://www.esnips.com/doc/8e232db4-21ac-4d93-90dc-2a8bc4db34a8/MSBuildTasks

Written by Vivek Unune

December 16, 2009 at 8:50 pm

Posted in .NET

Tagged with

IDataReader GetValue Extension method

with 2 comments

It is offten desired to get a value from DataReader using column name with known Type. For example you want to get a string value of column ‘first_name’ and int value of column ‘account_number’. The following extension method makes it easy to fetch values from a DataReader using Type and column name:

public static class ReaderHelper
{
    public static bool IsNullableType(Type valueType)
    {
        return (valueType.IsGenericType &&
            valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }

    public static T GetValue<T>(this IDataReader reader, string columnName)
    {
        object value = reader[columnName];
        Type valueType = typeof(T);
        if (value != DBNull.Value)
        {
            if (!IsNullableType(valueType))
            {
                return (T)Convert.ChangeType(value, valueType);
            }
            else
            {
                NullableConverter nc = new NullableConverter(valueType);
                return (T)Convert.ChangeType(value, nc.UnderlyingType);
            }
        }
        return default(T);
    }
}

It can be used as:

User GetUser(IDataReader reader)
{
    User user = new User();
    user.FirstName = reader.GetValue<string>("first_name");
    user.LastName = reader.GetValue<string>("last_name");
    user.Email = reader.GetValue<string>("email");
    user.AccountNumber = reader.GetValue<int>("account_number");
    user.NumberOfVehiclesOwned = reader.GetValue<int?>("vehicle_count"); // nullable data field
    return user;
}

Written by Vivek Unune

July 15, 2009 at 9:27 pm

Posted in .NET

Tagged with ,

RotateString v2.0

leave a comment »

I added the ability to rotate string right or left. Here is the code:


public enum Direction { Right, Left }

string rotateString(string source, int rotationCount, Direction direction)
{
    if (String.IsNullOrEmpty(source) || rotationCount <= 0)
        return source;

    int pivot = 0;
    List<int> delimiterLocations = new List<int>();
    char[] sourceChars = new char[source.Length];

    char temp;
    // Reverse the whole string and
    // save the dilimiter locations
    for (int i = 0; i < source.Length; i++)
    {
        sourceChars[source.Length - i - 1] = source[i];

        if (source[i] == ' ')
            delimiterLocations.Add(source.Length - i - 1);
    }

    // calculate neededDelimiters mod wordCount
    // (assume words = delimiterCount + 1)
    pivot = rotationCount % delimiterLocations.Count;

    if (pivot > 0)
    {
        if (direction == Direction.Left)
            pivot = delimiterLocations.Count - pivot;

        pivot = delimiterLocations[delimiterLocations.Count - pivot];
    }
    else
    { return source; }

    // reverse the first part
    for (int i = 0, j = pivot - 1; i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    // reverse the second part
    for (int i = pivot + 1, j = sourceChars.Length - 1;
         i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    return new string(sourceChars);
}

Written by Vivek Unune

September 27, 2008 at 4:46 pm

Posted in .NET

Tagged with ,

StackOverflow – RotateString

with 4 comments

Someone asked the following question on StackOverflow. Before I could post my answer, it was removed. Hmm, so He/She tried to abuse StackOverflow! Anyway, I found that question interesting.

The question was to write a function to rotate a string of words. Words are separated by ‘ ‘ (space). In the result string, the words should remain human readable. The function will also take an integer argument that will specify number of words to rotate.

example:

string source = “A quick brown fox jumps over the lazy dog.”

rotateString(source, 3);

Should give:

the lazy dog. A quick brown fox jumps over

Here is my solution:

static string rotateString(string source, int rotationCount)
{
    if (String.IsNullOrEmpty(source) || rotationCount <= 0)
        return source;

    int pivot = 0;
    List<int> delimiterLocations = new List<int>();
    char[] sourceChars = new char[source.Length];

    char temp;
    // Reverse the whole string and
    // save the dilimiter locations
    for (int i = 0; i < source.Length; i++)
    {
        sourceChars[source.Length - i - 1] = source[i];

        if (delimiterLocations.Count < rotationCount && source[i] == ' ')
            delimiterLocations.Add(source.Length - i - 1);

    }

    // calculate neededDelimiters mod wordCount
    // (assume words = delimiterCount + 1)
    pivot = rotationCount % (delimiterLocations.Count + 1);

    if (pivot > 0)
        pivot = delimiterLocations[pivot-1];
    else
        return source;

    // reverse the first part
    for (int i = 0, j = pivot - 1; i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    // reverse the second part
    for (int i = pivot + 1, j = sourceChars.Length - 1;
         i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    return new string(sourceChars);
}

Written by Vivek Unune

September 25, 2008 at 5:04 am

Posted in .NET

Tagged with ,

Asynchronous Delegates in .NET 2.0

leave a comment »

One of the good features of .NET 2.0 is Asynchronous Delegates. Use these when you want to maintain the application responsive and reliable. Especially when the application wants to complete an IO call, database call, web service call or number crunching (CPU intensive) that can take up fairly long time. For example refreshing of the UI is handled by a single main thread. Which means all the events such as mouse click, mouse movement, keyboard events and even displaying text to the console are handled by this single thread. In this case we were told that we should use threads, i.e. spawn a worker thread and return quickly. But in .NET it is efficient to re-use threads, i.e. borrow them from .NET ThreadPool and not instantiate them. Jeffrey Richter goes on to describe in detail why so in this interview. To simply summarize Jeffrey I can say that spawning a new thread is a costly affair. One of the ways to re-use/borrow threads is to use Asynchronous Delegates. Asynchronous pattern basically involves fire and forget. Once the result is available .NET will call back a method that you must specify during the initial call.

The .NET runtime generates BeginInvoke and EndInvoke methods for each delegate defined. BeginInvoke is a non blocking method and returns right away.Lets take an example of a method that takes long time

public int MySlowTask(int someInput)
{
//simulate slow task
Thread.Sleep(20);
Console.WriteLine(“Processed input : {0}”,someInput);
return someInput+1;
}

In order to call a method asynchronously we must define a delegate with same method singnature as that method.

delegate int SlowTaskDelegate(int someInput);
SlowTaskDelegate slowTaskDelegate = MySlowTask;

Then we call the BeginInvoke method to call the long task asynchronously.

slowTaskDelegate.BeginInvoke(10, // Input parameter to MySlowTask()
EndInvokeMySlowTask, // Callback Method
slowTaskDelegate); // AsyncState

We must also write EndInvokeMySlowTask method (a callback method) that the runtime calls after completing the task.Its signature is fixed defined as
void MethodName(IAsyncResult result):

public void EndInvokeMySlowTask(IAsyncResult result)
{
SlowTaskDelegate myDelegate = result.AsyncState as SlowTaskDelegate;
// obtain the result
int resultVal = myDelegate.EndInvoke(result);
Console.WriteLine(“Returned output : {0}”,resultVal);
}

Written by Vivek Unune

September 9, 2007 at 2:30 am

Posted in .NET

Tagged with , , ,