Archive

Archive for the ‘Visual Studio 2010’ Category

Use “Run To Cursor” and save time while debugging

September 7, 2013 Leave a comment

Run to cursor is a great and an hidden features of Visual Studio. This can really boost up your productivity of work while debugging any application in Visual Studio. You can really avoid the step by step debugging and directly stop the debugger where you are targeting it to stop. “Run to Cursor” is just like another breakpoint, but in this case you don’t need to start the Visual Studio debugger manually and the break points clears when it’s hit. When you select the run to cursor option, visual studio starts the debugger automatically and execution stopped to the selected line.
Right click on the line where you want to stop the debugger, you will get the “Run to Cursor” option from the context menu; Select it.

Run To Cursor

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

How to increase debugging idle time in Visual Studio configuring IIS

March 12, 2012 1 comment

Background

When we are debugging any web application hosted in our local IIS using visual studio, we attach the worker process (w3wp.exe) and start debugging. It works fine when we are continuously doing step into (F11) and step over(F10) actions to debug the code. But i am sure that every developer has faced the situation when he/she is debugging the code for a long time and in some cases he/she is idle or not doing any step in or step over action and getting the error message from visual studio saying :

“The debugger stopped execution of code on the Web site. This caused Internet Information Services (IIS) to assume that the worker process stopped responding. Therefore, IIS terminated the worker process.” 

then we press “ok” and immediately visual studio stops debugging process. In that case, to debug the application again we need to start the debugging process from the beginning. This kills significant amount of development time and effort.

 

Why we get this error message?

IIS monitors the worker process by sending a periodic ping request. If the worker process does not respond in a timely manner, IIS terminates the process after a specific number of ping. Default timeout is 90 second and that why we get this error message.

 

Solutions

Configuring the application pool in IIS, we can easily fix this problem and can debug easily. There are two configurable way to solve this:

1. Setting the ping enable to false

Setting Ping Enabled to False stops IIS from checking whether the worker process is still running and keeps the worker process alive until you stop your debugged process.

2. Increasing the ping maximum response time

Setting Ping Maximum Response Time to a large value allows IIS to continue monitoring the worker process.

To do these follow the steps:

  1. Open IIS Manager .
  2. Click Application Pools.

3. In the Application Pools list, right-click the name of the pool your application runs in, and then click Advanced Settings.

4.In the Advanced Settings dialog box, locate the Process Model section, and perform one of the following actions:

  • Set Ping Enabled to False.
  • Set Ping Maximum Response Time to a value that is larger than 90 seconds

5. Click “Ok” to close the Advanced Settings dialog box.

6. Close IIS Manager.

 

Encrypt Connection String in web.config

December 7, 2011 Leave a comment

Never keep clear plain connectionstring in web.config file. The risk and consequences of this is self expalanatory. All you need to do is follow below steps and you are through with this.

Steps to be followed.

 

  1. Go to Visual Studio Command prompt in the “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\”path.
  1. Encrypt Web.Config connectionStrings using below command;
  1. aspnet_regiis -pef “connectionStrings” path of the physical folder where web.config resides (e.g. aspnet_regiis -pef “connectionStrings” D:\ProjectName)
  1. You will get the message “Encrypting configuration section… Succeeded!”
  1. Run Following Commands;
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “ASPNET”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NETWORK SERVICE”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NT AUTHORITY\NETWORK SERVICE”
  1. Restart IIS

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;

}

 

 

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.

 

 

Finding Geolocation information from ip address in asp.net

November 18, 2010 2 comments

Ip is the internet protocol for communication between nodes.

Ip is used to identify a host and address the location. If we need to identify the user

who are all accessing our website and store the ip address in our database is very simple and very easier.

This is the way to track the users ip address. Fetch a client’s ip address as soon as he access our web site in asp.net.

Some of them may use a proxy ip address. But we can get their ip address with this simple code.

Add following namespace in page

using System.Net;

string ipAddress ="";

//Get the Host Name
string hostName = Dns.GetHostName();

//Get The Ip Host Entry
IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);

//Get The Ip Address From The Ip Host Entry Address List
IPAddress[] ipAddress = ipHostEntry.AddressList;

ipAddress = ipAddress[ipAddress.Length - 1].ToString();

To get the Geolocation of IP address you can use the various
API which would gives you result in various different format(csv,xml)

http://www.ipinfodb.com/ip_location_api.php

You can get Geolocation information from

http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Response comes in XML format. using xml deserialize, I deserialize the response.

[XmlRootAttribute(ElementName = "Response", IsNullable = false)]

public class IPLocator
{
private string longitude;
public string Longitude
{
get { return longitude; }
set { longitude = value; }
}

private string latitude;
public string Latitude
{
get { return latitude; }
set { latitude = value; }
}
private string zip;
public string Zip
{
get { return zip; }
set { zip = value; }
}

private string ip;
public string IP
{
get { return ip; }
set { ip = value; }
}
}

After deserialization IPLocater class bind All properties of requested IP Address.

Binding Class is return IPLocater class.

Code of IPDetals Class

public IPLocator GetData(string ipAddress)
{
IPLocator ipLoc = new IPLocator();
try
{
//apiKey can be generated from below link

//http://www.ipinfodb.com/ip_location_api.php

string apiKey = "anykey";
string path = "http://api.ipinfodb.com/v2/ip_query.php?key=" + apiKey + "&ip=" + ipAddress + "&timezone=false";

WebClient client = new WebClient();
string[] eResult = client.DownloadString(path).ToString().Split(',');

if (eResult.Length > 0)
        ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
}
catch
{ }

return ipLoc;
}

//Desrialize XML String
private Object Deserialize(String pXmlizedString)
{
   XmlSerializer xs = new XmlSerializer(typeof(IPLocator));

   MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));

  XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

  return xs.Deserialize(memoryStream);

}

//String to UTF8ByteArray

private Byte[] StringToUTF8ByteArray(String pXmlString)
{

UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
}

//You can get the Geolocation infoamation here

string ipAddress = HttpContext.Current.Request.UserHostAddress;

IPDetails ipDetails=new IPDetails ();
IPLocator ipLocater = ipDetails.GetData(ipAddress);
Response.Write(ipLocater.CountryName);