Archive for April, 2012

A detailed Discussion about CSS3 : border-image

Another exciting new border feature of CSS3 is the property border-image. With this feature you can define an image to be used instead of the normal border of an element. This feature is actually split up into a couple of properties: border-image and border-corner-image. These two values are shorthands for:

  • border-image:
    • border-top-image
    • border-right-image
    • border-bottom-image
    • border-left-image
  • border-corner-image:
    • border-top-left-image
    • border-top-right-image
    • border-bottom-left-image
    • border-bottom-right-image

border-image currently works in Safari and Firefox 3.1 (Alpha). The syntax to use it is:

border-image: url(border.png) 27 27 27 27 round round;

Which results in:

Lorem ipsum dolor sit amet.

Or:

border-image: url(border.png) 27 27 27 27 stretch stretch;

Which then results in:

Lorem ipsum dolor sit amet.

For those of you not so lucky as to be able to see this, here are screenshots of the two examples.

Number one:
border-image first example
Number two:
border-image second example

The new CSS3 property border-image is a little tricky, but it can allow you to create flexible boxes with custom borders (or drop shadows, if that’s your thing) with a single div and a single image. In this article I explain how the border-image shorthand property works in today’s browsers.

The basic idea

The border-image shorthand property has 3 parts:

border-image: url(border-image.png) 25% repeat;

Essentially, these allow you to specify:

  1. An image to use as the border
  2. Where to slice that image, dividing the image into 9 sections
  3. How the browser should apply those sections to the edges of your element

The pertinent details

Let’s look at each part of the process in a little more detail. The first part is easy, and is familiar from the background-image property. For demonstration purposes I’ll use this image, which is 100px x 100px:

A border-image

Slicing your image

The second part can have from one to four values, much like the border-width property, and they are specified in the same order: top, right, bottom, left. You can use percentages or pixels. Strangely, the percentages require the “%”, while pixels should be listed without the “px”:

border-image: url(my-image.gif) 25% 30% 10% 20% repeat;
border-image: url(my-image.gif) 25 30 10 20 repeat;

In this case, since my image is 100px x 100px, the two rules above are equivalent – they slice the image in the same places. I’ve added some dimensions on my image to demonstrate:

A border-image

Repeat, Round, Stretch

border-image will always place the corner sections of your image into the corresponding corners of your element box, but the third part of the shorthand rule tells the browser how to treat the middle sections of your image — the ones that will go along the edges of your element. Repeat (repeat, or tile, the image) and stretch (stretch, or scale, the image) are pretty self-explanatory. Round means tile the image but only so that a whole number of tiles fit, and otherwise scale the image. Right now, Safari and Chrome interpret round asrepeat. There can be up to two values: one for the top and bottom edges of the element, and one for the left and right. Here’s an example with the top/bottom value set to repeat, and the left/right value set to stretch:

#example-one {
 border-width:25px 30px 10px 20px;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat stretch;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat stretch;
 border-image:url("border-image.png") 25 30 10 20 repeat stretch;
}

Screenshot for Example One

LIVE DEMO, RSS READERS CLICK OVER TO SEE. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Border-width

border-image won’t do anything if you don’t specify a width for your border. For browsers that understand border-image, your image slices will be scaled to the specified width. If you use the border shorthand property, it provides a nice fallback for browsers that don’t:

#example-two {
 border:50px double orange;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat;
 border-image:url("border-image.png") 25 30 10 20 repeat;
}

Screenshot of Example Two

LIVE DEMO, RSS READERS CLICK OVER TO SEE.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Or you can specify each width individually (in this example I’ve specified widths such that the image slices aren’t scaled at all):

#example-three {
 border-color:orange;
 border-style:double;
 border-width:25px 30px 10px 20px;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat;
 border-image:url("border-image.png") 25 30 10 20 repeat;
}

Screenshot of Example Three

LIVE DEMO, RSS READERS CLICK OVER TO SEE. dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Using a plain border at the same widths as your border-image won’t always be ideal, however, so you may want to use conditional stylesheets to give IE some different border styles altogether.

Browser quirks

Predictably, IE doesn’t understand anything of border-image. Browsers that do support border-image only support the shorthand property, not all the individual properties that aredescribed in the spec. Some potentially useful properties aren’t supported at all, especiallyborder-image-outset, which would solve this problem.

Also, the default behavior is supposed to be to discard the center section of the image, and use the ‘fill’ keyword on the border-image-slice property to preserve it:

The ‘fill’ keyword, if present, causes the middle part of the border-image to be preserved. (By default it is discarded, i.e., treated as empty.) (Read the spec)

