Posts Tagged ‘.Net’

Today a friend of mine started getting this error while he tried to deploy his solution to a server. This only started when ‘Precompiling during publishing’ option is selected.


“Error 20 It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.”

After having a look, I identified this was caused by a temporary copy of a Web.Config file. Earlier developer created a copy of the Web.Config and placed it inside a folder named Backup within the solution. This backup config file had authentication tag (<authentication>), which is a tag that can be only used in global Web.Config file or the Web.Config file in applications root. Due to the presence of authentication tag, compiler started complaining that there is a virtual directory not configured as a application in IIS.

The solution for my friend’s issue was to simply exclude the copy of the Web.Config file from project by right clicking the file. Then the project started deploying happily.


As you may be knowing, now you do not need to separately download and install .Net framework as we used to do with the older .Net frameworks. Since it is coming with Windows, you can just go to “Turn Windows Features On or Off” screen and enable framework you are after. It is simple right?

But in one of the machines it was not that simple for me. The installation tried to download files from Windows Update and was failing mentioning that it cannot get connected to Windows Update when the machine is connected to the internet without any issues.

The solution is to use DISM (Deployment Image Servicing and Management) tool to get it installed.

First you need to find a Windows setup media, a setup DVD or an ISO downloaded will work.

Then use the below command to enable the feature using a local source. Remember to open the Command Window as an Administrator of the machine.

DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:E:\Sources\sxs

/Online – Targets the currently active and running OS.

/LimitAccess – If some installation files are missing, this will check Windows Update for the missing files. For not to check use /LimitAccess:True.

/Source – Is the location to find the source files, E: is my virtual drive which I mounted the previously downloaded Windows ISO.

If typed correctly, there will be a progress bar showing the installation progress.


While trying to setup and use the Code Plugin by Rich Hewlett I had trouble getting the plugin loaded into Live Writer. I did add the registry entry required as mentioned in the site, but still the plugin did not load.


Location – HKEY_CURRENT_USER\SOFTWARE\OpenLiveWriter\PluginAssemblies

Key – SyntaxHighlight_WordPressCom_OLWPlugIn

Value – C:\Users\Arjuna\AppData\Local\OpenLiveWriter\Plugins\SyntaxHighlight_WordPressCom_OLWPlugIn.dll

After a while I figured out that, when loading the plugin Live Writer encounters the following error.

"System.IO.FileLoadException: Could not load file or assembly ‘file:///C:\Users\Arjuna\AppData\Local\OpenLiveWriter\Plugins\SyntaxHighlight_WordPressCom_OLWPlugIn.dll’ or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: ‘file:///C:\Users\Arjuna\AppData\Local\OpenLiveWriter\Plugins\SyntaxHighlight_WordPressCom_OLWPlugIn.dll’ —> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See for more information.

This is due to a security feature of .Net Framework 4 or later. Before framework 4, if a DLL is downloaded (which is created in another computer), they used to run in full trust in the zone the assembly is running, but with frameworks 4 and later, downloaded DLLs will not run by default. To make them run, simply grant the DLL full access by going to file properties and selecting the Unblock checkbox in the security section as seen in the below image. This will apply to any plugin you download from internet. Also keep in mind to do this to DLLs you trust safe. Otherwise your computer will be unsafe.


To troubleshoot plugin and other errors you can refer to Open Live Writer log file located in C:\Users\Arjuna\AppData\Local\OpenLiveWriter\Open Live Writer.log.

As you may be knowing, you can use Windows PowerShell to change registry values. In this article I am going to do five things.

I have created few registry entries to use in this example as seen below. In real world you can use whatever entries in your registry. It is always advisable to backup your registry before changing it.


1. Set a registry key value.

To set a value you need to use the “Set-ItemProperty” cmdlet as below.

Set-ItemProperty -Path "HKLM:\Software\Test\Live" -Name "TestValue2" –Value “TestData2”

Above command will put “TestData2” in the registry key “TestValue2” located in HKEY_LOCAL_MACHINE\Software\Test\Live.

2. Read a registry key value.

Reading from the registry can be done by using the cmdlet “Get-ItemProperty”.

Below command will get the value in the “TestValue1” key.

Get-ItemProperty -Path "HKLM:\Software\Test\Live" -Name "TestValue1"

