Recently at work, I encountered an assignment to export DataTable objects into .xls file in C#. I conducted quite a research which revealed myself few alternatives to achieve this task.

 

Using HtmlTextWriter and StringWriter Objects

 

//make sure these two are imported

using System.IO;

using System.Text;

 

protected void ExportToExcel()

{

//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();

Response.Clear();

Response.Buffer = true;

Response.AddHeader(“content-disposition”,”attachment;filename=New.xls”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-excel”;

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

for (int i = 1; i < gvGridView.HeaderRow.Cells.Count; i++)

{

gvGridView.HeaderRow.Cells[i].Text = Table.Columns[i - 1].ColumnName;

}

for (int i = 0; i < gvGridView.Rows.Count; i++)

{

//Apply text style to each Row
gvGridView.Rows[i].Attributes.Add(“class”, “textmode”);

}
gvGridView.RenderControl(hw);

//style to format numbers to string
string style = @”<style> .textmode { mso-number-format:\@; } </style>”;
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

}

The good thing about this method is it’s very simple to be understood. What it basically does is creating an HTML table and tell our computer that it’s an .xls file. Yeah, it’s that simple. Problem is .xls file resulted from this process won’t be available to be accessed reversibly. If you would like to import back this .xls file into DataTable, you won’t be able to. Because this is basically a conned file.

 

Using XmlTextWriter Objects

 

//ensure that this is imported

using System.Xml;

 

public class ExcelHelper

{

//private static readonly ExcelHelper _instance = new ExcelHelper();
private static readonly ExcelHelper _instance = new ExcelHelper();

public static ExcelHelper Instance
{
get { return _instance; }
}

///
/// Create one Excel-XML-Document with SpreadsheetML from a DataTable
///
/// Datasource which would be exported in Excel
/// Name of exported file

public void Create(DataTable dtSource, string strFileName)
{

// Create XMLWriter
using (XmlTextWriter xtwWriter = new XmlTextWriter(strFileName, Encoding.UTF8))
{

//Format the output file for reading easier
xtwWriter.Formatting = Formatting.Indented;

//
xtwWriter.WriteStartDocument();

//
xtwWriter.WriteProcessingInstruction(“mso-application”, “progid=\”Excel.Sheet\”");

//
xtwWriter.WriteStartElement(“DocumentProperties”, “urn:schemas-microsoft-com:office:office”);

// Write document properties
xtwWriter.WriteElementString(“Author”, “Rofans Manao”);
xtwWriter.WriteElementString(“LastAuthor”, “Rofans Manao”);
xtwWriter.WriteElementString(“Created”, DateTime.Now.ToString(“u”) + “Z”);
xtwWriter.WriteElementString(“Company”, “Siemens Malaysia Sdn Bhd”);
xtwWriter.WriteElementString(“Version”, “12″);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteStartElement(“ExcelWorkbook”, “urn:schemas-microsoft-com:office:excel”);

// Write settings of workbook
xtwWriter.WriteElementString(“WindowHeight”, “8010″);
xtwWriter.WriteElementString(“WindowWidth”, “14805″);
xtwWriter.WriteElementString(“WindowTopX”, “240″);
xtwWriter.WriteElementString(“WindowTopY”, “105″);
xtwWriter.WriteElementString(“ProtectStructure”, “False”);
xtwWriter.WriteElementString(“ProtectWindows”, “False”);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteStartElement(“Styles”);

//
xtwWriter.WriteStartElement(“Style”);
xtwWriter.WriteAttributeString(“ss”, “ID”, null, “Default”);
xtwWriter.WriteAttributeString(“ss”, “Name”, null, “Normal”);

//
xtwWriter.WriteStartElement(“Alignment”);
xtwWriter.WriteAttributeString(“ss”, “Vertical”, null, “Bottom”);
xtwWriter.WriteEndElement();

// Write null on the other properties
xtwWriter.WriteElementString(“Borders”, null);
xtwWriter.WriteElementString(“Font”, null);
xtwWriter.WriteElementString(“Interior”, null);
xtwWriter.WriteElementString(“NumberFormat”, null);
xtwWriter.WriteElementString(“Protection”, null);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteStartElement(“Style”);
xtwWriter.WriteAttributeString(“ss”, “ID”, null, “s16″);
xtwWriter.WriteStartElement(“Font”);
xtwWriter.WriteAttributeString(“ss”, “Bold”, null, “1″);
xtwWriter.WriteAttributeString(“ss”, “Size”, null, “11″);
xtwWriter.WriteAttributeString(“ss”, “Underline”, null, “Single”);
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteStartElement(“Worksheet”);
xtwWriter.WriteAttributeString(“ss”, “Name”, null, dtSource.TableName);

//
xtwWriter.WriteStartElement(“Table”);
xtwWriter.WriteAttributeString(“ss”, “ExpandedColumnCount”, null, dtSource.Columns.Count.ToString());
xtwWriter.WriteAttributeString(“ss”, “ExpandedRowCount”, null, (dtSource.Rows.Count + 1).ToString());
xtwWriter.WriteAttributeString(“x”, “FullColumns”, null, “1″);
xtwWriter.WriteAttributeString(“x”, “FullRows”, null, “1″);
//xtwWriter.WriteAttributeString(“ss”, “DefaultColumnWidth”, null, “60″);

// Run through all rows of data source

//
xtwWriter.WriteStartElement(“Row”);

foreach (DataColumn Header in dtSource.Columns)

{

//
xtwWriter.WriteStartElement(“Cell”);
xtwWriter.WriteAttributeString(“ss”, “StyleID”, null, “s16″);

// xxx
xtwWriter.WriteStartElement(“Data”);
xtwWriter.WriteAttributeString(“ss”, “Type”, null, “String”);
// Write content of cell
xtwWriter.WriteValue(Header.ColumnName);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

}

xtwWriter.WriteEndElement();

foreach (DataRow row in dtSource.Rows)

{

//
xtwWriter.WriteStartElement(“Row”);

// Run through all cell of current rows

foreach (object cellValue in row.ItemArray)

{

//
xtwWriter.WriteStartElement(“Cell”);
//if (cnt == 0)
// xtwWriter.WriteAttributeString(“ss”, “StyleID”, null, “s16″);

// xxx
xtwWriter.WriteStartElement(“Data”);
xtwWriter.WriteAttributeString(“ss”, “Type”, null, “String”);
// Write content of cell
string strcellValue = (cellValue == System.DBNull.Value ? string.Empty : (string)cellValue);
xtwWriter.WriteValue(strcellValue);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

}

//
xtwWriter.WriteEndElement();

}

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteStartElement(“WorksheetOptions”, “urn:schemas-microsoft-com:office:excel”);

// Write settings of page
xtwWriter.WriteStartElement(“PageSetup”);
xtwWriter.WriteStartElement(“Header”);
xtwWriter.WriteAttributeString(“x”, “Margin”, null, “0.4921259845″);
xtwWriter.WriteEndElement();
xtwWriter.WriteStartElement(“Footer”);
xtwWriter.WriteAttributeString(“x”, “Margin”, null, “0.4921259845″);
xtwWriter.WriteEndElement();
xtwWriter.WriteStartElement(“PageMargins”);
xtwWriter.WriteAttributeString(“x”, “Bottom”, null, “0.984251969″);
xtwWriter.WriteAttributeString(“x”, “Left”, null, “0.78740157499999996″);
xtwWriter.WriteAttributeString(“x”, “Right”, null, “0.78740157499999996″);
xtwWriter.WriteAttributeString(“x”, “Top”, null, “0.984251969″);
xtwWriter.WriteEndElement();
xtwWriter.WriteEndElement();

//
xtwWriter.WriteElementString(“Selected”, null);

//
xtwWriter.WriteStartElement(“Panes”);

//
xtwWriter.WriteStartElement(“Pane”);

// Write settings of active field
xtwWriter.WriteElementString(“Number”, “1″);
xtwWriter.WriteElementString(“ActiveRow”, “1″);
xtwWriter.WriteElementString(“ActiveCol”, “1″);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

// False
xtwWriter.WriteElementString(“ProtectObjects”, “False”);

// False
xtwWriter.WriteElementString(“ProtectScenarios”, “False”);

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

//
xtwWriter.WriteEndElement();

// Write file on hard disk
xtwWriter.Flush();
xtwWriter.Close();

}

}

}

To use: ExcelHelper.Instance.Create(DataTable,strFileName). This method is perfect. Only one problem it’s caused. It doesn’t use objects instantiated from any System.IO classes. So when you execute this method, there is no popup asking you where to save downloaded .xls file as the first method produced. What it will do (this really scares me) it will write straight away your .xls file in the directory you defined. Off course in normal environment this will result in no problem. But imagine the situation where you don’t have admin rights or you have to store your files in mainframe/server. You basically get my point right?

 

Using Interop Objects

 

//Make sure you add this reference and have it imported

Using Excel = Microsoft.Office.Interop.Excel;

 

protected void xlsWorkBook()
{

Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;

// Start Excel and get Application object.
oXL = new Excel.Application();

// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;

// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);

// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = “Customers”;

// Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
//DataTable dt = Customers.RetrieveAsDataTable();//commented

DataTable dt = Table;//added
Session["dt"] = dt;//added

int rowCount = 1;

foreach (DataRow dr in dt.Rows)

{

rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)

{

// Add the header the first time through
if (rowCount == 2)

{

oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;

}

oSheet.Cells[rowCount, i] = dr[i - 1].ToString();

}

}

// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();

// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(“test.xls”, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();

// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

}

This method is good enough. So far, I found no problem. There is potential memory leak if you process giant files, but so far I haven’t found any.

Well I hope these helps. Let me know if you find any problems with this code.

 

Dear Sir,

I penned down this article as soon as I finished reading an article about you here.

I previously heard about your plan to implement that TOEFL policy when a few of my friends bashed it out in Facebook. Their main premise was “even to win a scholarship in US, we only need to score 550″.

I didn’t do a double check on my friends’ premise. There was no point doing it anyway, as I believe taking GRE/SAT exam will be more helpful in that case. In fact, I almost forgot about this issue. It was until I read that particular article I mentioned above, this issue caught my attention again.

I have to say that I was very impressed reading your opinions. Most of Indonesians nowadays realize on the importance of Professional English Communication. But I barely see any effort from anybody (private or government entity) to actually realize that importance.

Allow me to tell you two experiences I encountered that sliced my heart up until today.

The first was during a PPIM (Persatuan Pelajar Indonesia Malaysia) congress on 2010. There was this officer from Indonesian Embassy. I forgot his name and his post. But he must be related into student affairs thus he attended the convention. This officer has come to my university previously where I met him face to face. I was with few of my university officials on that time, so I kinda have to speak English all the time to him (I must!). As I remembered, it was basically a one way communication. I spoke most of the time in purpose of explaining the situation of Indonesian students in my university to that officer. Once or twice my university officials would stop me to elaborate more on certain details. In fact, I got corrected several times, haha. Well, in that PPIM program I met him again, few months after the first encounter. As most of the students there, I waited to greet him after the event concluded (basically everybody wanted to shake his hand). That officer somehow remembered me. And it was that time I could clearly listen to his English. It was him whom voluntarily communicate in English at the first place. I was really shocked as I noticed that there was no significance on this officer’s English skills. I believed real diplomats should be able to perform more. He was very enthusiast to speak English to me. I figured he doesn’t get a lot of chance to do so elsewhere. This is diplomat we are talking about.

That was the first. The second happened last year. When I met and Indonesian lecturer (with a doctorate) who conducted Post Doctorate research in my university. There was nothing special this time, it was basically two Indonesians who were exchanging thoughts to each other. As I am merely a ‘pemuda tanggung’ compared to this doctor, I simply listened to him more as I expect to gain more knowledge. I believe he was a credible person, therefore I hoped him to tell me bits and pieces about his research. It turned out differently somehow as he began complaining of the communication skills of lecturers in our beloved country. He said that our lecturers are not as good as Malaysians’. And he expressed how he regret this as being a threatful inhibitor to our education system. Needless to say, I was made speechless of this.

These two events while short and sporadic revealed the same problem our country facing: We are not good English communicator!

Therefore, I really support any effort made to resolve this issue. Our country is in the process of becoming a big nation and without English we will be victimized by the cruelty of our cunning neighbors.

I don’t know about any other industry. But I am an IT student in Malaysia with high interest in IT industry in Malaysia, so I do know this (they are related to English somehow, trust me):

1. IBM insisted to build HQ in Malaysia
2. Intel build a plant in Malaysia
3. RIM who doesn’t have any market in Malaysia build plant in Malaysia

Some more (not related to IT):

1. Biggest listed palm oil companies are not from Indonesia yet they have farms in Indonesia
2. Schlumberger sends people to Malaysia for training while in contrary here they have a lot of competition, their operation in Indonesia is bigger some more.
3. Temasek plants their money everywhere while they have no solid business. All they do is making investor come to invest their money somewhere else. It’s like investor come to Temasek then Temasek come to Indonesia.

Why these things keep happening?

Therefore Sir, as someone who has lost faith in other leaders I really put a high hope and expectation in you. You have determined the first step to revive our country.

All I hope for now is to join your team one day (If God allows us, Amen).

Good day and Good luck achieving your targets!

————————————

Rofans Beleam Hilisebua Manao

I am taking a shot, sue me!

Ever since I discovered how informative newspapers and magazines are, I have been regularly updating myself with latest news whenever possible. The first magazine I regularly read was the Bobo magazine. It was basically a kids magazine focusing on students ranging from primary school to teenagers. Just like every other magazine I remembered growing up, Bobo also has expiration date. I found it later no more fun to read and I turned to read Tabloid Bola instead. Tabloid Bola consists more news on sports especially football. I spent good years reading it over and over until I become sufficiently proficient to talk about football now. Now I don’t feel I need to read it anymore. Sport news are very informative but they are barely educational.

I started reading on politics and economics after I move to Jakarta 4 years ago. Special rates for students for top newspapers and magazines was the main catalyst (something I can’t see in Malaysia). Routine students discussions and forums were also supportive in pumping up my awareness. I noticed good thing from this process that happened to me. It was me myself who chose to self-aware in the first place. Therefore I automatically set my mindset to be strongly critical in responding issues. But because of my hot head nature, I couldn’t maximize the potential of absorbing knowledge. I realize now that I can spend better time to exercise my mind than arguing with a lot of self abused people who barely understand the meaning of democracy.

My interest in politics took a break for a moment after I moved to UTP. And I somehow invoked it recently. Politics is not all about observation, to be effective it must include participation.

It took me some time but at this point I finally know where I should stand. I know very well I haven’t been aware about Indonesian politics lately, but I have gained myself enough knowledge about Malaysian politics instead.

I remembered my first year in this country. I really spent a lot of time admiring how its leaders have done a very good job. But who are we kidding right? Nothing is perfect! So I simply decided to move on being critical and soon enough I understand how things going on in this country. But I don’t want to talk about it now. I pro some I anti some but what I really hope is the best for Malaysia only. After all, I owe this country a lot and I hope I can pay my respect and budi one day.

My main point here is actually is that I just want to show how I pity Malaysians really. I mean they have serious problems exercising democracy. Off course not all of them, but most of them especially the youth are! Gosh. I dare you to talk to Malaysians youth about democracy! It will feel like talking to a chimpanzee! I realized now why so many talents of this country decided to exile themselves voluntarily. It was like talking to Indonesians during the Suharto’s regime. Below is my effort to list out what triggered this thought of mine:

  1. Serious disbelieve in judiciary system
  2. Impossibility to stand in the middle in politics. If you are not with us, you are against us.
  3. Ability to tolerate corruption and to in-tolerate sex issues.
  4. Prejudice above race, religion, and economical status
  5. Media. Need I say more?

Frankly speaking, a country like this should have collapsed long time ago. But due to the economic success that is unlikely to happen. Yet this level is not good enough for Malaysia. What Malaysians truly need is fair and democratic government, clean media, and sustainable economic growth.

I somehow see Najib as a different leader than others. He has true potential in effort and hard-work. He must do something to save this country before it’s too late. Not for his party, not for his post, but for the future of Malaysia.

Three new year celebrations, yet I am just all by myself.

After I moved to KL, there have been three new year celebrations took place. The first happened last November. It was the celebration of 1st Muharram which marked the beginning of the Islamic calendar year. The second was the Gregorian New Year on 31st December which I believe is celebrated by most of us. And the last but not least occured today in conjunction with the Chinese New Year celebration. I only celebrated the second one. But, I like the third one somehow due to the fact that it gives me more holidays than the others.

Noteworthy enough, I also have another new year celebration. This one is solely personal event (if not celebration cause there’s no party basically). It took place on 1st February every year. For some reasons the upcoming 2012 edition will be the first to be celebrated. Why Feb 1st? It goes back way on 2009. That day on that year, I stepped my foot for the first time in Bolehland Malaysia. It was quite a hazy memory. I chosed not to remember most of what happened back then. Probably because I was such a jerk that time. I was so jerky until I myself hate that version of me. But enough about that now. I have transformed. In fact last year (2011) I transformed above my own expectation. So to celebrate this transformation I somehow plan to treat myself on this 1st February this year specially.

3 years ago as I want to remember, I was really a different person. I never shaved my moustache. I seldom did my hair. I eat uncontrollably. But the most embarassing thing is that I was really an emo person. I mean I could be angry for no reason. I was probably angry to myself, but I poured the emotion out to my peers. This has pushed my peers to resent me, something I may deserved.

Anyway, I somehow over it now. How? I also can’t answer As far as I know, I did receive good encouragement from family and friends. But it wasn’t them or their efforts that helped me. I didn’t have a girlfriend who are willing to share my pain and sorrow. I was not religious, in fact in some point I behaved like an atheist. So what is exactly happening to me? Transformation always happens for a cause. In my case, it’s simply a natural one. Au naturel. It happened because of no reasons and to serve no purporses. This has lead me to have this thought: Everyone no matter how lame they are MUST TRANSFORM! 2nd chance is actually a birth right and mandatory.

However, I also discovered that to some point natural process is not enough. Sooner or later it will stop by itself and it will only continue to grow if it has been give a catalyst. The catalyst in people’s life could have been anything. A supernatural faith, a special someone, a hobby, or even a political event. I have checked on the possibility of every options that I listed just now and it’s looking pretty promising. In fact, I have been i a very good shape of my faith since years (thank’s to my family in GTPJ).

Actually. my transformation that I have been bragging not actually ending yet. I just can’t wait the natural process to stop. I know that as early as I could I must find it and thank’s to my Lord Jesus Christ I am currently on the right direction..

The typical web form consists of controls (like labels, buttons, and data grids), and programming logic. In ASP.NET 2.0, there are two approaches to managing these control and code pieces: the single-file page model and the code-behind page model. Regardless of which model you choose, it’s important to understand how the runtime is processing and executing your web forms behind the scenes. In this article, we will examine how web forms move from design time to run-time in ASP.NET 2.0.

The Code-Behind Model

Visual Studio creates a web form using the code-behind model when you add a new web form to a project and check the “Place code in separate file” checkbox in the Add New Item dialog. Visual Studio will add two files to the project: an aspx file and a .cs or .vb file. If we were creating a Default.aspx web page, the aspx file would look like the following.

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head runat=”server”>

<title>Untitled Page</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div> </div>

</form>

</body>

</html>

The ASPX page contains the typical markup for a form, including the html, head, and body tags. Any controls we add to the form using the designer will appear inside the ASPX file also. The three key pieces for us to focus on are in the @ Page directive on top. The AutoEventWireup attribute defaults to true, and we will return to this attribute later in the article. The CodeFile attribute is the link to the source code file with the programming logic for this web form, in this case the file is Default.aspx.cs. The runtime will use the CodeFile attribute to determine which source code file it needs to compile for this ASPX page. Likewise, the Inherits attribute tells the runtime the name of the class it will use as a base class for this web form, and again we will see how this works shortly when we see the entire picture. For now, let’s look at the CodeFile (code-behind) file for the ASPX page.

using System;

using System.Web.UI;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e) {}

}

