Tuesday, June 29, 2010

Binary to String Conversion in C#

Converting binary to different format is quiet common scenario for developers.Its just two line of code that will do the magic , but when time matter love search in google so if this blog help someone really happy for that.
Binary to String

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(MyByteArray);
if you want to make sure that there is no data loss then use Base64 Encoding

Base64 Encoding :- converts binary data to plain text using 64 case-sensitive, printable ASCII characters: A-Z, a-z, 0-9, plus sign (+) and forward slash (/), and may be terminated with 0-2 "padding" characters represented by the equal sign (=).

Convert.ToBase64String(myByteArray);
when you are working with picture it will be good to use Base64 conversion so you could make sure that there is no data lose

XDocument or XElement with XmlNamespace

Loading or parsing xml with namspaces are common in development scenarios.When we work with Xdocument and XElement there is no direct way to pass the namespace. Let see how we can work with namspace.

Step1 Create a NameTable

NameTable nameTable = new NameTable();

Step2 Create Namespace Manager
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(nameTable );
Step3 Add the Namespace or Ignore It
Adding
nameSpaceManager.AddNamespace("p", "office.server.policy");
Ignoring
nameSpaceManager.AddNamespace("log4net", "urn:ignore");

Step4 Create a ParserContext
XmlParserContext parserContext = new XmlParserContext(null, nameSpaceManager,
null, XmlSpace.None);
Step5 Create a XmlTextReader
XmlTextReader txtReader = new XmlTextReader("Strin XML", XmlNodeType.Element,
parserContext);

Step6 Load the XML
XElement elem = XElement.Load(txtReader);

For Example we have a Log4net xml and we need to parse it

<log4net:event logger="TestingTransmitter.Program"
timestamp="2009-08-02T17:50:18.928+01:00"
level="ERROR"
thread="9"
domain="TestingTransmitter.vshost.exe"
username="domain\user">
<log4net:message>Log entry 103</log4net:message>
<log4net:properties>
<log4net:data name="log4net:HostName" value="machine" />
</log4net:properties>
</log4net:event>


Following code will load the xml without error like "an undeclared namespace"

NameTable nameTable = new NameTable();
XmlNamespaceManager nameSpaceManager
= new XmlNamespaceManager(nameTable );
nameSpaceManager.AddNamespace("log4net", "urn:ignore");
XmlParserContext
parserContext = new XmlParserContext(null, nameSpaceManager,
null,
XmlSpace.None);
XmlTextReader txtReader = new XmlTextReader("Strin XML",
XmlNodeType.Element,
parserContext );
XElement elem =
XElement.Load(txtReader);

Thursday, June 24, 2010

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

Linq query are one of the favourite among the developers, sometimes people get following error in the Linq Query and became clueless.Error will look like following

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

For Example we have a query like following
cars = from car in Vehicle.Cars
where car.Make.Contains("BMW")
select car;
we then enumerate through the cars like
foreach (var myCar in cars)
{
//
}
the code starts blowing up in the enumeration with a error Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
At first instance we may wonder why this is not working looks like the code has no issue. If we look at the query closely we can see the where condition "car.Make.Contains("BMW") " can blow up if the Make is null. So we found the issue next we need to change the query like following
cars = from car in Vehicle.Cars
where ((car.Make != null) && (car.Make.Contains("BMW")))
select car;

Now we are good to go.Stop Googling !!!
Cheers
Shyju Mohan

Monday, June 21, 2010

Loading xml from string

XML Document Approach

Let see how we can load xml from a string to a xmldocument
object
Step 1 Create XmlDocument Object
XmlDocument doc = new
XmlDocument();
Step 2
Creat a StringReader Object
System.IO.StringReader sr = new
System.IO.StringReader("XML
Sring");
Step 3 Create
XmlReader Object
XmlReader xmlrd =
XmlReader.Create(sr)

Here we are calling XmlReader.Create method and passing a
StringReader object
Step 4 Load xml
doc.Load(xmlrd);
Uses Load method of
XmlDocument object and pass XmlReader

XDocument Approach
XDocument.Parse("StringXML", LoadOptions.PreserveWhitespace);
In Xdocument you can directly pass the string and specify the load
options.Even you can directly parse into a XElement
XElement.Parse("StringXML")
You could also specify the declaration for your xml when you are creating the XDocument.Look at the following line
XDocument xdoc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", "YES"), XElement.Parse("StringXML"));

Here XDeclaration you can specify version of xml,encoding you are using and standalone or not