Archive for July, 2011

How to Import CSV File Into SQL Server Using Bulk Insert in SQLServer?

July 26, 2011 12 comments

Restore data from csv files into SQL Server

This is very common scenario that we have to import data into sql server database from csv files. In SQL Server there is an option to insert data from a csv file into database. We are going to demonstrate how we can import data from csv files into a sql server database. The constraints are we need to have data in csv files as same structure in the table structure


Imports a data file into a database table or view in a user-specified format in SQL Server 2008 R2. Use this statement to efficiently transfer data between SQL Server and heterogeneous data sources.

Arguments :


Is the database name in which the specified table or view resides. If not specified, this is the current database.


Is the name of the table or view schema. schema_name is optional if the default schema for the user performing the bulk-import operation is schema of the specified table or view.


Is the name of the table or view to bulk import data into. Only views in which all columns refer to the same base table can be used. For more information about the restrictions for loading data into views,


Is the full path of the data file that contains data to import into the specified table or view. BULK INSERT can import data from a disk (including network, floppy disk, hard disk, and so on).

BATCHSIZE =batch_size

Specifies the number of rows in a batch. Each batch is copied to the server as one transaction


Specifies that all constraints on the target table or view must be checked during the bulk-import operation.

Steps to Import CSV to SQL Server / Sample CSV import to SQL Server using BULK Insert

Here we are going to show how to import csv files data into a SQL Server table using bulk Insert method. First of all create a csv file with data as follows :- id, name, age, joindate (Should be same as structure of table).  We have a table with same structure of columns : id, name, age , joindate.

Step 1 : Create a table