Here we find the _Default class (which we saw in the Inherits attribute) and our standard Page_Load event handler which (note: some non-essential using directives have been removed from the listing to conserve space). We typically use the Page_Load even handler to initialize controls and perform data binding. Currently, in VB.NET, the default .vb file will not contain the Page_Load event handler, but you can easily add the event handler using the page event drop down list just above the text editor. In either language, the key to focus on is the ‘partial’ keyword.

The partial keyword (new in .NET 2.0) is one of the rare keywords that is present in both C# and VB.NET and carries the same meaning (shocker!). Partial allows us to split a class definition across two or more source code files. In previous version of the .NET framework this was impossible to achieve – a class definition had to exist inside of a single .cs or .vb file.

The partial keyword plays an important role because it will allow the runtime to extend the definition of our _Default class with additional members. For instance, any control appearing in the ASPX markup with runat=”server” and an id attribute will ultimately act like a member variable in our class. For example, in the Page_Load event handler we can already access a variable named form1 – form1 represents the HTML form tag in the ASPX, which does have runat=”server” specified. How does all the magic happen? Let’s take a look at what happens when we browse to the web application to execute the form.

Compilation In The Code-Behind Model

When an incoming browser request arrives for our web form, the ASP.NET runtime needs to accomplish two tasks. First, the runtime needs to parse and understand the controls we’ve placed in the ASPX file. Parsing involves reading the ASPX portion of the form, and generating source code to create those controls and HTML markup. The second job is then to compile the generated source code. You can actually see the code the runtime generates by poking around in the ‘Temporary ASP.NET Files’ directory, which will reside underneath the framework installation in the \Microsoft.NET\Framework\v2.0.50215\Temporary ASP.NET Files. The following is an excerpt of the file generated by parsing the ASPX at the top of this article. Although a good portion of the actual code is omitted from this example, the snippet will give us a good idea of how the runtime is putting pieces together underneath the covers.

