Thursday, March 5, 2009

Convert Word .doc files to .html using ASP.NET

Programatically converting Word DOCs to HTML

This article describes how to use ASP.NET 2 to convert documents in Word .doc format into .html documents. This is done using the built-in features of MS Word, via the COM object.

The reason for doing this was as follows: I wanted to allow users to upload files to my Intranet, through their browser, and make them available for other people to look at. But if they uploaded Word documents, only people with Word installed would be able to view them, causing problems for Mac & Linux users. So, I wanted to get my server to convert the .doc file into a .html file automatically, at the point when the file is uploaded. There was no way that I was going to reverse-engineer a Word doc and figure out how to convert it into html, so instead I used the built-in facility inside MS Word that does this for you. If you give it a Word doc, it will save a .html file, and a separate folder with all the necessary images in it, all linked properly to the html file. Yes, I admit it is an html file full of weird codes, but it does work, in fact very nicely.

How to do it

The first step is that you must have MS Word installed on the server where this ASP.NET page is going to be running. You then add a reference to your ASP.NET project, telling Visual Studio where to find the vital Word library. To do this:

  1. In Solution Explorer, right-click on your project root and select "Add Reference".
  2. Go to the COM tab and find Microsoft Word 11 Object Library.
  3. Click on it and then click OK.

Once you have done this, you will be able to use the "Word" namespace in your project.

To test it, make a sample webpage, perhaps called test.aspx, and put a FileUpload, a Button and a Label on it. The FileUpload component is used to upload the file; the Button is clicked to make the process start, and the Label is used to display a success message.

The complete code for the upload routine is here:

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// When we click Button1, the file we specify is uploaded to a temporary
// folder, then converted into an html document...
string folder_to_save_in = @"c:\temp\documents\";
string filePath = folder_to_save_in + FileUpload1.FileName;
// This bit does the actual file upload:
FileUpload1.SaveAs(filePath);

// Here we set up a WOrd Application...
Word.ApplicationClass wordApplication = new Word.ApplicationClass();

// Opening a Word doc requires many parameters, but we leave most of them blank...
object o_nullobject = System.Reflection.Missing.Value;
object o_filePath = filePath;
Word.Document doc = wordApplication.Documents.Open(ref o_filePath,
ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject,
ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject,
ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject);

// Here we save it in html format...
// This assumes it was called "something.doc"
string newfilename = folder_to_save_in + FileUpload1.FileName.Replace(".doc", ".html");
object o_newfilename = newfilename;
object o_format = Word.WdSaveFormat.wdFormatHTML;
object o_encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
object o_endings = Word.WdLineEndingType.wdCRLF;
// Once again, we leave many of the parameters blank.
// See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbawd11/html/womthSaveAs1_HV05213080.asp
// for full list of parameters.
wordApplication.ActiveDocument.SaveAs(ref o_newfilename, ref o_format, ref o_nullobject,
ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject,
ref o_nullobject, ref o_nullobject, ref o_encoding, ref o_nullobject,
ref o_nullobject, ref o_endings, ref o_nullobject);

// Report success...
Label1.Text = "Uploaded successfully!";
// Finally, close original...
doc.Close(ref o_nullobject, ref o_nullobject, ref o_nullobject);
}
}

And that is it really. When you browse to a file and click the upload button, the file is uploaded to your server and stored in the temp folder. Then, this doc file is opened, and a SaveAs performed. This saves the new .html file in the same temp folder, with the associated image files in a subfolder with the same name as the .html file, but with _files appended to its name.

Sunday, March 1, 2009

DateTimePicker in datagridview using C#

If you want to add datetimepicker in datagridview then you have to create a custom control and its very easy.

If you create a seperate project and then you can use the dll in you future projects.

I have given the code just copy and past your project. Make it as seperate project then simply by adding the dll you can do it.

Step 1: Create a project name: datetimePicker_gridview

