Archive

Archive for the ‘ASP.Net’ Category

Find the References Easily – Code Reference Indicator in Visual Studio 2013 Preview

September 7, 2013 Leave a comment

As a developer one of the common task that we perform during the development is finding the code references using “Find All References” features. This is very much known to us and we all know why we used it. In Visual Studio 2013, the same things can be achieved in much easier and visualize way. You can see the number of reference as and when you are referring a class, properties, member variable or a method. You can call this feature as “Code Reference Indicator” which is part of “Code Information Indicator” feature of Visual Studio 2013 Preview.

As shown in the image attached, the references are show in the just top of referenced members.

reference

Advertisements

State Management

What is state management?

Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can’t holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.

Page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.

There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:

  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.

Different types of state management?

There are two different types of state management:

  1. Client Side State Management
    • View State
    • Hidden Field
    • Cookies
    • Control State
  1. Server Side State Management
    • Session
    • Application Object
    • Caching
    • Database

Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.

Advantages of view state?

This are the main advantage of using View State:

  • Easy to implement
  • No server resources are required
  • Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state?

This are the main disadvantages of using View State:

  • It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
  • Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
  • It does not have any support on mobile devices.

When we should use view state?

A few point you should remember when you select view state for maintain your page state.

  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state

When we should avoid view state?

You won’t need view state for a control for following cases,

  • The control never change
  • The control is repopulated on every postback
  • The control is an input control and it changes only of user actions.

Where is view state stored?

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.

Viewstate value is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read. any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to trace your view state information?

If you want to trace your view state information, by just enable “Trace” option of Page Directive

state information

Now Run your web application, You can view the details of View State Size along with control ID in Control Tree Section. Don’t worry about “Render Size Byte” , this only the size of rendered control.

trace

Enabling and Disabling View State

You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false.

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.

Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.

For enabling the same, you have to use the same property just set them as True

Exporting XML in a C# ASP .NET Web Application

August 16, 2011 2 comments

XML (extensible markup language) is a popular format of data for importing and exporting between different applications designed using different programming languages. Since XML uses a standardized format of data, applications can easily parse the XML data to pull out specific fields, blocks, and even write their own XML files. XML is especially useful as a protocol for communicating over the Internet with applications

using (System.IO.MemoryStream stream = new System.IO.MemoryStream())

{

// Create an XML document. Write our specific values into the document.

System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.ASCII);

// Write the XML document header.

xmlWriter.WriteStartDocument();

// Write our first XML header.

xmlWriter.WriteStartElement(“WebApplications”);

// Write an element representing a single web application object.

xmlWriter.WriteStartElement(“WebApplication”);

// Write child element data for our web application object.

xmlWriter.WriteElementString(“Date”, DateTime.Now.ToString());

xmlWriter.WriteElementString(“Programmer”, “Primary Objects”);

xmlWriter.WriteElementString(“Name”, “Hello World”);

xmlWriter.WriteElementString(“Language”, “C# ASP .NET”);

xmlWriter.WriteElementString(“Status”, “Complete”);

// End the element WebApplication

xmlWriter.WriteEndElement();

// End the document WebApplications

xmlWriter.WriteEndElement();

// Finalize the XML document by writing any required closing tag.

xmlWriter.WriteEndDocument();

// To be safe, flush the document to the memory stream.

xmlWriter.Flush();

// Convert the memory stream to an array of bytes.

byte[] byteArray = stream.ToArray();

// Send the XML file to the web browser for download.

Response.Clear();

Response.AppendHeader(“Content-Disposition”, “filename=MyExportedFile.xml”);

Response.AppendHeader(“Content-Length”, byteArray.Length.ToString());

Response.ContentType = “application/octet-stream”;

Response.BinaryWrite(byteArray);

xmlWriter.Close();

}

Categories: ASP.Net, C#

Creating Crystal reports in ASP.NET

August 12, 2011 3 comments

Create a new website and right click on

solution explorer >

add new Item

Select Crystal Report

In the dialog box choose blank report

 

 

Now click on Crystal Report Menu in Visual Studio 2010 and select Database Expert

 

 

Select OLE DB under “Create New Connection” and select Data Provider.

 

 

Click on Next, In Next Screen provide Server name and credential. And select Database.

 

 

Now from Database field, drag and drop fields as required in the report.

 

Add New ASPX Page and drag Crystal Report viewer  on the form.

Click on smart tag of Report Viewer and choose report source and click on finish.

Here is the HTML markup.

<CR:CrystalReportViewer ID=”CrystalReportViewer1″ runat=”server”

