Friday, July 31, 2009

export data image to excel from gridview

http://www.aspsnippets.com/post/2009/04/23/Export-GridView-with-Images-to-Word-Excel-and-PDF-Formats-in-ASPNet.aspx

Thursday, July 30, 2009

merge cell of same data in grid view

public static void MergeRows(GridView gridView)
{
for (int rowIndex = 0; rowIndex <= gridView.Rows.Count - 1; rowIndex++)
{
GridViewRow row = gridView.Rows[rowIndex];

for (int i = 2; i {
int j = 1;
for (int z = i+1; z < row.Cells.Count ; z++)
{
if (row.Cells[i].Text == row.Cells[z].Text)
{
j++;
}
else
{
break;
}
}
row.Cells[i].ColumnSpan = j;
if (j > 1)
{
for (int k = 1; k <= j - 1; k++)
{
i++;
row.Cells[i].Visible = false;

}

}
}
}

}

export data to excel from gridview

public void ExportGridToExcel(GridView grdGridView, string fileName)
{

Response.Clear();

Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";

Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{

}

Merge Header - Gridview/DataGrid

protected void GridView_Merge_Header_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Build custom header.
GridView oGridView = (GridView)sender;
GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell oTableCell = new TableCell();

//Add Department
oTableCell.Text = "Department";
oTableCell.ColumnSpan = 2;
oGridViewRow.Cells.Add(oTableCell);

//Add Employee
oTableCell = new TableCell();
oTableCell.Text = "Employee";
oTableCell.ColumnSpan = 3;
oGridViewRow.Cells.Add(oTableCell);
oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
}
}

Merging columns in GridView/DataGrid header

Background
As necessity to show header columns in a few rows occurs fairly often it would be good to have such functionality in the GridView/DataGrid control as an in-built feature. But meanwhile everyone solves this problem in his own way.

The described below variant of the merging implementation is based on irwansyah's idea to use the SetRenderMethodDelegate method for custom rendering of grid columns header. I guess this approach can be simplified in order to get more compact and handy code for reuse.

The code overview

As it may be required to merge a few groups of columns - for example, 1,2 and 4,5,6 - we need a class to store common information about all united columns.
[Serializable]
private class MergedColumnsInfo
{
// indexes of merged columns
public List MergedColumns = new List();
// key-value pairs: key = the first column index, value = number of the merged columns
public Hashtable StartColumns = new Hashtable();
// key-value pairs: key = the first column index, value = common title of the merged columns
public Hashtable Titles = new Hashtable();

//parameters: the merged columns indexes, common title of the merged columns
public void AddMergedColumns(int[] columnsIndexes, string title)
{
MergedColumns.AddRange(columnsIndexes);
StartColumns.Add(columnsIndexes[0], columnsIndexes.Length);
Titles.Add(columnsIndexes[0], title);
}
}

Attribute Serializable is added in order to have a possibility to store information about merged columns in ViewState - it is required if paging or sorting is used.
That is the only additional action. Now the code usage.

.ascx file:

//for GridView

//for DataGrid


Columns can be defined in design time or can be auto generated - it does not matter and doesn't influence the further code. Merging also does not harm sorting and paging if they are used in the GridView/DataGrid.

.cs file:

//property for storing of information about merged columns
private MergedColumnsInfo info
{
get
{
if (ViewState["info"] == null)
ViewState["info"] = new MergedColumnsInfo();
return (MergedColumnsInfo)ViewState["info"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//merge the second, third and fourth columns with common title "Subjects"
info.AddMergedColumns(new int[] { 1, 2, 3 }, "Subjects");
grid.DataSource = ... //some data source
grid.DataBind();
}
}


Particular code for GridView: protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
//call the method for custom rendering the columns headers
if (e.Row.RowType == DataControlRowType.Header)
e.Row.SetRenderMethodDelegate(RenderHeader);
}


and for DataGrid: protected void DataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
//call the method for custom rendering the columns headers
if (e.Item.ItemType == ListItemType.Header)
e.Item.SetRenderMethodDelegate(RenderHeader);
}

Next code is common for both GridView and DataGrid:

//method for rendering the columns headers