public partial class _Default : System.Web.SessionState.IRequiresSessionState
{

protected System.Web.UI.HtmlControls.HtmlForm form1;

protected System.Web.Profile.DefaultProfile Profile
{

get

{
return ((System.Web.Profile.DefaultProfile)(this.Context.Profile));
}

}

protected System.Web.HttpApplication ApplicationInstance

{

get

{

return ((System.Web.HttpApplication)(this.Context.ApplicationInstance));
}

}

}

namespace ASP

{

public class Default_aspx : _Default
{

public Default_aspx()
{
// …
}

protected override void FrameworkInitialize()
{

base.FrameworkInitialize();
this.__BuildControlTree(this);
this.AddWrappedFileDependencies(ASP.Default_aspx.__fileDependencies);
this.Request.ValidateInput();

}

// …
}

}

The first piece to notice is the partial class definition at the top of the generated code. This partial class will complete the _Default class definition from our Default.aspx.cs code behind file by adding some additional members. One of these members is a field to represent the HTML form tag on the page (again, because it has a runat=”server” tag). Any other server controls we would place on the form would also become members of the class.

The second class (Default_aspx) in this generated file represents the ASPX page itself. This class inherits the _Default class and contains all the code needed to initialize the form, instantiate the server controls, and spit out literal HTML.