AutoDataBind=”True” GroupTreeImagesFolderUrl=”” Height=”1202px”

ReportSourceID=”CrystalReportSource1″ ToolbarImagesFolderUrl=””

ToolPanelWidth=”200px” Width=”1104px” />

<CR:CrystalReportSource ID=”CrystalReportSource1″ runat=”server”>

<Report FileName=”CrystalReport.rpt”>

</Report>

</CR:CrystalReportSource>

 

Add following code in Page_load,

 

protected void Page_Load(object sender, EventArgs e)

{

ReportDocument crystalReport = new ReportDocument();

crystalReport.Load(Server.MapPath(“CrystalReport.rpt”));

CrystalReportViewer1.ReportSource = crystalReport;

}

 

 

Move ViewState to the bottom of the page

If you move your viewstate from the top of the page to the bottom, you will get better search engine spidering.

 

Step 1 :

Create a class file in App_code folder of your application and name it as “PageBase.cs“. Copy following code to the class file.

 

using System.IO;

using System.Web.UI;

 

namespace WebPageBase

{

public class PageBase : System.Web.UI.Page

{

/// This method overrides the Render() method for the page and moves the ViewState

/// from its default location at the top of the page to the bottom of the page. This

/// results in better search engine spidering.

 

protected override void Render(System.Web.UI.HtmlTextWriter writer)

{

// Obtain the HTML rendered by the instance.

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

base.Render(hw);

string html = sw.ToString();

 

// Hose the writers we don’t need anymore.

hw.Close();

sw.Close();

 

// Find the viewstate.

int start = html.IndexOf(@”<input type=””hidden”” name=””__VIEWSTATE””” );

// If we find it, then move it.

if (start > -1)

{

int end = html.IndexOf(“/>”, start) + 2;

 

string strviewstate = html.Substring(start, end – start);

html = html.Remove(start, end – start);

 

// Find the end of the form and insert it there.

int formend = html.IndexOf(@”</form>”) – 1;

html = html.Insert(formend, strviewstate);

}

 

// Send the results back into the writer provided.

writer.Write(html);

}

}

}

 

 

Step 2 :

Inherit your aspx pages from the base class.

 

public partial class Page : WebPageBase.PageBase

{

// Your code here

}

10 Principal for keeping Your Programming code clean

February 2, 2011 Leave a comment

A common issue in almost every profession that can drive people completely insane is having to continue from what somebody else started. The main reason for this being the fact that everyone has different ways of working, and sometimes these self-induced habits can be just downright messy.

In order to make code look cleaner, and thus, support team work (meaning that somebody else might need to work with what was coded before), there are certain considerations that should be taken into account.

1. Revise Your Logic Before Coding

Before blindly typing into the debugger of choice, some flow diagrams or written pseudo-code might come in handy to previously verify the logic behind those lines of code. Writing it down first can clarify many doubts or insecurities about complex functionality, and therefore save a lot of time. But most importantly, helping you get it right faster will also help you avoid all the messy code replacements and additions that tamper with the following principles.

2. Clearly Expose the Structure of the Page

Working with main containers is useful, but working with main containers with a representative ID is even more useful. Consider the following starting scenario:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<div id=”main-container”>

<div id=”header”>

<div id=”logo”>…</div>

<div id=”main-menu”>…</div>

</div>

<div id=”content”>

<div id=”left-column”>…</div>
<div id=”center-column”>…</div>

<div id=”right-column”>…</div>

</div>

<div id=”footer”>

<div id=”footer-menu”>…</div>

<div id=”disclaimer”>…</div>

</div>

</div>

The structure appears evident, thanks to the DIV containers that are concretely named after their destined content. Not only will it be simpler to start adding code, but it’ll also be perfectly transparent for someone who tries to add or remove something afterward. This structuring method, however, should be aided by the next statement.

 3. Use the Correct Indentation

Supporting the previous pronouncement on structure, indentation distinctly displays the opening and closing points of each element used. If every line of code is glued to the left side of the screen, it’ll be very hard to distinguish the exact place where an element is closed. Therefore, it’ll mess up the effort made at designing a complete structure, since it won’t be noticeable afterward.

 4. Write Explanatory Comments

Underestimating the value of good comments is disregarding a very effective way of code documentation. It’s easy, fast, and very straight-to-the-point, since it’s done right then and there when it’s needed.

Comments are also efficient considering the fact that they can be read at the exact moment of doubt. They can, however, be overused. And that brings us to the next recommendation.

 5. Avoid Abusing Comments