3. Using variables in PowerShell.

Here I am going to read a registry key value and put it to another registry key. This can be done using a variable. First you need to read the value into a variable using the “Get-ItemProperty” cmdlet and that value can be saved using the “Set-ItemProperty” cmdlet.

  1. # Check for the existance of the registry key.
  2. IF (Get-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “TestValue1” -ea 0)
  3. {
  4.     # Fetching the value from TestValue1.
  5.     $OldValue = Get-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “TestValue1”
  6. }
  7. ELSE
  8. {
  9. # Inserting a blank, if the registry key is not present.
  10.     $OldValue = “”
  11. }
  12. # Printing the value in the variable.
  13. Write-Host $OldValue.TestValue1
  14. # Setting the value to TestValue2.
  15. Set-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “TestValue2” -Value $OldValue.TestValue1

4. Working with registry keys with spaces.

In case your registry keys contain spaces, you need to use double quotes in your script as seen below.

  1. # Check for the existance of the registry key.
  2. IF (Get-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “Test Value 1” -ea 0)
  3. {
  4.     # Fetching the value from Test Value 1.
  5.     $OldValue = Get-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “Test Value 1”
  6. }
  7. ELSE
  8. {
  9.     # Inserting a blank, if the registry key is not present.
  10.     $OldValue = “”
  11. }
  12. # Printing the value in the variable.
  13. Write-Host $OldValue.“Test Value 1”
  14. # Setting the value to Test Value 2.
  15. Set-ItemProperty -Path “HKLM:\Software\Test\Live” -Name “Test Value 2” -Value $OldValue.“Test Value 1”


5. Saving PowerShell commands as scripts and running them.

Both above can be saved as a PowerShell script by saving it in a file with the extension ps1. For example I did save it as “ChangeReg.ps1” in my C drive inside the folder “new”. Then the script can be run by browsing to the folder and using the command “.\ChangeReg.ps1”.


After the script is run my registry keys looked like this.


In case you need to retrieve values from other registry hives (locations), following table may be helpful.


Registry Hive




In case you need to read more on “Get-ItemProperty” and “Set-ItemProperty”, use the links to visit official documentation from Microsoft TechNet.

Request Filtering

I recently got this error in one of my applications. When troubleshooting, I found my application is configured to have the default value of 30000000 Bytes for the content length, which was not sufficient for me in some of the file uploading functionalities.

Simply adding / increasing the number in the configuration file corrected this error.

Request Content Length in Bytes.

Default Value – 30000000 Bytes (~28MB)

Maximum Value – 4284229877 Bytes (3.99GB)

  1. <system.webServer>
  2.   <security>
  3.     <requestFiltering>
  4.       <requestLimits maxAllowedContentLength=100000000></requestLimits>
  5.     </requestFiltering>
  6.   </security>
  7.   …
  8. </system.webServer>


To obtain more information read this article.


Sometime back I started getting this error in all the forms in which AJAX tools were used. The thing worried me most is that there were no changes made to the project source code. Later a friend of mine found that it is happening because of the wrong AjaxControlToolkit.

As I feel this dll swap happens when a control is dragged from the Visual Studio toolbox because the toolbox is referenced to a newer version of the toolkit than the project was using.

If you are also getting this error simply delete all the AJAX related files and folders in your projects’ bin directory. Once you are done there should not be any folders such as ar, cs, de, etc. Also remove the AjaxControlToolkit.dll. Then copy the version of the toolkit dll your project was using earlier to the Bin directory. Now clean and build your project to see the error disappear.

If you are still getting the error after correctly doing all this you might be getting the error due to another reason causing the same error. Since there are many reasons for this same error you better check the internet for other reasons to find out the exact reason causing the error for you.

Menu Overlapping with Report

Posted: April 3, 2011 in .Net, CSS, Web
Tags: , ,

If you had lengthier menus in you ASP.Net application and had used report viewer control you may have faced the problem of report and menu overlapping when ever the report is loaded with data. For example in my sample application it appeared as below.