The runtime will compile both of these classes (_Default and _Default_aspx) into the same assembly. This assembly will be located in the temporary ASP.NET files directory.

Read more: http://odetocode.com/Articles/406.aspx

By Mani Raja

Even though ASP.NET is the next version of ASP, it is more than just a next version. ASP.NET is completely re-designed from the ground up and it provides a neat object oriented programming model. An ASP.NET page is an object derived from the .NET Page class. We all know that ASP.NET provides several new features and one of the important features is the separation of code and content.

In today’s ASP application, we have a mix of HTML and Scripts making the code difficult to read, debug and maintain. ASP.NET relieves us from this problem by promoting the separation of code and content. That is, the user interface and the user interface programming logic need not necessarily be written in a single page. There are two ways in which you can separate the code and content:

1.) By using Code-behind files that are pre-compiled modules written in any of the Microsoft .NET runtime compliant languages.
2.) By developing the frequently used page logic in to separate files called Pagelets (also known as page controls) and by using them several times in your ASP.NET pages.

As the title of the article indicates, I will explain the first mechanism that is used to neatly encapsulate the UI functionality in to a separate pre-compiled module. You will typically follow the steps below to develop an ASP.NET page that uses code-behind pages:

1.) Create the User Interface using the HTML and/or Web controls and store them in an ASP.NET page with extension “.aspx”.
2.) Create the code-behind file using the .NET runtime classes that mimic the entire ASP.NET page with the member variables that correspond to the HTML and/or Web controls used in the ASP.NET page. The extension of code behind files will vary depending on the language you use. Typical extensions will be .cs for C#, .vb for VB7 and .js for JScript .NET