CREATE TABLE [dbo].[Employee](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [name] [varchar](50) NULL,
      [age] [int] NULL,
      [joindate] [datetime] NULL,
      [id] ASC

Step 2 : Create a csv files and enter the data as same as structure table


Step3 : Run following script to insert data from csv to table

INSERT Employee
FROM 'c:\emp.txt'

Collapsible panel extender samples in ASP.Net indifferent scenario

July 25, 2011 3 comments

How to implement collapsible panel extender in ASP.Net/C#?

Ajax collapsible panel extender is a tool used to collapse and expand each section with content or without content with asynchronous javascript, hence there is no postback happening in the middle of collapse/expand process. Dot Net framework helps to create collapse and expand functionalities within easy steps. Ajax tool kit included a control name Ajax Collapsible Panel Extender allows to implement above mentioned process as very easily.  The CollapsiblePanel is a very flexible extender that allows you to easily add collapsible sections to your web page. This extender targets any ASP.NET Panel control. The page developer specifies which control(s) on the page should be the open/close controller for the panel, or the panel can be set to automatically expand and/or collapse when the mouse cursor moves in or out of it, respectively.

Steps to implement Ajax collapsible panel extender in ASP.Net/C#

Here we are going to demonstrate step by step process to implement ajax collapsible panel extender in ASP.Net/C#. In order to implement collapsible panel extender we need to include ajax control toolkit dll as reference to our visual studio.

  1. Register Ajax control toolkit to your aspx page
  2. Drag and drop a <ScriptManager> from the Toolbox to the page
  3. Now add an UpdatePanel to the page. Inside the <ContentTemplate> drag and drop a CollapsiblePanel from the AJAX toolkit. After applying some Css and add properties of the CollapsiblePanel, the mark up will look similar to the following


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="">
<head runat="server">
<title>CollapsiblePanelExtender Tips </title>   
<style type="text/css">
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
padding: 4px;           
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;               
padding: 4px;
padding-top: 7px;

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">
<asp:Label ID="lblText" runat="server" />

<asp:Panel ID="pBody" runat="server" CssClass="cpBody">
Here will display our contents or controls

<cc1:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
TargetControlID="pBody" CollapseControlID="pHeader" ExpandControlID="pHeader"
Collapsed="true" TextLabelID="lblText" CollapsedText="Click to Show Content.."
ExpandedText="Click to Hide Content.."



How to Expand/Collapse the ASP.NET AJAX CollapsiblePanel programmatically using JavaScript?

In above example we looked that how we can implement ajax collapsible panel extender within the aspx page. In some scenario we need to call this functionality on some javscript events. In those scenario, we need to study that how we can call collapse and expand functionalities from javascript. Below is the code for calling ajax collapsible panel extender from javascript.

<asp:Button ID="btnClick" OnClientClick="ExpandCollapse()"
runat="server" Text="Expand/Collapse" />
Add JavaScript in the <head> tag as shown below:
<script type="text/javascript">

function ExpandCollapse() {           
var collPanel = $find("CollapsiblePanelExtender1");
if (collPanel.get_Collapsed())


How we can implement ajax collapsible panel extender from code behind in ASP.Net/C#?

We are going to check how we can call expand/collapse ajax collapsible panel extender from code behind in In some scenario we need to call expand/collapse functions in Ajax collapsible panel extender dynamically from Below mentioned code helps to dynamically call expand/collapse ajax collapsible panel extender from

protected void btn_Collapse(object sender, EventArgs e)
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = false;
        this.CollapsiblePanelExtender1.ClientState = "false";
        // Collapse
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = true;
        this.CollapsiblePanelExtender1.ClientState = "true";

How to add an Ajax collapsible panel extender dynamically from code behind in ASP.Net/C#

In some scenario we have to create and implement a ajax collapsible panel extender dynamically as per the data from the database in ASP.Net/C#. We can create and implement ajax collapsible panel extender dynamically from code behind in ASP.Net/C# using below mentioned code.


using AjaxControlToolkit;

protected void Page_Load(object sender, EventArgs e)
// Create Header Panel
Panel panelHead = new Panel();
panelHead.ID = "pH";
panelHead.CssClass = "cpHeader";
// Add Label inside header panel to display text
Label lblHead = new Label();
lblHead.ID = "lblHeader";

//Create Body Panel
Panel panelBody = new Panel();
panelBody.ID = "pB";
panelBody.CssClass = "cpBody";
// Add Label inside body Panel to display text
Label lblB = new Label();
lblB.ID = "lblBody";
lblB.Text = "This panel was added dynamically";

// Create CollapsiblePanelExtender
CollapsiblePanelExtender cpe =
    new CollapsiblePanelExtender();
cpe.TargetControlID = panelBody.ID;
cpe.ExpandControlID = panelHead.ID;
cpe.CollapseControlID = panelHead.ID;
cpe.ScrollContents = false;
cpe.Collapsed = true;
cpe.ExpandDirection =
cpe.SuppressPostBack = true;
cpe.TextLabelID = lblHead.ID;
cpe.CollapsedText = "Click to Show Content..";
cpe.ExpandedText = "Click to Hide Content..";



How to refresh page using javascript freaquently and automatically ?

July 25, 2011 2 comments

Refresh web page using javascript with regular intervals

In some scenario, we need to refresh our web page automatically with some interval of time. The better method to do it is using Javascript function. Then we can set a time interval period and for each interval time page will be refresh without any user interaction with web page.

Using setTimeout() with Javascript

The Javascript setTimeout() function allows code to be executed a set of time after some trigger, such as when the page has loaded or a button is pressed.  That means, the setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Syntax of SetTimeOut() in Javascript


Examples of setTimeout() with Javascript

A simple example of setTimeout() in javascript, below sample function shows alert message with the time interval 3 seconds after click the button.

<script type="text/javascript">
function timedMsg()
var t=setTimeout("alert('I am displayed after 3 seconds!')",3000)

<input type="button" value="Display timed alertbox!" onclick="timedMsg()" />


Below mentioned example of setTimeout() in Jvascript will start count down after click the button up to the seconds that we enterd into the text box. It is very simple sample for setTimout(0 in javasscript can be easily understood by beginners also.


<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()

function doTimer()
if (!timer_is_on)

How to reload web page frequently and automatically using javascript setTimeout() function? Below mentioned function will help to refresh page frequently with the time of interval that we mentioned.  We can done it by two methods

  1. In meta tage we can set time of interval and have to also mention url that we have to load with the time of interval.
<meta http-equiv="refresh" content="30;url=index.html">
  1. 2.  Next option is create a method in javascript and call it in page load as mentioned below.  
<script type="text/javascript">
    window.onload = setupRefresh;

    function setupRefresh() {
      setTimeout("refreshPage();", 30000); // milliseconds
    function refreshPage() {
       window.location = location.href;

How to get all classes and methods from a dll in ASP.Net C# using Reflection

July 21, 2011 12 comments

Use of reflection in ASP.Net/How to extract dll file in ASP.Net,C#

By using Reflection class we can access all types of objects in a dll file. Now we are going to demonstrate how we can access all list of classes and methods by browsing a dll file. We can also run a particular method from the dll by passing proper parameters. We are using Reflection class to accept all types from a dll file in ASP.Net, C#.  The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.

What is Reflection in ASP.Net/C#?

  • Reflection is a collection of classes which allow you to query assembly (classes/objects) metadata at runtime. Using reflection you can also create new types and their instances at runtime and invoke methods on these new type instances.
  • Reflection enables you to find out information about types in your assemblies during runtime. Using reflection, you can find out the details of an object’s methods in terms of its access modifier ( private, public etc.), you can discover the name and types of parameters in a methods signature.
  • Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime.
  • Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them.

How to List all classes in a dll file using Asp.Net,C# using reflection?

The following function accept dll file and extracting dll file using reflection class and return all classes in the dll file. We can call this function by dll file path as parameter then it will return all classes in the dll. In our project we are using a openfiledialog control to browse dll file and once the user select the dll file from local folder it will call below mentioned function with parameter as dll path. Then  it will return all classes in the dll file and we are displaying this list of class names in a list so that user can clearly seen all classes in the dll.

Funtion for listing all classes/types in a dll file in ASP.Net,C#

/// <summary>
/// Return all types loaded from desired DLL
/// </summary>
/// <param name="dllName">The DLL in which to parse and get the types from</param>
/// <returns>A filled ArrayList object containing all types </returns>
public ArrayList GetAllTypesFromDLLstring(string dllName)
Assembly _Assemblies = null;
_Assemblies = Assembly.LoadFrom(dllName);
catch (Exception ex)
Console.WriteLine("\n\nError - couldn't obtain assemblies from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
ArrayList _Quit = new ArrayList(1);
return _Quit;

Type[] _AllTypes = _Assemblies.GetTypes();

ArrayList _Temp = new ArrayList();

foreach (Type t in _AllTypes)

return _Temp;

How to access all methods in a dll file in ASP.Net,C# using reflection library

Next we are going to access all methods in a class in the dll file. Here we have to pass dll file patha and class name to list all methods. The output will be the list of all methods in the particular class in the dll file.

Function for listin all methods in a class from dll file using reflection in ASP.Net,C#

/// <summary>
/// Returns all method names from desired DLL/Class
/// </summary>
/// <param name="dllName">The DLL in which to parse for desired class</param>
/// <param name="className">The class in which to parse for all methods</param>
/// <returns>An ArrayList of each method from desired class</returns>
public ArrayList GetAllTypesFromClass(string dllName, string className)
Assembly _Assemblies = Assembly.LoadFrom(dllName);

Type _Type = _Assemblies.GetType(className);

ArrayList _Temp = new ArrayList();

MethodInfo[] _Methods = _Type.GetMethods();

foreach (MethodInfo meth in _Methods)
catch (Exception ex)
Console.WriteLine("\n\nError - couldn't obtain methods from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
_Temp.Capacity = 1;

return _Temp;


Is it possible to run a method in the dll file at run time in ASP.Net,C# using reflection ?

Yes, we can run a particular method in a dll file from our ASP.Net/C# application using reflection library at run time. Let’s see how we can run a method in the assembly file. The below mentioned function demonstrates how we can run a particular method from the,c# application at run time.

Function to call/run a method/function in a dll file from ASP.Net/C#  using reflection at runtime

/// <summary>
/// Runs target Method from target Class from target DLL.
/// </summary>
/// <param name="dllName">The DLL to load and use parse for methods</param>
/// <param name="className">The class to load from specific DLL</param>
/// <param name="methodName">The method to call from class</param>
public void RunClass(string dllName, string className, string methodName)
// Create the assemblies from our current DLL.
Assembly _Assemblies = Assembly.LoadFrom(dllName);

// Get the type that we want from the assemblies.
//  IE: This would be the fully qualified class name (including namespace)
//  Example: "Reflectionism.Examples.Example1" or "Reflectionism.Examples.Example2"
Type _Type = null;
_Type = _Assemblies.GetType(className);
catch (Exception ex)
Console.WriteLine("\n\nError - couldn't obtain classrd from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);

// Get the desired method we want from the target type.
MethodInfo _MethodInfo = null;
_MethodInfo = _Type.GetMethod(methodName);
catch (Exception ex)
Console.WriteLine("\n\nError - couldn't obtain method " +
    methodName + " from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);

// The first parameter to pass into the Invoke Method coming up.
Object _InvokeParam1 = Activator.CreateInstance(_Type);

// This calls the target method ("DisplayMyself").
//  NOTE: I'm not passing any arguments down to the method being invoked.
//  Therefore, I'm passing null as my argument, otherwise Invoke takes an
//  array of Objects.
_MethodInfo.Invoke(_InvokeParam1, null);

Hence we have discussed all possibilities regarding reflection in such as how to access types/classes from dll file, how to get/access methods/functions from dll file/assembly using reflection in, possible way to call/run a method/function in the dll from at run time. We hope you got a needful help from this post. Thanks..

How to access URL or URL parts using javascript / Get the Website URL using JavaScript

July 14, 2011 20 comments

How To Get URL Parts in JavaScript :: A JavaScript Tutorial For Beginners

In some scenario we need to communicate with website url that seen in address bar of the browser using JavaScript. It’s very easy to access the url using javascript. But in order to get query string from URL, default functions or methods are not available. Using javscript we can access the URL using default method in javascript. We are not able to edit URL in javascript without postback. But we can reload the page from javascript and also we can redirect to other url from javascript. Let’s see all about jaavscript with website URL.

How to get website URL in JavaScript / how do I use javascript to get url of current page

Here we are going to explain how we can use javascript to get the website url of the current page. Lets imagine our current page is and we need to get each part of the url separately in javascript. We can access the parts of URL using javascript as follows.

window.location.protocol = "http" = " "
window.location.pathname = "example/index.html"
window.location.href = ""

If we want to access the entire website URL of the current page we can use window.location.href as mentioned above. Also we can access part by part of current page URL in javascript using above mentioned options. But there is no default option to get/access the query string values in current page URL in javascript.

 Redirect to another page using JavScript/ JavaScript redirect to a new page

 By using window.location we can redirect to another website page from javascript. So it’s better to use javascript navigation to redirect to another page instead of response.redirect function. Because Response.Redirect function first send to Server then identifying the web page that we need to navigate and again resend to client. There is a extra round trips will be happen in the case of Response.Redirect method. To avoid this round trips we can use Javascript redirection method as follows.

           window.location = “;;

 How to access/get query string values in website URL using JavaScript (from client side)

 In order to access the querystring  of the current web page there are no default functions or methods in JavaScript.  To get URL parameters using javascript we are demonstrating a function that is used to get all the URL parameters from website in JavaScript.

 Javascript function to get all URL parameters from Website URL

 function getUrlParams() {
    var params = {};[?&]+([^=&]+)=([^&]*)/gi,
function (str, key, value) {
    params[key] = value;
    return params;

 var params = getUrlParams();



 Whenever we want to get querystring values from website URL we can call above function and which returns a object that holds all website URL parameters of the current page as key value pairs.

 How to get a particular querystring value from the URL in JavaScript

 We have noted that we cannot able to get query string from website URL in default methods in JavaScript. So we written a function to get all parameter values in the current page. But if we want to get a particular querystring values from the URL it’s difficult to use above method. That means if I want to get ‘id’ query string from the URL we need to get all parameters from the URL and from that collection get id values. Instead of this we are going to write another function which access the URL parameter name as the function parameter and return value of the particular querystring. If there is no query string in the URL with specified name will return empty string.

 Javascript function to get particular querystring value from the website URL

 function getParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
        return results[1];
var id = getParam('id');

By using above function, we can easily get particular query string from client side script. If we send a value to above function and suppose there is no query string with that name, then it will return empty string. Hence we can easily accessing query string from client side using JavaScript.

How to create thumbnail image in ASP.Net/C# OR resize the image before upload in ASP.Net/C#

July 7, 2011 18 comments

How to reduce the size of image before uploaded to the server in ASP.Net/C#

In most of the ASP.Net application with uploaded image facility will face the performance issue while loading uploaded images to display for the user. We can limited the maximum size of the image that a user can upload but it may not be a good solution because a user has to facing very difficult situation for uploading a large image. He has to reduce the image from other tools and upload again.

The better approach to solve this issue, we are not going to giving any maximum size limit for uploading image. Instead we are internally reducing the size of the image that a user going to upload by checking whether it is exceeds affordable size.  Then there is no constraints are given to user so that he doesn’t care about the size and quality of the image.

Image Size 764 KB

Simple steps to reduce the size of image before upload in ASP.Net/C#

 Here we are going to demonstrate a very simple and best approach to reduce the size of the image before uploaded to the server. In some application we need to show thumbnail image with uploaded images. In that case there is no need to store very large image in the server. So before going to uploading to the server, we are going to create thumbnail image or reduce the size of image as we wish using C#/ This is very simple sample of reducing image and can be easily understand by beginners also.

Step by Step process to create an application for reducing size of image before uploaded to the server in ASP.Net/C#

 Step 1 . Create a ASP.Net project and create a web page.

Step 2.  Drag a file uploader, button and Datalist(for display uploaded images)


 <asp:Panel runat="server">
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>'
NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>'
runat="server" />
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px"
VerticalAlign="Bottom" />


Step 3 .  In page load call function ‘BindDataList’ to display uploaded images

Step 4.   On Save button click event, call function ‘GenerateThumbnails’ for reduce of image.

Code Behind Page 

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
protected void BindDataList()
DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
dtlist.DataSource = listItems;
protected void btnsave_Click(object sender, EventArgs e)
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images1/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.5, strm, targetFile);
private void GenerateThumbnails(double scaleFactor, Stream sourcePath,
string targetPath)
using (var image = Image.FromStream(sourcePath))
// can given width of image as we want
var newWidth = (int)(image.Width * scaleFactor); 
// can given height of image as we want
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);

Image Size 36 KB

By using above application, we can reduce the size of images before uploaded to the server. If we check the size of the image that we uploaded, that will be less than the size of image that having in the local folder. We can implement this mechanism in most of the shopping site and photo gallery sites so that we can store large amount of images with small size and it will help the performance of the application. We can identify that even reducing the size of image there is no variation in quality or clarity of the image.  So we can easily reduce the resolution of the image using above code in ASP.Net/C# application.

%d bloggers like this: