Monday, April 4, 2016

Datatble Remove Rows C# while Looping

If you want to remove certain rows from a DataTable in C# and looping is easier to check the values to delete the FOR or FOREACH ROWS doesnt work because the count will be different once the Row is removed and it doesnt work.

So instead of using the following code which will fail

//Wrong Code dont use this .. this will Fail
            foreach (DataRow orow in dataTable.Rows)
                {
                    
                        if ((orow["ID"].ToString()).Equals("2"))
                        {
                            dataTable.Rows.Remove(orow);
                        }
                    
                }
Instead of using the above code use Select() as shown below

//Correct code use this
           foreach (DataRow orow in dataTable.Select())
                {

                    if ((orow["ID"].ToString()).Equals("2"))
                    {
                        dataTable.Rows.Remove(orow);
                    }

                }
Check this Fiddle
Leave a Comment. Bob



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 

Wednesday, June 8, 2011

Maintain scrollback position ASP.NET

Two ways to do this:

1 ) MaintainScrollPositionOnPostback="true" at the page directive so that it works for that page only
2) in the web.config that way it works for all the pages in the website.

Peace :)

Bobby

Wednesday, April 13, 2011

Specifying a same port for a Web site project that uses the Visual Studio Development Server

To specify a port for a Web site project that uses the Visual Studio Development Server

1.In Solution Explorer, select the project name.
2.In the Properties pane, set Use dynamic ports to False. This enables editing of the Port number property.
3.Enter a port number for the Port number property.
4.Click outside of the Properties pane. This saves the property settings
5.To verify the change, press CTRL+F5 to run the project. The new port number appears in the address bar of the browser.

For more info check this URL from MSDN

http://msdn.microsoft.com/en-us/library/ms178109.aspx

Thanks,
Suman

VSS ISSUE VISUAL STUDIO

When adding a project to a VSS some times the window doesnt show the network folders but asks for entering a DNS Address(in other words VSS over internet).

Solution is as follows:

Vs 2005 :
TOOLS -- Options -- Menu
choose Source Control and from the Current source control plugin in the right change the drop down value from Microsoft Visual SourceSafe(internet) to Microsoft Visual SourceSafe



You will be all set :)

Bobby

Thursday, March 31, 2011

Debug tools missing / only some shown in VISUAL STUDIO 2005

IF the Debug tools are missing (step into, out and over.. or RUN, STOP etc...) completely or only some shown partially (i.e only step out and nothing else) in VS 2005 do the following

1. Click on the tiny drop down button at the end of the debugging toolbar.
2. Select "Add or Remove buttons" option.
3. Select "Customize" option to bring up "customize" dialog box.
4. Go to Commands tab. This tab has Categories list to the left and Commands list to the right.
5. Select Debug category from Categories. This shows all commands (buttons) available in debug category - this includes Step Into, Step Out and many others.
6. Select any command buttons from the commands (Step Into or Step Out) - drag the button and drop it on any toolbar you like - in this case, you may drop it on debug toolbar.

Bobby

Thursday, January 27, 2011

Error configuring asp.net 1.1 websites IIS 7 windows 7 64 bit

Eventhough you set up the asp.net 1.1 websites correctly and they run... When you try to make some changes like Authentication etc from IIS 7 in a 64 Bit win7 OS you might see the follwing error

\\?\C:\Windows\system32\inetserv\config\applicationHost.config


Do the Following:
1. create a directory v1.1.4322 under (\windows\microsoft.net\framework64 by default 64 doesnt have the v1.1)
2. create a directory called CONFIG under (\windows\microsoft.net\framework64\v1.1.4322)
3. copy the machine.config file from \windows\microsoft.net\framework\v1.1.4322\config to \windows\microsoft.net\framework64\v1.1.4322\config folder.

4. Everything should work fine.

Found this solution from this http://forums.iis.net/t/1157568.aspx

In a 64 bit OS IIS 7 is wrongly looking for the machine.config under framework64 and as it doesnt exist there it fails.. so we can fool it by creating the necessary folders and copying the file :)

Wednesday, November 3, 2010

Could not find stored procedure 'sp_sdidebug'.

Could not find stored procedure 'sp_sdidebug'.
Might get this error message when debugging in VS 2003.

Need to uncheck the Microsoft T SQL when attaching the Debugger from the processes window to aspnet

Error usually appears when you are manually attaching the debugger

Bobby

Thursday, October 28, 2010

upload file to a database

Following is code to read a file from html Input and convert it into byte[]

byte[] imgBinaryData = null;

try
{
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
imgStream .Dispose ();
}
catch (Exception)
{


}


Following is the code to insert in DB

string cmdtext1 = "INSERT INTO [Info]([ID] ,[Picture],[afterpic])  values(1,@pic,@aftpic)";
SqlConnection scn = new SqlConnection(AppContext.ConnectionString);
SqlCommand scmd = new SqlCommand(cmdtext1, scn);
SqlParameter param1 = new SqlParameter("@pic", SqlDbType.Image);
SqlParameter param2 = new SqlParameter("@aftpic", SqlDbType.Image);
param1.Value = imgBinaryData;
param2.Value = imgBinaryData1;
scmd.Parameters.Add(param1);
scmd.Parameters.Add(param2);
scn.Open();
scmd.ExecuteNonQuery();
scn.Close();
imgBinaryData=null;;
imgBinaryData1=null;