Step 2: Create the CalendarCell class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace datetimePicker_gridview
{
class CalendarCell : DataGridViewTextBoxCell
{

public CalendarCell(): base()
{
// Use the short date format.
this.Style.Format = "dd MMM yy";
}

public override void InitializeEditingControl(int rowIndex, object
initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
// Set the value of the editing control to the current cell value.
base.InitializeEditingControl(rowIndex, initialFormattedValue,dataGridViewCellStyle);
CalendarEditingControl ctl =DataGridView.EditingControl as CalendarEditingControl;
try
{
if (this.Value != DBNull.Value)
ctl.Value = (DateTime)this.Value;
}
catch (Exception err) { }
}

public override Type EditType
{
get
{
// Return the type of the editing contol that CalendarCell uses.
return typeof(CalendarEditingControl);
}
}

public override Type ValueType
{
get
{
// Return the type of the value that CalendarCell contains.
return typeof(DateTime);
}
}

public override object DefaultNewRowValue
{
get
{
// Use the current date and time as the default value.
return "";///DateTime.Now;
}
}

}
}


Step 3: Create the CalendarColumn class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Windows.Forms;

namespace datetimePicker_gridview
{
public class CalendarColumn : DataGridViewColumn
{
public CalendarColumn(): base(new CalendarCell())
{
}

public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
// Ensure that the cell used for the template is a CalendarCell.
if (value != null && !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
{
throw new InvalidCastException("Must be a CalendarCell");
}
base.CellTemplate = value;
}
}

}
}


Step 4: Create the CalendarEditingControl class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace datetimePicker_gridview
{
class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
{
DataGridView dataGridView;
private bool valueChanged = false;
int rowIndex;

public CalendarEditingControl()
{
this.Format = DateTimePickerFormat.Short;
}

// Implements the IDataGridViewEditingControl.EditingControlFormattedValue
// property.
public object EditingControlFormattedValue
{
get
{
return this.Value.ToShortDateString();
}
set
{
if (value is String)
{
this.Value = DateTime.Parse((String)value);
}
}
}

// Implements the
// IDataGridViewEditingControl.GetEditingControlFormattedValue method.
public object GetEditingControlFormattedValue(
DataGridViewDataErrorContexts context)
{
return EditingControlFormattedValue;
}

// Implements the
// IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
public void ApplyCellStyleToEditingControl(
DataGridViewCellStyle dataGridViewCellStyle)
{
this.Font = dataGridViewCellStyle.Font;
this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
}

// Implements the IDataGridViewEditingControl.EditingControlRowIndex
// property.
public int EditingControlRowIndex
{
get
{
return rowIndex;
}
set
{
rowIndex = value;
}
}

// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey
// method.
public bool EditingControlWantsInputKey(
Keys key, bool dataGridViewWantsInputKey)
{
// Let the DateTimePicker handle the keys listed.
switch (key & Keys.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Home:
case Keys.End:
case Keys.PageDown:
case Keys.PageUp:
return true;
default:
return !dataGridViewWantsInputKey;
}
}

// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit
// method.
public void PrepareEditingControlForEdit(bool selectAll)
{
// No preparation needs to be done.
}

// Implements the IDataGridViewEditingControl
// .RepositionEditingControlOnValueChange property.
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}

// Implements the IDataGridViewEditingControl
// .EditingControlDataGridView property.
public DataGridView EditingControlDataGridView
{
get
{
return dataGridView;
}
set
{
dataGridView = value;
}
}

// Implements the IDataGridViewEditingControl
// .EditingControlValueChanged property.
public bool EditingControlValueChanged
{
get
{
return valueChanged;
}
set
{
valueChanged = value;
}
}

// Implements the IDataGridViewEditingControl
// .EditingPanelCursor property.
public Cursor EditingPanelCursor
{
get
{
return base.Cursor;
}
}

protected override void OnValueChanged(EventArgs eventargs)
{
// Notify the DataGridView that the contents of the cell
// have changed.
valueChanged = true;
this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
base.OnValueChanged(eventargs);
}

}
}


Now Just create a form and test it.

private DataGridView dataGridView1 = new DataGridView();

public Form1()
{
InitializeComponent();

this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView calendar column ";
}

private void Form1_Load(object sender, EventArgs e)
{
CalendarColumn col = new CalendarColumn();
col.HeaderText = "Date";
this.dataGridView1 .Columns.Add(col);
this.dataGridView1 .RowCount = 5;
foreach (DataGridViewRow row in this.dataGridView1 .Rows)
{
row.Cells[0].Value = DateTime.Now;
}
}


Thats all. Now use it.


One more thing you can do. when you are create the datagridview after createing and binding with dataSet

1. Click on CodeView in your form (which containig datagridview)
2. got to InitializeComponent();
3. Change your desire column type from System.Windows.Forms.DataGridViewTextBoxColumn to datetimePicker_gridview.CalendarColumn

No check it.

Thanks