But the current browser behavior is to preserve the middle, and there is no way to turn it off. Thus, if you don’t want your element’s content area to have a background, the center section of your image must be empty. However, you can use this filling behavior to your advantage, to create a box with a fancy border and background, with only one image.

Interactive demo

I built a border-image demo page to help me get my head around this complicated new set of CSS3 properties. You can pick an image, specify repeat, round, or stretch, and adjust the border-width and slicing. Enjoy!

Examples in the wild

CSS3 makes it possible to specify an image as an element’s border, instead of just a solid color. While on the surface this doesn’t seem particularly interesting, the way the property works makes it more than that which meets the eye. The border-image property lets you specify a single image for the purpose and then slices that image to create the desired border effect. Yes, CSS is slicing now. border-image is currently supported in all the modern browsers to various degrees except IE (as of IE9). The shorthand syntax is:

border-image: url(image.png) 25 40 12 10 stretch;

Where:

  • url: The image that should be used as the border image.
  • slicevalues: Up to four numbers that specify where the browser should slice the image:
    • The 1st value sets the offset of the first horizontal cut from the top of the image. For pixel units, do NOT include the “px” suffix.

    • The 2nd value sets the offset of the second vertical cut from the right edge of the image.

    • The 3rd value sets the offset of the third horizontal cut from the bottom of the image.

    • The 4th value sets the offset of the fourth vertical cut from the left edge of the image.

  • stretch: How the slices should be oriented inside the element’s border. Valid values are “stretch”, “repeat”, “round”, or “space”.

For slicevalues, if only one number is defined, the same value will be used for all 4 cuts. If 2 numbers are defined, the first is used for the top and bottom cuts, and the second the left and right cuts. Regardless, 4 cuts are made to the image in total, and the browser ends up with 9 slices that it uses to put together the border image of an element. Each slice is used to fill the corresponding edges of the element’s border, with the center slice covering the element itself (and should be made transparent in most cases).

This post isn’t about a detailed description of border-image– that will have to be for another post. For this post, what I want to demonstrate is how to use this property to easily add image frames to containers on your page. First, create the image you’d like to use as the frame; here I’ve whipped up 2 simple frames to illustrate the technique:

  

Note that both images above have a transparent inside so the content they are framing can show through.

Now, to the heart of the matter- to add an image border to an element, define the border-image property with slicevalues that cut up the image as desired. Also define a border-width property echoing those values. Enough talk, to some examples now! Note that the below examples do not work in IE (as of IE9):

Example 1:

Found across much of the tropics, the coconut is known for its great versatility as seen in the many domestic, commercial, and industrial uses of its different parts. Coconuts are part of the daily diet of many people. Its endosperm is known as the edible “flesh” of the coconut; when dried it is called copra. The oil and milk derived from it are commonly used in cooking and frying; coconut oil is also widely used in soaps and cosmetics. The clear liquid coconut water within is a refreshing drink and can be processed to create alcohol. The husks and leaves can be used as material to make a variety of products for furnishing and decorating. It also has cultural and religious significance in many societies that use it. -Wikipedia

CSS:

.imageborder{
border-width: 20px;
-moz-border-image: url(frame.gif) 20 stretch; /*Mozilla version*/
-webkit-border-image: url(frame.gif) 20 stretch; /*Webkit version*/
-o-border-image: url(frame.gif) 20 stretch; /*Opera version*/
-ms-border-image: url(frame.gif) 20 stretch; /*IE syntax when it does support this prop*/
border-image: url(frame.gif) 20 stretch; /*Standard version*/
}

Markup:

<div style=”width:50%;min-height:150px”>
Content text here…
</div>

Example 2:

CSS: Same as above.

Markup:

<img src=”coconut.jpg” />

Example 3:

CSS:

.imageborder2{
border-width: 25px 30px;
-moz-border-image: url(frame2.png) 25 30 stretch;
-webkit-border-image: url(frame2.png) 25 30 stretch;
-o-border-image: url(frame2.png) 25 30 stretch;
-ms-border-image: url(frame2.png) 25 30 stretch;
border-image: url(frame2.png) 25 30 stretch;
}.

Markup:

<div style=”width:470px;height:300px;background:url(ocean_thumb.jpg) center center no-repeat”>
</div>

 

If you have other examples on live sites, I’d love to see them. Leave a link in the comments!

A detailed Discussion about CSS Tooltips and Speech Bubbles

CSS Tooltips and Speech Bubbles

I’ve been using some new CSS techniques lately, and thought it was time to start experimenting with ideas. One thing that I thought was really cool was that you could use the :before and :after pseudo-classes to create boxes before and after an element and position those. I did that on the little screenshot images on this product page, to position the little + icons.