private void RenderHeader(HtmlTextWriter output, Control container)
{
for (int i = 0; i < container.Controls.Count; i++)
{
TableCell cell = (TableCell)container.Controls[i];
//stretch non merged columns for two rows
if (!info.MergedColumns.Contains(i))
{
cell.Attributes["rowspan"] = "2";
cell.RenderControl(output);
}
else //render merged columns common title
if (info.StartColumns.Contains(i))
{
output.Write(string.Format("{1}",
info.StartColumns[i], info.Titles[i]));
}
}

//close the first row
output.RenderEndTag();
//set attributes for the second row
grid.HeaderStyle.AddAttributesToRender(output);
//start the second row
output.RenderBeginTag("tr");

//render the second row (only the merged columns)
for (int i = 0; i < info.MergedColumns.Count; i++)
{
TableCell cell = (TableCell)container.Controls[info.MergedColumns[i]];
cell.RenderControl(output);
}
}

Wednesday, July 22, 2009

convert dd/mm/yyyy to any format

Dim result As String = DateTime.ParseExact("24/5/2009 3:40:00 AM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture) .ToString("M/d/yyyy h:mm:ss tt")

Wednesday, July 15, 2009

ASP.net Tips

1.Smart navigation
Smart navigation is a little-known Internet Explorer feature that enables the individual controls on your Web forms to maintain focus between postback, as well as allows you to suppress that flicker that occurs as you load the new page.
To turn on this little-known feature, simply set the smartNavigation property of your ASPX page to True. You can also apply the property to all project pages, by adding the tag to the following location within your Web.config file:










Note that smart navigation works on only Internet Explorer 5 and above; however, ASP.NET will automatically detect this and serve up the ?smart? code only if the target browser supports it.

Also, I?d personally advise that you test it against any third-party menu controls or scripts you may have running: it is prone to falling over on particularly advanced pages.

2.Stopping Your User from Right-Clicking
Want to prevent your user from performing any of the other commands available by right-clicking on a Web page in Internet Explorer? It?s not foolproof, but this neat little HTML edit usually does the trick.

Just alter the opening tag of your HTML to the following:



When the menu is requested, the oncontextmenu event runs, and we instantly cancel it using JavaScript. This is especially potent as a method for stopping the user from viewing your source, when used in conjunction with a menu-less browser window. Great stuff!

3.Creating Images Dynamically
Ask any ASP developer who has ever tried to dynamically create his own images and he?ll tell you it?s a nightmare. In fact, it?s more than a nightmare. It?s practically hell. The only true solution? Reverting to an expensive, dodgy, third-party control to do the work for you.

With ASP.NET, however, you can develop your own dynamic images with ease. Simply create an image object and use the new GDI+ features to add objects to that image, such as text, rectangles, and ellipses. After that, you can simply stream straight back down to the client.

But covering the graphics features in depth would require at least another two books, and, unfortunately, we don?t have that much room. So, I?m going to share a sample that demonstrates creating a small ?Drawing? button, alongside a little blue-and-yellow bullet point.It?s the sort of personalized graphic you?ll find on sites such as Amazon.com.

Here?s the code:

Bitmap objBitmap = new Bitmap(120, 30);
Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.FillRectangle(new SolidBrush(Color.LightBlue), 0, 0, 120, 30);
objGraphics.FillEllipse(new SolidBrush(Color.Blue), 3, 9, 10, 10);
objGraphics.FillEllipse(new SolidBrush(Color.Yellow), 4, 10, 8, 8);
objGraphics.DrawString("Drawing", new Font("Tahoma", 8), new SolidBrush(Color.Green), 16, 8);
Response.Clear();
Response.ContentType = "image/jpeg";
objBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
objGraphics.Dispose();
objBitmap.Dispose();

You can put it inside any event you want.

4.Clear All The Textbox Values (Reset Function)
In Classic ASP, to clear all the textboxes in a form, to start over, we just had to use a simple html 'Reset' button in the form. Sometimes that works in ASP.Net;sometimes it doesn't.

Here are a couple of ways to do this, iterating through the ASP.Net TextBox controls in a form --
Just create a Reset type subroutine - in that routine, use the following code:
in C# - it would be:

Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
((TextBox)ctl).Text = "";

This will clear EVERYTHING from the textboxes - even if you had them pre-populated with data. A VERY simple way to just reset it to the condition at Page_Load time, just do this in the Reset SubRoutine:

Server.Transfer("YourPageName.aspx")

5.Pressing Enter key
Sometimes, you will notice, that, in an ASP.Net form, depending on the circumstances, pressing the 'Enter' key to submit the form does not work.

To force this to happen for a particular button on your page, just put this in the Page_Load routine:

Page.RegisterHiddenField("__EVENTTARGET", "button1")

Then, change 'button1' to the ID of your particular button. Understand, of course, if your cursor is inside of a MultiLine textbox, the default action of the enter key is to create a new line in the textbox, so, if this basically works anywhere outside of that scenario.

6.ASP.Net Server Controls Not Showing on pages
It's possible that ASP.Net is not registered correctly on your system.Try running aspnet_regiis from the command prompt.

Here's the default location:

C:\WINNT\Microsoft.NET\Framework\<>\aspnet_regiis.exe -i

Windows Server 2003, you must use aspnet_regiis -i -enable. This is because of the "Web Service Extensions" feature in IIS 6

7.Where To Store Database Connection
Let's say you have a database connection (or several) that you will be using over and over. Yes, you can manually copy/type it in on every ASP.Net page - BUT - an easier way is to store it in the Web.Config file (formerly config.web) and then refer to it in the code.

In Web.Config, you would add a key to the AppSettings Section:





for OleDb - use Absolute Path - Not Server.MapPath:


Then, in your ASP.Net application - just refer to it like this:

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings("MyDBConnection"));

Wednesday, July 1, 2009

Generate LDF file from MDF file in sqlserver

Last would be undocumented command DBCC REBUILD_LOG but I am not sure it will work in 2005...

1. Rename existing .mdf file to .mdf_old
2. Create a new database with same .mdf and .ldf file as old one.
3. Stop the sql server
4. Rename .mdf and .ldf files of the new db to .mdf_old and .ldf_old
5. Rename .mdf_old to .mdf
6. Start sql server
7. You should see db in suspect mode.
and then follow the following instructions...
Note: you can't update system tables in 2005 so you can use alter database command to change to db emergency mode...

8. Change the database context to Master and allow updates to system
tables:

Use Master
Go
sp_configure 'allow updates', 1
reconfigure with override
Go

9. Set the database in Emergency (bypass recovery) mode:

-- note the value of the status column for later use
select * from sysdatabases where name = ''
begin tran
update sysdatabases set status = 32768 where name = ''
-- Verify one row is updated before committing
commit tran

If you run DBCC REBUILD_LOG without setting the database in Emergency
mode, the command does not work. You do not receive an error, but the
log is not rebuilt either.

10. Stop and restart SQL server.

If you run DBCC REBUILD_LOG without recycling the server, the following
message displays:

Server: Msg 5023, Level 16, State 2, Line 1 Database must be put in
bypass recovery mode to rebuild the log. DBCC execution completed. If
DBCC printed error messages, contact your system administrator.

11. The syntax for DBCC REBUILD_LOG is as follows:

DBCC REBUILD_LOG('','')

where is the name of the database and is the
physical path to the new log file, not a logical file name. If you do
not specify the full path, the new log is created in the Windows NT
system root directory (by default, this is the Winnt\System32
directory).

12. Rebuild the log with this code:

DBCC TRACEON (3604)
DBCC REBUILD_LOG('','')
Go

If the command is successful, the following message appears:

Warning: The log for database '' has been rebuilt.
Transactional consistency has been lost. DBCC CHECKDB should be run to
validate physical consistency. Database options will have to be reset,
and extra log files may need to be deleted.

After the log is successfully rebuilt, the database is placed in DBO Use
Only mode. That is, the status of the database is 2048 irrespective of
what the status was previously. You must reset the status using
sp_dboption or through the SEM.

13. Set the database in single-user mode and run DBCC CHECKDB to validate
physical consistency:

sp_dboption '', 'single user', 'true'
DBCC CHECKDB('')
Go
begin tran
update sysdatabases set status = where name =
''
-- verify one row is updated before committing
commit tran
Go

14. Turn off the updates to system tables by using:

sp_configure 'allow updates', 0
reconfigure with override
Go

WARNING: After verifying the consistency of the database by running DBCC
CHECKDB, and fixing any errors, please make sure to check the database
for logical consistency as well. Because a new log has been built, the
transactions in the
old log are lost, hence you must also verify the logical consistency of
the data as well.