Now, we know that there are two separate files: one for the UI and the other for the UI logic. But, how do we relate these two files so that the ASP.NET page compiler will locate the code-behind file for the ASP.NET page. The glue between these two files is provided through the Page Directives, which are used to specify optional settings at the page level.

Creating the “Content”
Enough theory said about code-behind files. Let us get our hands on to the actual coding of a code-behind file. The ASP.NET page that displays the Web UI can be seen below. It uses a post-back form to query the user for username and information:

<%@ Page language=”c#” Codebehind=”CodeBehind.cs” Inherits=”ASPPlus.CodeBehind” %>

<HTML>

<BODY>

<form action=”CodeBehind.aspx” method=post runat=”server

<p align=center>Demonstration of Code Behind File</P>

<p align=center><asp:Label id=Message runat=”server”></asp:Label></P>

<p>

<h5>Sign-In Form</h5>

Login: <asp:TextBox id=txtLogin Width=200 Runat=server />

<asp:RequiredFieldValidator ControlToValidate=”txtLogic”

Display=”Static” Font-Name=”verdana,arial,sans-serif”

Font-Size=”9pt” ErrorMessage=”You must enter a Login.”

runat=”server” ID=”RFVLogin” />

<P>

Password: <asp:TextBox id=txtPassword Width=200 Runat=server