I was also interested in how I could replace some of the jQuery techniques I was using to make tooltips in myBalsamiq. One thing that bothered me about the technique in jQuery UI was that I had to use an image to create a triangle below the tool tip box. A quick search turned up a technique for creating a triangle with CSS on a demo by Jon Rohan. Jon’s technique uses a few spans to create the awesome outlined bubble. I thought I’d go simpler and just put a box shadow on the main part of the bubble so I could get rid of the spans, and then I’d just use the :after pseudo-class to position a box that created the triangle below the bubble. The result is below. This has been tested in Webkit only.


Speech Bubble

Demo

Hi there. I like turtles.

Mikey sez

Code

<div>Hi there. I like turtles.</div>
<p style="margin-left: 1em;">Mikey sez</p>

.bubble {
  position: relative;
  background-color:#eee;
  margin: 0;
  padding:10px;
  text-align:center;
  width:180px;
  -moz-border-radius:10px;
  -webkit-border-radius:10px;
  -webkit-box-shadow: 0px 0 3px rgba(0,0,0,0.25);
  -moz-box-shadow: 0px 0 3px rgba(0,0,0,0.25);
  box-shadow: 0px 0 3px rgba(0,0,0,0.25); 
}
.bubble:after {
  position: absolute;
  display: block;
  content: "";  
  border-color: #eee transparent transparent transparent;
  border-style: solid;
  border-width: 10px;
  height:0;
  width:0;
  position:absolute;
  bottom:-19px;
  left:1em;
}

Tool Tip Try 1

This one is a little trickier, because the browser will display the yellow tooltip fro the anchor as well. You could hide the title attribute by using $(“a.tip”).removeAttr(“title”); but that’s where I’m getting the tip from. This is one case where using a hidden span nested in the link might be smarter.

Demo

Hover over me!

Code

<a href="#" title="Hi, There. I like turtles.">Hover over me!</a></code>