Thanks,
Suman

Wednesday, October 27, 2010

xml xslt issue with html tags

If you print a dataset to a xml and if one of the values of a XML node has html tags they will be converted

for ex a "<" will be converted to a  "&lt;"  etc... when using style sheet to convert the XML use the following in XSL to
disable-output-escaping="yes"
   <xsl:value-of select="img1" disable-output-escaping="yes" />

Suman

Thursday, October 21, 2010

read excel sheet C#


Assuming txtFileName is a textbox which has the name of the excel. Make sure the sheet name is Sheet1. Please adjust the code according to your requirements.

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFileName .Text .ToString () + ";Extended Properties=Excel 8.0;";
OleDbConnection oleDBConn = new OleDbConnection(sConnectionString);
oleDBConn.Open();
OleDbCommand oleDBCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oleDBConn);
OleDbDataAdapter oledbadptr = new OleDbDataAdapter();
oledbadptr.SelectCommand = oleDBCmd;
DataSet ds1 = new DataSet();
oledbadptr.Fill(ds1);
oleDBConn.Close();

Friday, October 15, 2010

Useful Code


Save stream to a file in C#


public static void saveFile(Stream stream, string FileName)
      {
          

          if (stream.Length == 0) return;

          // Create a FileStream object to write a stream to a file
          using (FileStream fileStream = System.IO.File.Create(FileName, (int)stream.Length))
          {
              // Fill the bytes[] array with the stream data
              byte[] bytesInStream = new byte[stream.Length];
              stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

              // Use FileStream object to write to the specified file
              fileStream.Write(bytesInStream, 0, bytesInStream.Length);
          }
 
      }

Tuesday, September 21, 2010

isDbNULL with Datarow in .NET

You want to check for isdbnull while using datarow from a datatable/dataset this is how you use it..

C# CODE:

Assuming orow is the datarow you are working with ...

if (!Convert.IsDBNull(orow [5]))
{
// Do some thing
}
else

{
//Do some thing else...
}

Thanks,
Suman

Monday, May 24, 2010

Row Index on button click in a gridview

Find the Row index when you click a button in a gridview by using the following in the button click method in code behind

GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;
Response.Write(row.RowIndex);


Other way to use it is to have a command Name(for ex:View) and a Command Argument for the button and then using the GridView_RowCommand(object sender, GridViewCommandEventArgs e) _

There you can use some thing like

if (e.CommandName.ToString().Equals("View"))
{
int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
}

Thursday, May 20, 2010

VS 2005 takes too much time to load

VS 2005 takes too much time to load when you open it or trying to open a project.

Go to Tools -- > Import and Export Settings
and select Reset Settings.

That should do it.

You can do it as often as you want

Friday, April 9, 2010

Force the users to download rather than opening

For known content types like PDF, doc, mp3 etc..... when you have a download link it just opens it in the browser if the browser knows how to open..

If you want to force the user to download rather than being opened / played in web browser do the following with asp.net

Create a link using a link button and on button click do the following

string myFilename="../docs/abc.doc";

Response.AppendHeader( "content-disposition", "attachment; filename=" + myFilename );

The 2 lines above would force the browser to show the download box .

Hope this Helps.

Bobby

Wednesday, March 10, 2010

Keyboard quits working in visual studio 2005

For Some reason Unknown (Or known only to microsoft) some times the keyboard would quit working on VS 2005.

Re installation might help some times and some times it wont.

Looks like when you click on Design to switch to Design mode you will lose the Key board .

Here is a link for the Fix that i found which fixes it

http://petesbloggerama.blogspot.com/2006/07/internet-explorer-7-beta-3-and-loss-of.html

Thanks,
Bobby

Monday, February 22, 2010

Inject javascript in Head Section using asp.net

Even though it doesn't matter where the script is in the form or in the head section, you want to have it in the HEAD section of the HTML.
When you use Page.RegisterClientScriptBlock it injects the script in the body.
To inject in the HEAD section do the following...
HtmlGenericControl myScriptCode = new HtmlGenericControl("script");
myScriptCode.Attributes.Add("type", "text/javascript");
myScriptCode.InnerHtml = "alert('Alert generated by Script in Head Section of HTML');";
this.Page.Header.Controls.Add(myScriptCode); 
that should do it.check it by clicking view source and you should see the Script in HEAD section If you want to refer to a js file as a external file use the SRC attribute
string jssrc="../abc.js";
HtmlGenericControl myScriptCode = new HtmlGenericControl("script");
myScriptCode.Attributes.Add("type", "text/javascript");
myScriptCode.Attributes.Add("src",jssrc);
this.Page.Header.Controls.Add(myScriptCode);