TextMode=”Password” />

<asp:RequiredFieldValidator ControlToValidate=”txtPassword”

Display=”Static” Font-Name=”verdana,arial,sans-serif”

Font-Size=”9pt” ErrorMessage=”You must enter a password.”

runat=server ID=”RFVPassword”> </asp:RequiredFieldValidator>

<P>

<asp:Button id=btnSignIn Runat=”server”

Text=”Sign In” onClick=”btnSignIn_Click” />

</FORM>

</body>

</html>

The first line of the ASP.NET page is the page directive that specifies the name of the code behind file and the actual class name inside that file. In our example, the file name is CodeBehind.cs and the class name is ASPPlus.CodeBehind.

<%@ Page language=”c#” Codebehind=”CodeBehind.cs” Inherits=”ASPPlus.CodeBehind” %>

The namespace that I used for this code behind page is ASPPlus. Namespaces provide the naming scope for the classes and is very convenient way to represent hierarchy of classes. The rest of the code consists of HTML tags and Web Control declaration tags. The main thing to note down in this page is the ID properties of the controls. I will explain the importance of these IDs when we discuss the code-behind file.

Read more: http://www.4guysfromrolla.com/webtech/100500-1.2.shtml 

by John Peterson

taken from CodeGuru

Introduction

Last time around we installed all the prerequisites and finally even ASP.NET. Now that that’s done, you can start writing ASP.NET pages of your very own. This time around, we walk you through your first one.

