Saturday, September 14, 2013

Export data from datareader to Excel in Vb.Net

Export data from datareader to Excel in Vb.Net

Step 1: Create a table andd insert data into that table.

Step 2: Use the below Function directly.

Public Sub exportData()
Dim strData As String = ""
Dim bolFirstPass As Boolean = True
Dim oCn As SqlConnection = Nothing
Dim oCmd As SqlCommand = Nothing
Dim oDr As SqlDataReader = Nothing
oCn = New SqlConnection("YOUR CONNECTION STRING ")
oCmd = New SqlCommand("select * from table", oCn)
'Dim da As SqlDataAdapter = New SqlDataAdapter(oCmd)
'Dim dt As DataTable = New DataTable()
oDr = oCmd.ExecuteReader(CommandBehavior.CloseConnection)
While oDr.Read
If bolFirstPass Then
bolFirstPass = False
'Write the Header Row
strData = "<body><meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>"
strData &= "<table border=1>"
strData &= "<tr>"
For i As Integer = 0 To oDr.FieldCount - 1
strData &= "<td>" & Replace(Replace(oDr.GetName(i), "[", ""), "]", "") & "</td>"
strData &= "</tr>"
bolFirstPass = False
Response.ContentType = "application/"
Response.AddHeader("content-disposition", "attachment; filename=filename.xls")
End If
strData = "<tr>"
For i As Integer = 0 To oDr.FieldCount - 1
strData &= "<td>" & i.Tostring() & "</td>"
strData &= "</tr>"
End While
Catch ex As Exception
If Not ex.Message.Contains("Thread was being aborted.") Then
_global.WriteErrorLog("exportData.loadPage() failed! Error is: " & ex.Message)
End If
If Not oCn Is Nothing Then If oCn.State = ConnectionState.Open Then oCn.Close()
End Try
End Sub

Step 3: Call this function on your button Click.

source :

Deploy a NopCommerce MVC Site

TO deploy you need to follow following steps.

 Step 1: Run the Prepare.bat file to build the project in release mode and move the plugins to the correct directory.

 Step 2: Run the Deploy.bat file to perform the same procedure as the Prepare.bat file, but also move all the websites and files to the \Deployable\Nop_{Version} directory.

 Step 3: Select all the files in \Deployable\Nop_{Version} directory and upload them to your web server.

 Step 4: Copy and paste setting.txt and InstalledPlugins.txt to App_Data folder from Presentation's App_Data Folder.

 Step 5: Now copy and paste Deployable\Nop_{Version} folder to WWWRoot foder and Just follow the steps that you used to Configure a normal Site.

 Step 6: Backup the database from your develope system.

 Step 7: Restore the database on server and make changes in setting.txt file as per Database server Setting(Server name,Userid,Password and Database name)

 Now run the site, your nopcommerce Site will be live.

source :

Polymorphism in C#

Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features: 
  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name.
Polymorphism is of two types: 
  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding
Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early binding.

In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.

Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.

Method overloading has nothing to do with inheritance or virtual methods.

Following are examples of methods having different overloads:

void area(int side);
void area(int l, int b);
void area(float radius);

Practical example of Method Overloading (Compile Time Polymorphism)

using System;

namespace method_overloading
    class Program
        public class Print
            public void display(string name)
                Console.WriteLine("Your name is : " + name);

            public void display(int age, float marks)
                Console.WriteLine("Your age is : " + age);
                Console.WriteLine("Your marks are :" + marks);
        static void Main(string[] args)

            Print obj = new Print();
            obj.display(34, 76.50f);

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.


When and why to use method overloading

Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.

Method Overloading showing many forms.

using System;

namespace method_overloading_polymorphism
    class Program
        public class Shape
            public void Area(float r)
                float a = (float)3.14 * r;
                // here we have used funtion overload with 1 parameter.
                Console.WriteLine("Area of a circle: {0}",a);

            public void Area(float l, float b)
                float x = (float)l* b;
                // here we have used funtion overload with 2 parameters.
                Console.WriteLine("Area of a rectangle: {0}",x);


            public void Area(float a, float b, float c)
                float s = (float)(a*b*c)/2;
                // here we have used funtion overload with 3 parameters.
                Console.WriteLine("Area of a circle: {0}", s);

        static void Main(string[] args)
            Shape ob = new Shape();

