Wednesday, October 28, 2015

( 0.1 + 0.2 ) - 0.3 = 5.55111512312578E-17


Puzzling looking at the title!!!!

Lets look at this code
var a =(0.1 + 0.2) - 0.3;
Console.WriteLine("a = "+ a);

I am sure you are expecting "0" but its not.

It is 5.55111512312578E-17

check my fiddle here Open my Fiddle




Friday, September 4, 2015

Generating XOR checksum in C#

Here is the code to generate the checksum


using System;
using System.Globalization;

public class Program
{
public static void Main()

//suman first convert to byte[]
byte[] bb = ConvertHexadecimalStringToByteArray("030100AA1902");
//calculate checksum with the above byte[]
Console.WriteLine(calculateCheckSum(bb));
}

//Following converts the hex to a byte[]
public static byte[] ConvertHexadecimalStringToByteArray(string hexadecimalString)
{
if (hexadecimalString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "HexaDecimal cannot have an odd number of digits: {0}", hexadecimalString));
}

byte[] hexByteArray = new byte[hexadecimalString.Length / 2];
for (int index = 0; index < hexByteArray.Length; index++)
{
string byteValue = hexadecimalString.Substring(index * 2, 2);
hexByteArray[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}

return hexByteArray;
}

    //calculates the checksum from the byte[]
private static byte calculateCheckSum(byte[] byteData)
{
Byte chkSumByte = 0x00;
for (int i = 0; i < byteData.Length; i++)
chkSumByte ^= byteData[i];
return chkSumByte;
}
}


check the fiddle: Fiddle Link



Tuesday, April 7, 2015

DataTable does not support schema inference from Xml error ?


If you are reading xml to Datatable using the method like below, it will throw a error.
string xmlString ="somexml string"; /// this will actually contain the xml...
DataTable dt = new DataTable();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
dt.ReadXml(oreader);

this might throw a error like DataTable does not support schema inference from Xml error.

This happens because the Datatable doesnt understand the Schema to properly convert to a DataTable.

Two way to solve this.
1) Easier way is to use the Dataset and then get the table from there like below

string xmlString ="somexml string"; /// this will actually contain the xml...
DataSet ds = new DataSet();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
ds.ReadXml(oreader);
DataTable dtt=ds.tables[0];

2) If the XmlString has the Schema use the following

string xmlString ="somexml string"; /// this will actually contain the xml...
DataTable dt = new DataTable();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
dt.ReadXmlSchema("xmlSchema.xsd"); -- If schema is in a xsd
dt.ReadXmlSchema(oreader); // if the XML string has the XML Schema.
dt.ReadXml(oreader);


Note: If you are generating the XML as well from a datatable you can generate the schema by
dt.WriteXml("a.xml",XmlWriteMode.WriteSchema);
  If you are not generating the XML, you can still generate schema from different XML editors. Like for EX if you have visual Studio you can use the create Schema to create the XML and then load it or the easier way of using the Dataset :)

Cheers,
Bob






             

Wednesday, January 28, 2015

Handle Null values in Datatable.WriteXML method

When there is a null value for a column in a datatable and when you try to convert to xml using the writeXML of the datatable, the XML will not have that element.

For ex: if your datatable is like this

FirstName LastName EmailAddress
bob j Bob.email@email1.com
santa Banta

As shown above the second entry doesnt have the email Address.. the generated XML will be
 <root>
            <table>
                <firstname>bob</firstname>
                <lastname>j</lastname>
                 <emailaddress>Bob.email@email1.com</emailaddress>
            </table>
            <table>
                 <firstname>santa</firstname>
                 <lastname>Banta</lastname>
            </table>
   </root>


as you can see the EmailAddress is missing from the second...

one way to accomplish this is writing string.empty to the null columns... wrote a small mehtod that can do this...

 public DataTable writeEmptyStringToNullElelments(DataTable dt){

      foreach (DataRow oRow in dt.Rows)
      {
        for (int colCount = 0; colCount < oRow.ItemArray.Length; colCount++)
        {
          if (oRow.ItemArray[colCount] == DBNull.Value)
          {
               oRow.SetField(colCount, string.Empty);
          }
              
        }
      }

      dt.AcceptChanges();

      return dt;
    }

call the above method before generating the XML
Now the generated XML will be


<root>
            <table>
                <firstname>bob</firstname>
                <lastname>j</lastname>
                 <emailaddress>Bob.email@email1.com</emailaddress>
            </table>
            <table>
                 <firstname>santa</firstname>
                 <lastname>Banta</lastname>
                  <emailaddress />
            </table>
        </root>





Bobby :)

Sunday, January 25, 2015

DataTable to XML C#

Datatable to XML

If you have a datatable and want to convert to XML the C# code is as follows

StringWriter writer = new StringWriter();
 dt.WriteXml(writer);

writer will have the xml.

for ex: if your datatable is in the following structue.

ID, FirstName,LastName then the above code will produce the XML in the following format.

<Table>
      <ID>1</ID>
      <FirstName>Bob</FirstName>
     </LastName>Burger</LastName>
</Table>


If you want the string Table to be replaced with something else give a name to the datatable

dataTable.TableName="StudentInfo"; then the xml will be as follows.

<StudentInfo>
      <ID>1</ID>
      <FirstName>Bob</FirstName>
     </LastName>Burger</LastName>
</StudentInfo>

if you want the XML schema along with the xml then use the following.

dt.WriteXml(writer, XmlWriteMode.WriteSchema, true);
.. what this does is adds the schema at the top.


Thanks,
Bob


Monday, January 12, 2015

cant access newly added class files in APP_code Folder VS 2013 from other files (aspx, etc....)



sometimes you cant access some newly added class files from APP_code folder in VS 2010,VS 2011 from aspx or other files.

select the File that cant be accessed in solution explorer. Click on properties.

Change the Build Action from Content to Compile

That should fix it.

Bobby :)

Sunday, January 11, 2015

Split string to Dictionary C#

Here is a neat little code that would split a string and puts the values in a dictionary..

For ex if the string is to=suman&From=bobby&subject=Hello How are you&Body=TEST

the following code would split the strings into a dictionary so that you can access by myStr["to"] instead of myStr[0],[1] etc..

Sometimes it will be handy to access by name instead of array ...

you might have to change the below code so that if your outer seperator isnt '&'  change it to your character.. you can also change the inner seperator from '=' to anything you want.

public static Dictionary  splitStringToaDictionary(string stringToConvertToDict)
    {
                 
            string[] splitSTR= stringToConvertToDict.Split('&');
               var  mydictionary = new Dictionary(splitSTR.Length);
                foreach (string item in splitSTR)    
                {        
                    List list = new List(item.Split('=')); 
                    mydictionary.Add(list[0], list[1]);
                                    
                }
       
        return mydictionary;
    }

//same method as above overloaded

public static Dictionary  splitStringToaDictionary(string stringToConvertToDict,char outerSeperator, char innerSeperator)
    {
                 
            string[] splitSTR= stringToConvertToDict.Split(outerSeperator);
               var  mydictionary = new Dictionary(splitSTR.Length);
                foreach (string item in splitSTR)    
                {        
                    List list = new List(item.Split(innerSeperator)); 
                   mydictionary.Add(list[0], list[1]);
                                    
                }
       
        return mydictionary;
    }

In case if your seperator isnt just one character but multiple characters like a string for ex #abc# ... i.e A#abc#Borwn#abc#Fox

then you need to use
item.Split(new string[] {"#abc#"},StringSplitOptions.None)

Bobby