To correct this behavior you need to set the z-index for menu and report viewer using CSS class property. For this I have used the following CSS classes in the Style.CSS.

  1. /* CSS Class for the Menu. */
  3. {
  4.     padding: 4px 0px 4px 8px;
  5. }
  7. /* CSS Class for a Menu Item. */
  8. ul
  9. {
  10.     list-style: none;
  11.     margin: 0px;
  12.     padding: 0px;
  13.     width: auto;
  14.     z-index: 1; /* Setting the control to appear on top of level 0 controls for e.g. report viewer. */
  15. }
  17. /* CSS Class for the Report Viewer. */
  18. .report
  19. {
  20.     z-index: 0; /* Setting the control to appear below the level 1 controls for e.g. menu items. */
  21. }

To apply the CSS use a code similar to following.

Appling CSS Class to menu in master page.

  1. <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"
  2. EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
  3.     <Items>
  4.         <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
  5.         <asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
  6.         <asp:MenuItem Text="New Item" Value="New Item">
  7.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  8.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  9.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  10.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  11.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  12.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  13.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  14.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  15.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  16.         </asp:MenuItem>
  17.         <asp:MenuItem Text="New Item" Value="New Item">
  18.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  19.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  20.             <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  21.         </asp:MenuItem>
  22.         <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  23.         <asp:MenuItem Text="New Item" Value="New Item"></asp:MenuItem>
  24.     </Items>
  25. </asp:Menu>

Appling CSS Class to report viewer.

  1. <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" CssClass="report"
  2.     Font-Size="8pt" InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana"
  3.     WaitMessageFont-Size="14pt" Width="636px">
  4.     <LocalReport ReportPath="Report1.rdlc">
  5.         <DataSources>
  6.             <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DataSet1" />
  7.         </DataSources>
  8.     </LocalReport>
  9. </rsweb:ReportViewer>

This will correct the overlapping issue as seen below.


Rounding a value Down

Posted: August 2, 2010 in .Net

If you did work with .Net Math classes you may have noted that you can quite easily round value upwards. But what about rounding values down?

For example if you tried to round the value 1.23501 into 2 decimal places using the Round method provided by the Math class as below, the result you will get is 1.24. Meaning .Net had rounded the value up.

  1. double dbl = Math.Round(1.23501, 2);

If the value is rounded down it should be 1.23, but in .Net I couldn’t find an easy way to get this done. So I did create a small code to get it done. It is very simple only a method with one statement as shown below.

  1. double RoundDown(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         return Math.Truncate(Number) +
  6.             (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length – 3)))) *
  7.             (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length – 3));
  8.     }
  9.     catch (Exception)
  10.     {
  11.         MessageBox.Show("Error ! Please check values.");
  12.         return 0.0;
  13.     }
  14. }

Ohh, I think this is complicated right? Please find a bit of self explanatory code below.

  1. double RoundDownExplained(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         // Get the whole number from the double value.
  6.         // For example we’ll take Number = 788.34567 and Digits = 3.
  7.         // WholeNumberPart = 788.
  8.         double WholeNumberPart = Math.Truncate(Number);
  9.         // Getting the decimal part from the doouble value.
  10.         // DecimalNumberPart = 0.3457.
  11.         double DecimalNumberPart = Math.Round((Number % 1), Digits);
  12.         // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  13.         // MultiplicationValue = 3.
  14.         int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length – 3;
  15.         // Create the double value to round down.
  16.         // RoundedDownValue = 345.
  17.         double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  18.         // Finding the value to devide the result to make it decimal again.      
  19.         // DivisionValue = 0.001.            
  20.         double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  21.         // Creating the decimal part with rounded down value.
  22.         // RoundedDownValue_Float = 0.345.
  23.         double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  24.         // Creating the full rounded down value.
  25.         // return = 788.345.
  26.         return WholeNumberPart + RoundedDownValue_Float;
  27.     }
  28.     catch (Exception)
  29.     {
  30.         MessageBox.Show("Error ! Please check values.");
  31.         return 0.0;
  32.     }
  33. }