Things to keep in mind while method overloading

If you use overload for method, there are couple of restrictions that the compiler imposes.

The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.

There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.


You can read my other article on inheritance explaining method overriding.

Hope the article would have helped you in understanding polymorphism. Please feel free to contact me for feedback or comments you may have about this article.

Page Life Cycle

In this article, I will discuss in detail the ASP.NET page life cycle Events 

(1) PreInit 

The entry point of the page life cycle is the pre-initialization phase called "PreInit". This is the only event where programmatic access to master pages and themes is allowed.  You can dynamically set the values of master pages and themes in this event.  You can also dynamically create controls in this event.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_PreInit(object sender, EventArgs e)
        //  Use this event for the following:
        //  Check the IsPostBack property to determine whether this is the first time the page is being processed.
        //  Create or re-create dynamic controls.
        //  Set a master page dynamically.
        //  Set the Theme property dynamically.       


This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The "Init" event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Init(object sender, EventArgs e)
    // Raised after all controls have been initialized and any skin settings have been applied. 
    // Use this event to read or initialize control properties.


Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_InitComplete(object sender, EventArgs e)
       // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete. 


Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance

Loads ViewState : ViewState data are loaded to controls 

Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. 
Loads Postback data : postback data are now handed to the page controls 

Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreLoad(EventArgs e)
        // Use this event if you need to perform processing on your page or control before the  Load event.
        // Before the Page instance raises this event, it loads view state for itself and all controls, and 
        // then processes any postback data included with the Request instance.


The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Load(object sender, EventArgs e)
        // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child
        // control, which does the same for each of its child controls until the page and all controls are loaded.
        // Use the OnLoad event method to set properties in controls and establish database connections.

(6)Control (PostBack) event(s)

ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button's click event or a dropdown's selectedindexchange event, for example.

These are the events, the code for which is written in your code-behind class(.cs file).

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Button1_Click(object sender, EventArgs e)
        // This is just an example of control event.. Here it is button click event that caused the postback


This event signals the end of Load.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_LoadComplete(object sender, EventArgs e)
        // Use this event for tasks that require that all other controls on the page be loaded.


Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.

For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreRender(EventArgs e)
        // Each data bound control whose DataSourceID property is set calls its DataBind method.
        // The PreRender event occurs for each control on the page. Use the event to make final 
        // changes to the contents of the page or its controls.


Prior to this event the view state for the page and its controls is set.  Any changes to the page's controls at this point or beyond are ignored. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnSaveStateComplete(EventArgs e)
        // Before this event occurs,  ViewState has been saved for the page and for all controls. 
        // Any changes to the page or controls at this point will be ignored.
        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.


This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page's controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
// Render stage goes here. This is not an event


This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. 

Cleanup can be performed on-

(a)Instances of classes i.e. objects
(b)Closing opened files
(c)Closing database connections.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_UnLoad(object sender, EventArgs e)
        // This event occurs for each control and then for the page. In controls, use this event to do final cleanup 
        // for specific controls, such as closing control-specific database connections.
        // During the unload stage, the page and its controls have been rendered, so you cannot make further 
        // changes to the response stream.
        //If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Wednesday, September 11, 2013

insufficient memory to continue the execution of the program (mscorlib)

When Sql script is too large then it gives message "insufficient memory to continue the execution of the program (mscorlib)"

To overcome this we can use commands in the command prompt to run the scripts instead. Below Is an exmaple of such a script:
osql -S <SQL Server IP/Name> -d <DB Name> -E -i <sql script file path>
-S ServerName Such as localhost
-d database if you are creating database by script then no need to use this
-U userid you can define when database is defined in above script
-P password
-E trusted connection