Hello World

Way back when programming was new, someone decided that the first thing you should do whenever you start programming in a new environment or language is print out “Hello World.” I have no idea who it was that came up with this idea or why it stuck, but it has. Not being one to fight the system without reason, we’ll be using this incredibly simple idea as the basis for our first ASP.NET page.

Hello World in HTML

For your reference, I’m going to start with a sample of what we’re trying to accomplish done completely in static HTML:

helloworld.html
<html>

<head>

<title>ASP.NET Hello World</title>

</head>

<body bgcolor=”#FFFFFF”>

<p>Hello World!</p>

Ok so that’s the goal… now let’s try it in ASP.NET.
Hello World in ASP.NET
The Easy Way – Cheating!

Fundamentally, there’s no requirement that an ASP.NET page (sometimes referred to as a Web Form) actually do any processing. As such, the simplest way to get the task at hand accomplished is to take the existing HTML page listed above and simply give it an aspx extension. This results in a perfectly legal and acceptable ASP.NET page. The only thing that happens when you do this is that you tell the web server to pass the aspx file through the ASP.NET runtime, which in turn compiles it and processes any code it finds (in this case none) before it returns the result to the client.
Note: I’ll be highlighting changes from the previous version of the code in red for emphasis and quickly mentioning them after each new listing.