Comments aren’t to be treated lightly. When commenting on code, the current functionality is explained in terms of variables and results. What comments are NOT made for is:

  • Writing explanatory notes to self (e.g. /* Will finish this later… */).
  • Blaming stuff on other people (e.g. /* John coded this. Ask him. */).
  • Writing vague statements (e.g. /* This is another math function. */).
  • Erasing chunks of code. Sometimes people are not sure of erasing things and it’s not absolutely evil to comment that code instead.

What’s not right is to just leave it afterwards. It’ll be terribly confusing. If the code will be documented via embedded comments, the team members need to make sure those comments are there for a reason.

Examples of good comment use are:

  • Authoring specifications (e.g. /* Coded by John, November 13th 2010 */).
  • Detailed statements on the functionality of a method or procedure (e.g. /* This function validates the login form with the aid of the e-mail check function */).
  • Quick notifications or labels that state where a recent change was made (e.g. /* Added e-mail validation procedure */).

6. Avoid Extremely Large Functions

In the process of adding functionality to an application, its coded methods tend to grow accordingly. One can come across functions that consist of up to a hundred lines of code, and this tends to become confusing.

A better practice would be to break up large functions into smaller ones. Some procedures may even be repeating themselves amongst the rest of the functions conforming the whole application process. The team could make better use of those repeated procedures through separate functions. This, however, should have been avoided from the beginning if the first recommendation was carried out correctly.

 7. Use Naming Standards for Functions and Variables

Whenever a variable or a function is created, its name should be descriptive enough as to give a general idea of what it does or what it’s for.

There are companies that have their own pre-established naming standards

(e.g. The prefix ‘int_’ for any numeric variables), but there are also many companies in which the employees do not keep these standards. Laziness makes people work double the time during future redesigns, so everyone needs to start learning how to get rid of it.

 8. Treat Changes with Caution

The correct appliance of changes summarizes a lot of what has been previously said, like commenting meaningfully and not disrupting indentations. Nevertheless, it needs to be emphasized. Whenever there’s a need for adding, removing, or changing something, there should also be an awareness of not meddling with previous efforts for maintaining the code clean and ordered.

This mainly involves:

  • Keeping the correct indentations (e.g. when inserting an IF clause, its contents’ indentations will be augmented).
  • Commenting on the modification made or broadening the existing comments.
  • Respecting standards in use.

 

9. Avoid Indiscriminate Mixing of Coding Languages

In-line CSS styling and scattered JavaScript tags with short procedures within them are very good examples of incorrect mixing of coding languages throughout your development process. Ignoring this principle will result in huge element tags with an embedded STYLE property, lots of interruptions in the flow of the structure because of embedded functions, and of course lots and lots of confusion.

Even with the addition of comments, it’ll still look like everything and nothing at the same time. Having the appropriate divisions between different coding languages will give order to the logic applied. This brings us, though, to the next consideration.

 10. Summarize Your Imports

Even though it is much better to have additional coding languages imported from different files, this shouldn’t be abused. If there are too many style sheets, they can probably be summarized into one or two.

This won’t only save space and make things look cleaner, but it will also save loading time. Each imported file is an HTTP request that tampers with the performance of your application. So apart from being a consideration for tidiness, it is also a consideration for efficiency.

Categories: ASP.Net, ASP.Net 3.5

The web server process that was being debugged has been terminated by Internet Information Services (IIS)

January 22, 2011 Leave a comment

By default, debugging a website or web project within Visual Studio bring up the built-in server of Visual Studio. But, we do have a problem to change the server to an IIS instance. I recently switched to debugging on IIS on my Windows 7. Debugging works fine. The only problem is that if your code hit some breakpoint and if you leave the program in ‘break’ mode for more than 90 seconds, Visual Studio shows the following message:

 


 

 

After a bit tweaking around in the new IIS interface, I got the solution:

  • Open Internet Information Services (IIS) Manager.
  • From the server tree (the item with the name as the server name), choose Application Pools.
  • Choose the Application Pool corresponding to your testing IIS website (usually it has the same name as your IIS website)
  • Right-click and choose Advanced Settings.
  • From the Process Model node, change the Ping Maximum Response Time (seconds) to a comfortably higher value (I have set the value to 900 seconds which is 15 minutes).

     

Alternatively, you can also set the Ping Enabled property to False.

Apparently what happens is that the server keeps pinging the worker process and waits for a response. When in debugging mode, the worker process is affectively suspended, which results in the ping not being responded.