The complete code of the application I created is below with a screenshot of the application running. Hope this helps to you.

  1. using System;
  2. using System.Text;
  3. using System.Windows.Forms;
  4. namespace WindowsFormsApplication1
  5. {
  6.     public partial class Form1 : Form
  7.     {
  8.         public Form1()
  9.         {
  10.             InitializeComponent();
  11.         }
  12.         double RoundDown(double Number, int Digits)
  13.         {
  14.             try
  15.             {
  16.                 return Math.Truncate(Number) +
  17.                     (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length – 3)))) *
  18.                     (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length – 3));
  19.             }
  20.             catch (Exception)
  21.             {
  22.                 MessageBox.Show("Error ! Please check values.");
  23.                 return 0.0;
  24.             }
  25.         }
  26.         double RoundDownExplained(double Number, int Digits)
  27.         {
  28.             try
  29.             {
  30.                 // Get the whole number from the double value.
  31.                 // For example we’ll take Number = 788.34567 and Digits = 3.
  32.                 // WholeNumberPart = 788.
  33.                 double WholeNumberPart = Math.Truncate(Number);
  34.                 // Getting the decimal part from the doouble value.
  35.                 // DecimalNumberPart = 0.3457.
  36.                 double DecimalNumberPart = Math.Round((Number % 1), Digits);
  37.                 // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  38.                 // MultiplicationValue = 3.
  39.                 int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length – 3;
  40.                 // Create the double value to round down.
  41.                 // RoundedDownValue = 345.
  42.                 double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  43.                 // Finding the value to devide the result to make it decimal again.      
  44.                 // DivisionValue = 0.001.            
  45.                 double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  46.                 // Creating the decimal part with rounded down value.
  47.                 // RoundedDownValue_Float = 0.345.
  48.                 double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  49.                 // Creating the full rounded down value.
  50.                 // return = 788.345.
  51.                 return WholeNumberPart + RoundedDownValue_Float;
  52.             }
  53.             catch (Exception)
  54.             {
  55.                 MessageBox.Show("Error ! Please check values.");
  56.                 return 0.0;
  57.             }
  58.         }
  59.         private void button1_Click(object sender, EventArgs e)
  60.         {
  61.             try
  62.             {
  63.                 label1.Text = RoundDown(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  64.             }
  65.             catch (Exception)
  66.             {
  67.                 MessageBox.Show("Error ! Please check values.");
  68.             }
  69.         }
  70.         private void button2_Click(object sender, EventArgs e)
  71.         {
  72.             try
  73.             {
  74.                 label2.Text = RoundDownExplained(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  75.             }
  76.             catch (Exception)
  77.             {
  78.                 MessageBox.Show("Error ! Please check values.");
  79.             }
  80.         }
  81.     }
  82. }

Class not registered

Posted: June 27, 2010 in .Net
Tags: , ,

Recently when I tried to build and run an existing .Net application code I got the following error which generated from a component named “axShockwaveFlash1” which is an object used to embed flash content on to the application.

System.Runtime.InteropServices.COMException was unhandled
  Message=Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
       at System.Windows.Forms.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid)
       at System.Windows.Forms.AxHost.CreateWithoutLicense(Guid clsid)
       at System.Windows.Forms.AxHost.CreateWithLicense(String license, Guid clsid)
       at System.Windows.Forms.AxHost.CreateInstanceCore(Guid clsid)
       at System.Windows.Forms.AxHost.CreateInstance()
       at System.Windows.Forms.AxHost.GetOcxCreate()
       at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state)
       at System.Windows.Forms.AxHost.CreateHandle()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.AxHost.EndInit()
       at Tour_Management_System.Loading_Form.InitializeComponent() in D:\Projects\Acc\TMS_20100205_Desktop\Tour_Management_System 2010-01-19\Tour_Management_System\Form1.Designer.cs:line 99
       at Tour_Management_System.Loading_Form..ctor() in D:\Projects\Acc\TMS_20100205_Desktop\Tour_Management_System 2010-01-19\Tour_Management_System\Form1.cs:line 30
       at Tour_Management_System.Program.Main() in D:\Projects\Acc\TMS_20100205_Desktop\Tour_Management_System 2010-01-19\Tour_Management_System\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

After some investigation I found that the reason for this was Flash Player’s incompatibility with 64 bit. Since my machine is running Windows 64 bit version it generates an error while trying to start Flash player. Good thing is Adobe is planning to release a Flash player which supports 64 bit soon.

For people who cannot wait until that (like me) can fix the problem in the following manner by running the application as an x86 application by changing the target platform in project properties.

