Archive for the ‘C#’ Category

Today’s post is a small code snippet for you to write byte array to an xml file using FileStream and Binary Writer class’s Write method.Hope this helps 🙂

private void ByteArrayToFile(string fileName, byte[] byteArray)
FileStream fs = new FileStream(fileName + ".xml", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode);

My previous post if you had seen,I talked about writing  eventlogs using Log4Net.You can always use the Windows Event Viewer to see the logs.But in case you cannot directly login to machine,you may want to read the logs from code.Here I am sharing a codesnippet on how you you can read using LINQ and bind to a gridview control.

            eventlog.MachineName = whichmachine;
           //this reads the name from a dropdown say for eg Application logs you selected
            eventlog.Log = ddleventlogs.Items[ddleventlogs.SelectedIndex].Value.ToString();
            //queries logs under Application from a selected source         
            var query = from EventLogEntry eventlogentry in eventlog.Entries
                        where eventlogentry.Source == ddleventsource.Text
                        select new
                            Time = eventlogentry.TimeGenerated,
                            Source = eventlogentry.Source,
                            Message = eventlogentry.Message

            eventviewgrid.DataSource = query.ToList();

Is that not simple?LINQ rocks always 🙂

How to run an exe from C#?

Posted: February 5, 2011 in C#

In my previous post I talked about how VS external tools , the exes can be called from Visual Studio itself.If I had not figured out this,I seriouly had some plans to write an application which can group all these exes together :).

If you do not know how an external exe can be called from .Net Application,its simple;use the Process class found in the System.Diagnostics namespace.

      Process proc = new Process();
      proc.StartInfo.FileName = @"Notepad.exe";

Read more about this here

Hope this information helps you sometime!

Exception: System.InvalidCastException: Unable to cast object of type ‘Oracle.DataAccess.Client.OracleParameter’ to type ‘System.IConvertible’.
at System.Convert.ToDateTime(Object value)
at Oracle.DataAccess.Client.OracleParameter.PreBind_Date()
at Oracle.DataAccess.Client.OracleParameter.PreBind(OracleConnection conn, IntPtr errCtx, Int32 arraySize)
at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()

What this means?
‘System.IConvertible’ interface provides methods to convert the value of an instance of an implementing type to a common language runtime type like Boolean,Int32, UInt32, Int64,DateTime, Char,String etc that has an equivalent value.

public static OracleParameter AddInParameter(string paramName, OracleDbType paramType, object paramValue)
OracleParameter cmdParam = new OracleParameter(paramName, paramType);
cmdParam.Value = paramValue;
cmdParam.Direction = ParameterDirection.Input;
return cmdParam;

OracleParameter paramCreatedDate = new OracleParameter();
if (string.Equals(CREATION_DATE, DateTime.MinValue))
paramCreatedDate.Value = DateTime.Now;
paramCreatedDate.Value = CREATION_DATE;

Here in the below code it throws InvalidCastException “Unable to cast object of type ‘Oracle.DataAccess.Client.OracleParameter’ to type ‘System.IConvertible'”.

//Throws exception Unable to cast object of type
//'Oracle.DataAccess.Client.OracleParameter' to type 'System.IConvertible'.

What is the fix? And Why this occured?

It’s trying to convert OracleParameter to DateTime.If there is no meaningful conversion to a common language runtime type, then a particular interface method implementation throws InvalidCastException.You were supposed to pass paramCreatedDate.Value instead of paramCreatedDate


Hope this gives you some information on why InvalidCastException occurs & how to fix this for any type conversion similar to this 🙂

Did you know that LINQ simplifies working with XML data & you need not use Xpath or XQuery for reading XML?Below code queries the xml & populates the listbox with values of Subject node under Book.

<?xml version=”1.0″ encoding=”utf-8″ ?>
      Social Science

     General Science

var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book")
select nodes;
if (books != null)
foreach (var b in books)


LINQ to query DataTable

Posted: January 13, 2011 in LINQ

I am pretty new to LINQ & today my team mate was suggesting me to learn LINQ & write about it.Just starting with a small homework,how to query datatable using LINQ 🙂

What this snippet does is,there is a DataTable having columns Name,Age,Address etc,LINQ queries the table with name as input & returns Age & Address

string searchname="Anupama";
DataTable dtContacts = new DataTable();
dtContacts = this.GetContactDetails;

var query = from r in this.dtContacts.AsEnumerable()
where r.Field("Name") == searchname
select new{ Age=r["Age"],Address=r["Address"]};

Simple right?Keep Watching this space,I will get back with complicated one’s 🙂

I came across this error “Could not find a part of the path” while copying a file from one location to another.It threw exception at the second parameter of this below line

File.Copy(Path,FilePath + @"\" +FileName, true);

Value expected for this second parameter was like this C:\Templates\ANUTESTCODE11\test.xml where the test.xml gets added from the value of FileName.At one particulat section of calling code,the FileName was null & It was reading as C:\Templates\ANUTESTCODE11\ which resulted in the error message “Could not find a part of the path”

I found this during unit testing & this scenario has to be handled in the code.You should not give a chance for your code to fail & the appropriate way of using File.Copy is as below.This code snippet was suggested by one of the readers & adding it here.

{ if (!string.IsNullOrEmpty(FileName))
{ string newPath = System.IO.Path.Combine(FilePath, FileName);
if (File.Exists(Path) && Path.ToLower() != newPath.ToLower())
File.Copy(Path, newPath, true);

catch (Exception ex){ // handle the exception as desired}