helloworld.aspx
<html>

<head>

<title>ASP.NET Hello World</title>

</head>

<body bgcolor=”#FFFFFF”>

<p>Hello World!</p>

The only thing that changed here is the filename. If the ASP.NET runtime doesn’t find any code it understands, it just leaves everything alone and passes it out to the browser.

While that is perfectly legal and runs, it doesn’t really get too much accomplished. In this scenario that’s fine, but that’s not usually the case so now we’ll move on to a version that actually does some processing.
The Classic ASP Way

One of the nice things about ASP.NET is that it will work with a lot of classic ASP style code with only minor changes. Anyone who is familiar with ASP should have no problem making out what is going on in the code listing below. Besides the use of VB instead of VBScript there’s really nothing to distinguish this from a classic ASP script.

helloworld2.aspx
<%@ Page Language=”VB” %>

<html>

<head>

<title>ASP.NET Hello World</title>

</head>

<body bgcolor=”#FFFFFF”>

<p><%= “Hello World!” %></p>

Read more: http://www.codeguru.com/csharp/.net/net_asp/tutorials/article.php/c19305/Writing-Your-First-ASPNET-Page.htm

I am a strongly typed fan programmer. A good explanation why PHP and Javascript actually gives me a lot of headache. Btw what I means with type is not type –> typing but more to type –> data type, type –> object type, type –> variable type. So I hope there is no confusion ok. Because I want to share sth about this really.

Lately I have been exploring C# a lot. A thing that most of software engineers do when they are already working or at least graduate from college. I am one of the lucky few to be able to access C# while I am not even in my final year :) .

What I am trying to tell you here is how powerful C# in this ‘type’ thingy. Let’s first explore how other languages perceive ‘type’.

PHP & Javascript, the 2 most famous language for Web Developer. Different architecture, uniquely separation in usage, in those parts these two differ. Several simiralities I can think of: there are no other languages in this world that has strong community support as big as these two! (Not even Java). Well actually I am not actually judging Javascript fairly. But I do know almost everyone knows how to use Javascript in the open source community. Even the most newbie ones. There is one more similarity these two share. That is loosely typed.

There exists Java and VB too. These two have too much differences. One is supported through a community, one is basically a product of a corporation. VB used to rule this world before Java replaced them few years ago. And now another product of the same corporation who made VB, which is C# is ready to reclaim the throne. Anyway forget about it first, what I want to tell you here is how these two are the strongly typed kinda language.

Let’s assume you know how to use Java / VB:
1. In Java you will declare variable like this:

int num = 5 //Java

Whereas in VB:

Dim num as Integer = 5 ‘VB

2. Where somehow in PHP

$num = 5;//PHP

And in Javascript

var num = 5;//JS

3. Whereas in C#

both of this valid!

int num = 5;//C#

var num = 5;//C#

Gosh this is so awesome!! You guys realize how much this will actually help? What I heard at first is that Microsoft wants to convert other language devotees by providing this feature. Yet they somehow came out with an actually a fantastic and awesome feature. The way I see this feature will help is too practical I don’t have words to describe it. But let’s give it a try!

1. Do you spend great deal of time dealing with casting type? Now with this feature you don’t have to any more!

2. Do you want to have a variable that is used interchangeably between your server side and client side without having to apply JSON? Well now you can! As JSON is too much pain in the ass aldy!

3. Are you working in the Unit Testing Team? Well this will certainly give you more visibility on bugs!

This feature certainly can benefits developers more. And certainly will give more benefits for C# to compete with Java.

Assume in your web application you have a gridview control. For some reason you would like to extract the value of a particular cell.

There is no direct method to extract it, however there are few built in functions that you can utilize.

First it depends on what is the “type” of your gridview cells..

1. If it’s a boundfield type (bounded to a datasource), then you shall do this.

GridView.Rows[rowindex].Cells[columnindex].Text;

2. Otherwise if it’s a template field (bounded to a datasource and later on binded into a web control template)

Label L = GridView.Rows[rowindex].Cells[columnindex].FindControl(“yourcontrolId”) as Label;
string cellvalue = L.Text;

If you have a TextBox control for example then change “Label” into “TextBox”.

I hope this helps. Thank you.

1 2 3 4 5 9