Step 1 – Right click on your project and click on the properties.

Step 2 – Click on the Build tab and select x86 as the Platform target:.

Step 3 – Rebuild the application and run it, you will not get the error.

Even though I posted similar 2 articles in 2008, the code of that article was having few errors. So thought to put more complete post on this.

The code will read an Excel file using an OleDbConnection and will write the same data back to another Excel file. This will explain how to read and write to Excel files. One thing to remember when running this code is to make sure the source Excel file is open. Otherwise you will get an error similar to “External table is not in the expected format.”

Also note that there are few connection string parameters you can use while opening Excel files.

HDR = Yes – Use when first row contains column headers.

HDR = No  – Use when first row contains data.

Excel xx.x – Use the following Table as a guide.

Parameter Value

Excel Version

Excel 12.0 Excel 2007 (Released in 2007)
Excel 11.0 Excel 2003 (Released in 2003)
Excel 10.0 Excel XP (Released in 2001)
Excel 9.0 Excel 2000 (Released in 1999)
Excel 8.0 Excel 97 (Released in 1997)

IMEX=1 – Use this when you want to treat all your data in the file as text.

For example – >

Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

To make the code to work properly you need to refer the Microsoft.Office.Interop.Excel assembly by adding a reference to your project.

  1. using System;
  2. using System.Data;
  3. using System.Windows.Forms;
  4. using System.Data.OleDb;
  5. using Microsoft.Office.Interop.Excel;
  6. namespace TestApp
  7. {
  8.     public partial class Form1 : Form
  9.     {
  10.         public Form1()
  11.         {
  12.             InitializeComponent();
  13.         }
  14.         private void button1_Click(object sender, EventArgs e)
  15.         {
  16.             openFileDialog1.ShowDialog();
  17.             // Create an OLEDBConnection to connect to the Excel file.
  18.             // I’m getting the required file by using a file dialog.
  19.             // The @ symbol makes the string to contain any special characters inside the string without breaking the string.
  20.             OleDbConnection dbConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog1.FileName.ToString() + @";Extended Properties=""Excel 8.0;HDR=Yes;""");
  21.             // Open the connection.
  22.             dbConnection.Open();
  23.             // Create a command object to work on the data.
  24.             // Note that I have given the sheet name as [Sheet1$] to retrieve data from that named sheet in the particular Excel file.
  25.             OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection);
  26.             // Creating a data reader to read data.
  27.             OleDbDataReader dbReader = dbCommand.ExecuteReader();
  28.             // If needed you can get the position of any column (e.g. Age), this will only work if you use HDR=Yes.
  29.             int SearchingItem = dbReader.GetOrdinal("Age");
  30.             // Create the Excel Application object.
  31.             ApplicationClass ExcelApp = new ApplicationClass();
  32.             // Set the visibility of the application.
  33.             ExcelApp.Visible = true;
  34.             // Create a new Excel Workbook.
  35.             Workbook ExcelWorkbook = ExcelApp.Workbooks.Add(Type.Missing);
  36.             // Create a new Excel Sheet.
  37.             Worksheet ExcelSheet = (Worksheet)ExcelWorkbook.Sheets.Add(ExcelWorkbook.Sheets.get_Item(1), Type.Missing, 1, XlSheetType.xlWorksheet);
  38.             // Will keep the current row index. This should start from 1 since the first row is 1.
  39.             int CurrentRowIndex = 1;
  40.             try
  41.             {
  42.                 // Read through the data.
  43.                 while (dbReader.Read())
  44.                 {
  45.                     // Traverse through all the data columns.
  46.                     for (int i = 0; i < dbReader.VisibleFieldCount; i++)
  47.                     {
  48.                         ExcelSheet.Cells[CurrentRowIndex, i + 1] = dbReader.GetValue(i);
  49.                     }
  50.                     CurrentRowIndex++;
  51.                 }
  52.                 // Save the Excel sheet.
  53.                 // The @ symbol makes the string to contain any special characters inside the string without breaking the string.
  54.                 ExcelApp.Save(@"C:\Projects\Ex.xls");
  55.             }
  56.             catch (Exception ex)
  57.             {
  58.                 MessageBox.Show(ex.ToString());
  59.             }
  60.         }
  61.     }
  62. }