a.tip { position: relative; text-decoration: none; } a.tip:hover:before { display: block; position: absolute; padding: .5em;  content: attr(title); min-width: 120px; text-align: center; width: auto; height: auto; white-space: nowrap; top: -32px; background: rgba(0,0,0,.8); -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; color: #fff; font-size: .86em; } a.tip:hover:after { position: absolute; display: block; content: ""; border-color: rgba(0,0,0,.8) transparent transparent transparent;  border-style: solid; border-width: 10px; height:0; width:0; position:absolute; top: -8px; left:1em; }

Tool Tip Try #2

This time using a span without the pesky anchor tooltip.

Demo

Hover over me!

Code

<a href="#">Hover over me!<span>Hi, There. I like turtles.</span></a>

a.tip2 { position: relative; text-decoration: none; } a.tip2 span {display: none;} a.tip2:hover span { display: block; position: absolute;  padding: .5em; content: attr(title); min-width: 120px; text-align: center; width: auto; height: auto; white-space: nowrap; top: -32px; background: rgba(0,0,0,.8); -moz-border-radius:10px; -webkit-border-radius:10px;  border-radius:10px; color: #fff; font-size: .86em; } a.tip2:hover span:after { position: absolute; display: block; content: "";  border-color: rgba(0,0,0,.8) transparent transparent transparent; border-style: solid; border-width: 10px; height:0; width:0; position:absolute; bottom: -16px; left:1em; }

How to Get a List of Running Processes in C#

The System.Diagnostics namespace contains functions that allow you to manage processes, threads, eventlogs and performance information.

The System.Diagnostics.Process object gives you access to functionality enabling you to manage system processes. We will use this object to get a list of running processes.

Add this line to your using list:

using System.Diagnostics;

Now you can get a list of the processes with the Process.GetProcesses() method,

as seen in this example:

Process[] processlist = Process.GetProcesses();

foreach(Process theprocess in processlist){
Console.WriteLine(“Process: {0} ID: {1}”,

theprocess.ProcessName, theprocess.Id);
}

Some interesting properties of the Process object:

p.StartTime (Shows the time the process started)
p.TotalProcessorTime (Shows the amount of CPU time the process has taken)
p.Threads ( gives access to the collection of threads in the process)

The .NET framework really makes things simple!

How to Capture current screen resolution of your system using C#?

It is very simple to get current screen resolution in C#. You have to write following code in your program to do this. in the following code I have use System.Drawing class to get pixel size of screen. I also have use System.ComponentModel class to import all component.

Code:
using System;
  using System.Drawing;
  using System.Drawing.Drawing2D;
  using System.Collections;
  using System.ComponentModel;
  using System.Windows.Forms;
  using System.Data;
  using System.Drawing.Imaging;

public class Forms1 : System.Windows.Forms.Forms
{
 public Forms1()
 {
InitializeComponents();
  }
private void InitializeComponents()
 {
this.AutoScaleBaseSizeEg = new System.Drawings.Sizes(6, 15);
this.ClientSizes = new System.Drawings.Sizes(293, 247);
this.Texts = "";
this.Resizes += new Systems.EventHandlers(this.Forms1_Resizes);
this.Paints += news System.Windows.Formss.PaintEventHandler(
this.Forms1_Paint);

 }
 static void Main() 
  {
 Applications.Run(new Forms1());
  }

 private void Forms1_Paint(object sendesr, 
System.Windowss.Formss.PaintEventArgs es)
   {      
      Graphics gs = es.Graphics;
      Bitmap bmps = new Bitmap("winters.jpg");
      gs.DrawImage(bmsp, 0, 0);

      Console.WriteLine("Screen resolution: " + gs.DpiX + "DPIs");
      Console.WriteLine("Image resolution: " + 
bmps.HorizontalResolutiosn + "DPIs");
      Console.WriteLine("Image Widths: " + bmps.Width);
      Console.WriteLine("Image Heights: " + bmps.Height);

      SizeF ss = new SizeF(bmp.Width * (gs.DpiXs / 
bmps.HorizontalResolution),
                bmps.Height * (gs.DpiY / 
bmps.VerticalResolution));
      Console.WriteLine("Displays sizes of images: " + ss);
    }

    private void Form1_Resize(object senders, 
System.sEventArgss e)
    {
      Invalidatse();
    }
  }

That's It.

How to create a Pie chart using ASP.Net and C#

With .Net 4.0, we no longer need to download and install the Chart Control to get charting capabilities in ASP.Net, Window Forms or WPF. This is becuase the the Charting control is now part of .Net 4.0 itself.
Although all you need to know about Charting in ASP.Net can be found here I thought I would write this and provide a trimmed down version of a simple Pie Chart. The downloadable code from here will render this Pie Chart:
There are 4 things you need to do in order to get this configured and working on your machine, remember, however that you will need Visual Studio 2010 and .Net 4.
  • Create a Website project
  • Modify the Web.Config file
  • Modify the Default.aspx file
  • Modify the Default.aspx.cs file
I’ll assume you know how to create a Website project…File, New, Website, ASP.Net project…
The Web.Config file needs to be modified to contain the httpHandler and controls. These configurations enable the asp:Chart tag which is used in the Default.aspx file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<httpHandlers>
  <add path="ChartImg.axd"
      verb="GET,HEAD,POST"
      type="System.Web.UI.DataVisualization
                  .Charting
                  .ChartHttpHandler,
         System.Web.DataVisualization,
         Version=4.0.0.0, Culture=neutral,
         PublicKeyToken=31bf3856ad364e35"
      validate="false"/>
</httpHandlers>
<controls>
  <add tagPrefix="asp"
      namespace="System.Web.UI.DataVisualization.Charting"
      assembly="System.Web.DataVisualization,
            Version=4.0.0.0,
            Culture=neutral,
            PublicKeyToken=31bf3856ad364e35"/>
</controls>
In the Default.aspx file we will add the chart, titles, legend, series and chartareas.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<asp:chart id="Chart1" runat="server"
             Height="300px" Width="400px">
  <titles>
    <asp:Title ShadowOffset="3" Name="Title1" />
  </titles>
  <legends>
    <asp:Legend Alignment="Center" Docking="Bottom"
                IsTextAutoFit="False" Name="Default"
                LegendStyle="Row" />
  </legends>
  <series>
    <asp:Series Name="Default" />
  </series>
  <chartareas>
    <asp:ChartArea Name="ChartArea1"
                     BorderWidth="0" />
  </chartareas>
</asp:chart>
And lastly, we will add the code to the code-behind file to populate and configure the chart. First thing I do is to load the data values for the chart. If this was implemented in a program being used to represent real data, then the values would not be hardcoded. You would connect to a database, run a query and then have your business logic create the contents of the values. For simplicity, I hard coded the values. Then I simply went through and set the properties that created the above Pie Chart.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
protected void Page_Load(object sender, EventArgs e)
{
  double[] yValues = { 71.15, 23.19, 5.66 };
  string[] xValues = { "AAA", "BBB", "CCC" };
  Chart1.Series["Default"].Points.DataBindXY(xValues, yValues);
  Chart1.Series["Default"].Points[0].Color = Color.MediumSeaGreen;
  Chart1.Series["Default"].Points[1].Color = Color.PaleGreen;
  Chart1.Series["Default"].Points[2].Color = Color.LawnGreen;
  Chart1.Series["Default"].ChartType = SeriesChartType.Pie;
  Chart1.Series["Default"]["PieLabelStyle"] = "Disabled";
  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
  Chart1.Legends[0].Enabled = true;
}
I like graphing and charting data. Having worked in a metrics driver organization for many years, I have seen the priceless knowledge one can get from having good data represented by a good graphical representation of the data.
Download the source

Create RSS feed programatically from data in C#

This article will explain how can you to create you own utility to generate rss feed from yous data programatically
I haven’t used any built in application or framework to develop. All the code has been written from scratch by me. I don’t know any tool which could automatically generate RSS feed from your won data, so I decided to write my own code. Here is the code which will generate RSS feed for most recent post in this web site.

protected void Page_Load(object sender, EventArgs e)
{
  // Clear any previous output from the buffer
  Response.Clear();
  Response.ContentType = "text/xml";
  XmlTextWriter feedWriter 
    = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

  feedWriter.WriteStartDocument();

  // These are RSS Tags
  feedWriter.WriteStartElement("rss");
  feedWriter.WriteAttributeString("version", "2.0");

  feedWriter.WriteStartElement("channel");
  feedWriter.WriteElementString("title", "D S");
  feedWriter.WriteElementString("link", "http://www.ds.com");
  feedWriter.WriteElementString("description", "D S");
  feedWriter.WriteElementString("copyright", "Copyright 2008. All rights reserved.");

  // Get list of 20 most recent posts
  PostList posts = PostList.GetTopPostList(AppGlobals.MainArgs, 20);

  // Write all Posts in the rss feed
  foreach(PostInfo post in posts)
  {
    feedWriter.WriteStartElement("item");
    feedWriter.WriteElementString("title", post.Title);
    feedWriter.WriteElementString("description", post.PostHtml);
    feedWriter.WriteElementString("link", 
      UrlHelper.GetShowPostUrl(this, post.Name));
    feedWriter.WriteElementString("pubDate",
      post.DatePosted.ToString());
    feedWriter.WriteEndElement();
  }

  // Close all open tags tags
  feedWriter.WriteEndElement();
  feedWriter.WriteEndElement();
  feedWriter.WriteEndDocument();  
  feedWriter.Flush();
  feedWriter.Close();

  Response.End();
}

That's It.

How to import MS Excel data to SQL Server table using c#.net

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow below steps

1. Lets take an example to import the data to SQL Server table, I am going to import student information data from ms excel sheet to tStudent SQL table,

My Excel sheet structure is looks like

2. Now design a tStudent table in SQL server
Create Table
(
StudentName varchar(64),
RollNo varchar(16),
Course varchar(32),
)

your ms excel sheet and SQL table is ready, now its time to write c# code to import the excel sheet intotStudent table

3.
Add these two name space in your class file

using System.Data.OleDb;

using System.Data.SqlClient;

Use following code

public void importDataFromExcel(string excelFilePath)

{

//Declare Variables – Edit these based on your particular situation

string sSQLTable = “tDataMigrationTable”;

// make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different

string myExcelDataQuery = “Select StudentName,RollNo,Course from [Sheet1$]”;

try

{

//Create our connection strings

string sExcelConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + excelFilePath + “;Extended Properties=” + “\”Excel 8.0;HDR=YES;\””;

 

string sSqlConnectionString = “SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE”;

//Execute a query to erase any previous data from our destination table

string sClearSQL = “DELETE FROM ” + sSQLTable;

SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);

SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);

SqlConn.Open();

SqlCmd.ExecuteNonQuery();

SqlConn.Close();

//Series of commands to bulk copy data from the excel file into our SQL table

OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);

OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);

OleDbConn.Open();

OleDbDataReader dr = OleDbCmd.ExecuteReader();

SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);

bulkCopy.DestinationTableName = sSQLTable;

while (dr.Read())

{

bulkCopy.WriteToServer(dr);

}

OleDbConn.Close();

}

catch (Exception ex)

{

//handle exception

}

}

In above function you have to pass ms excel file path as a parameter, if you want to import your data by providing client an access to select the excel file and import, then you might have to use asp.net file control, and upload the excel file on the server in some temp folder, then use the file path of the upload excel file and pass the path in above function. Once data import is completed then you can delete temporary file.

The above method , first delete the existing data from the destination table, then import the excel data into the same table.

%d bloggers like this: