Adsence750x90

Sunday, September 20, 2009

DataTable to CSV or Text File in Download format

Download Reports in CSV or Text Fromat in C# ( C Sharp)

Some special situations programmers want to download user reports in .csv or .txt format from database. This code snippet is a solution for that situations. first to take data from database in DataTable. Below class file is helpful to overcome this problam

first Example this wrote in a separate class file.

use system.io;


public class DownloadReports
{
public DownloadReports()
{
}

public void TextFormat(DataTable objData,string filename)
{
MemoryStream mm = getStream(objData);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.txt;", filename));
HttpContext.Current.Response.BinaryWrite(mm.ToArray());
HttpContext.Current.Response.End();
}

public void ExcelFormat(DataTable objData, string filename)
{
MemoryStream mm = getStream(objData);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/Ms-Excel";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv;", filename));
HttpContext.Current.Response.BinaryWrite(mm.ToArray());
HttpContext.Current.Response.End();
}

private System.IO.MemoryStream getStream(DataTable objData)
{
System.IO.MemoryStream mm = new MemoryStream();
if (objData.Rows.Count > 0)
{
StreamWriter sw = new StreamWriter(mm);
sw.AutoFlush = true;
sw.WriteLine(); sw.WriteLine();
foreach (DataColumn dcols in objData.Columns)
{
sw.Write(dcols.ColumnName.ToString() + ",");
}
sw.WriteLine();
sw.WriteLine();
foreach (DataRow drow in objData.Rows)
{
for (int i = 0; i < objData.Columns.Count; i++)
{
sw.Write(drow[i].ToString() + ",");
}
sw.WriteLine();
}
}
return mm;
}
}


2nd option wrote in ASPX.CS file


public class DataTableToCsvAndTxtFormat
{
public DataTableToCsvAndTxtFormat()
{
}
private MemoryStream GetStream()
{
DataTable objData = new DataTable();
MemoryStream mm = new MemoryStream();
DBHelper objDBHelper=new DBHelper ();
string cmd = string.Format("SELECT Column1,Column2,Column3,Column4 FROM Table");
objData = objDBHelper.GetReaderTable(cmd);
if (objData.Rows.Count > 0)
{
objData.Columns[0].ColumnName = "First Name";
objData.Columns[1].ColumnName = "Last Name";
objData.Columns[2].ColumnName = "Email";
objData.Columns[3].ColumnName = "Mobile Number";

StreamWriter sw = new StreamWriter(mm);
sw.AutoFlush = true;
sw.WriteLine(); sw.WriteLine();
foreach (DataColumn dcols in objData.Columns)
{
sw.Write(dcols.ColumnName.ToString() + ",");
}
sw.WriteLine();
sw.WriteLine();
foreach (DataRow drow in objData.Rows)
{
for (int i = 0; i < objData.Columns.Count; i++)
{
sw.Write(drow[i].ToString() + ",");
}
sw.WriteLine();
}
}
}
public void DownloadTextFormat()
{
MemoryStream mm = GetStream();
Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "attachment; filename=Reports.txt;");
Response.BinaryWrite(mm.ToArray());
Response.End();
}
public void DownloadCsvFromat()
{
MemoryStream mm = GetStream();
Response.Clear();
Response.ContentType = "application/Ms-Excel";
Response.AddHeader("content-disposition", "attachment; filename=Reports.csv;");
Response.BinaryWrite(mm.ToArray());
Response.End();
}
}

Wednesday, September 2, 2009

General page life Cycle Stages in ASP.NET

General page life Cycle Stages in ASP.NET
1: Page Request
2: Start
3: Page Initializations
4: Load
5: Validation
6: Postback event handling
7: Rendering
8: Unload

1: Page Request:

The Page Request occurs before the page life cycle start. When a page is requested by a user ASP.NET determine some common things
1: whether the page need to be parsed and compiled
2: whether a cached version of the page can be sent in response without running the current page

2: Start

In start, page properties like request and response are set. In this stage the page also determine whether the request is a Postback or new request and set IsPostBack Property.

3: Page Initializations

During page initialization, controls on page are available and each control set its uniqueid property is set and themes. ie control raise their Init ViewState is set in this stage.

4: Load

On load if the current request is Postback control property are loaded with information recoved from viewstate and control state


Control state: Control state, introduced in ASP.NET version 2.0, is similar to view state but functionally independent of view state. A page developer can disable view state for the page or for an individual control for performance. However, control state cannot be disabled. Control state is designed for storing a control's essential data (such as a pager control's page number) that must be available on postback to enable the control to function even when view state has been disabled. By default, the ASP.NET page framework stores control state in the page in the same hidden element in which it stores view state. Even if view state is disabled, or when state is managed using Session, control state travels to the client and back to the server in the page. On postback, ASP.NET deserializes the contents of the hidden element and loads control state into each control that is registered for control state.
Note:
Use control state only for small amounts of critical data that are essential for the control across postbacks. Do not use control state as an alternative to view state.


Control state FROM MSDN


5: Validation

Validate method of all validator control is called, which set the IsValid property of individual validator controls in the requested page.

6: Postback event handling

If the request is a Postback any events handlers are called. And save viewstate

7: Rendering

Before rendering viewstate is saved for the page and all control.during the rendering phase the page calls the Render method for each control.

8: Unload

Unload call after the page has been fully rendered,sent to the client and is ready to be discarded.

Monday, August 24, 2009

Create Error Log in ASP.NET - Exception handling

How to log your errors in asp.net C#

There are many methods to log errors for example send errors via mail or keep in text file. This is an example to how to log errors in text file.

Class file to save Exception.

In this class there is one function ErrorLog parameter of error log is Exception
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public class LogError
{
public LogError()
{
public static void ErrorLog(Exception er)
{
try
{
string path = HttpContext.Current.Server.MapPath("errorlog.txt");
if (!System.IO.File.Exists(path))
{
using (System.IO.StreamWriter sw = System.IO.File.CreateText(path))
{
sw.WriteLine("Error :" + DateTime.Now.ToString());
sw.WriteLine(er.Source + er.Message + er.StackTrace);
sw.WriteLine("******************************************************");
}
}
else
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
{
sw.WriteLine("Error :" + DateTime.Now.ToString());
sw.WriteLine(er.Source + er.Message + er.StackTrace);
sw.WriteLine("******************************************************");
}
}
}
catch
{
}
}
}

Wednesday, August 12, 2009

d3dx9_34.dll was not found - Installation Error

This is a common error when we installing some software like games in Windows XP / Vista.
we can fix this bug by installing DirectX.

You can download DirectX 10 click here
Alternate Link

Saturday, August 1, 2009

How to Strip (Remove) HTML tag from a String Using ASP.NET C# - using regular expression

How to Strip (Remove) HTML tag from a String Using ASP.NET C#

Using regular Expressions we can strip HTML Contents from a string. System.Text.RegularExpressions namespace conatin regular expressions in asp.net.
Replaces all occurrences of a pattern defined by a specified regular expressionwith a specified replacement character string, starting at the first character in the input string. Options can be specified to modify matching behavior.

Syntax

1: Regex.Replace(string input, string pattern, string replacement);
2: Regex.Replace(string input, string replacement, int count, int startat);
3: Regex.Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options);

Example

string pattern = @"<(.|\n)*?>";
string withOutHtml=Regex.Replace("html content",pattern,string.Empty,RegexOptions options);

Friday, May 22, 2009

Partial Classes in C#.Net - examples usage definition

Definition :Partial types are allow to define a single class in multiple files (more than one file), when compilation time theses classes are combined to form a single class.

The partial modifier is not available on delegate or enumeration declarations.

Example
//partial class


public partial class Student

{
public virtual void GetRollNo();
}

public partial class Student
{
public virtual void GetStudentName();
}

//Derived class

public class School : Student
{
public void getStudentDetails()
{
GetRollNo();
getStudentDetails();
}
}

Monday, May 18, 2009

What is an Interface? CSharp tutorials and sample code

What is an Interface?
Interface is defined as set of methods properties evnets and fields.
The scope of an inetrface is public.interface contain only signature.(it contain only definition no implementation)
Implementation are done in derived class.Only the interface can support multiple inheritance in C#.



//Example of Interface
interface ITestInterface
{
void TestMethod();
//Declaring Properties in interface
int Count
{
get;
set;
}
//Read only Property
string Item
{
get;
}
//Write only Property
string Name
{
set;
}

}

//interface Implementation are done in derived class.so we are going to inherit ITestInterface in a class named InterfaceImplimentation
public class InterfaceImplimentation:ITestInterface
{
public InterfaceImplimentation()
{
}

#region ITestInterface Members

public void TestMethod()
{
//Write Implimentation
}
private int y;
private string z = string.Empty;
public int Count
{
get
{
return y;
}
set
{
y = value;
}
}
public string Item
{
get
{
return "Item1";
}
}
public string Name
{
set
{
z = value;
}
}

#endregion
}


//implimentation


public class Implementation
{
InterfaceImplimentation if1 = new InterfaceImplimentation();
public void GetItem()
{
if1.TestMethod();
}
}

Thursday, March 12, 2009

How to Get Session In Handler (ashx) Files?

To Access session variable in Handler File

using System;
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Session.Add("SessionName", "SessionValue");
}

public bool IsReusable {
get {
return false;
}
}

}

Tuesday, February 17, 2009

How to Clear All Values in Page -tutorials and code snippet

How to Clear all controls values like TextBox1,DropDownList?

We can get Page controls from Page.Controls. each controls are child controls of other page element in asp.net.
protected void Button1_Click(object sender, EventArgs e)
    {
        ClearAllControlsValues(Page.Controls, 0);
    }

    private void ClearAllControlsValues(ControlCollection controls, int depth)
    {
        foreach (Control ctrl in controls)
        {
            if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                TextBox txt = (TextBox)FindControl(ctrl.ID);
                if (txt != null)
                {
                    txt.Text = string.Empty;
                }
            }
            if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
            {
                DropDownList dDownList = (DropDownList)FindControl(ctrl.ID);
                if (dDownList != null)
                {
                    dDownList.SelectedIndex = 0;
                }
            }
            if (ctrl.Controls != null)
            {
                ControlCollection(ctrl.Controls, depth + 1);
            }
        }
    }

What is ViewState Chunking in ASP.Net - Definition & Solution

What is ViewState Chunking

Size of hidden viewstate have no limit.some poxy and firewalls refuse page loads if they have hidden file have greater than certain size. to solve this problem by viewstate chunking.ViewState Chunking is automatically divide view state multiple field to ensure that no hidden field overcome max size. viewstate chunking is not a method for good performance, its only for some proxys and firewalls.
for viewState chunking u can set the maxPageStateFieldLength attribute of the <>
element in the web.config file
<>
< maxpagestatefieldlength="1024">< / pages >
< /system.web >

Sunday, February 15, 2009

Page Caching in ASP.Net - enable and disable client cache

How to Enable Page output caching in ASP.NET?

ASP.NET provides easier methods to control caching. You can use the @ OutputCache directive to control page output caching in ASP.NET. Use the HttpCachePolicy class to store arbitrary objects, such as datasets, to server memory. You can store the cache in applications such as the client browser, the proxy server, and Microsoft Internet Information Services (IIS). By using the Cache-Control HTTP Header, you can control caching.

Some datas are not requried to reload all time when clint attempting to server. we can save ouput page cache in Client side.



method 1

Take ISS (Inertner Information Service) form machine. select site then take properties then
select HTTP Headers Enable content Exparation. this Set your sites output cache properties



Method 2

we Can add Programmatic
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Declarative method
<%@ OutputCache Duration="60" VaryByParam="None" %>
Turn off Caching
Response.Cache.SetCacheability(HttpCacheability.NoCache);