A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for the ‘ASP.NET’ Category

DataSet Vs Custom Entities

Posted by kiranpatils on June 1, 2012

Challenge:

Dear Readers, Apologize for not sharing anything with you since so long. As was bit busy with projects. (But as I told in my earlier posts as well, It’s good to be busy. Because during your busy time you will learn a lot, and needless to say once you get time you will have a lot to share!)

This week, We were discussing what to use for our new project for passing data from one layer to another layer. DataSet Or Entities.

I’m big fan of Entities and Generics. But thought to do some research on it, before concluding anything. And my research revealed that I’m (I know you as well) not only one who is searching on this topic. Lot of people shared their views on web. But I filtered out few links, which I liked most (along-with the Excerpt which is important to read from that link)  and thought to share with you! So, here you go

http://forums.asp.net/t/1129497.aspx/1

“The problem with DataSets is that they tend to be pretty memory hungry. They also get a bit difficult to manage as your application gets larger. When you need more complex solutions, the initial effort that you put into getting custom classes up and running can pay off with shorter development cycles if you do it right. “

Going with custom classes is certainly better in many ways.

i) easier to add logic

ii) business validation is easier. This is tougher when using DataSet

iii) if you are using DataSet, even when the number of rows returned are small, the whole dataset has to be constructed which is quite an overhead. Custom classes are more light-weight

http://codebetter.com/jefferypalermo/2005/05/20/displaying-aggregates-dataset-vs-domain-object-performance-level-300/

“The page that used an array of custom domain objects to present a read-only display was 3.7% FASTER than the same functionality using a DataSet. “

http://blogs.msdn.com/b/reinouth/archive/2006/03/08/546510.aspx

“Now, amazingly, this has sparked somewhat of a religious war between various parties within the project. Just to be clear – I prefer custom objects – partly for their simplicity and readability”

“I agree with you on custom objects, you will have more control and better performance.”

http://blogs.msdn.com/b/irenak/archive/2006/02/27/539832.aspx

  • Memory consumption using Dataset = 290,436 (3.5 times larger than using Products class)
  • Memory consumption using array of objects = 140,028 (1.7 times larger than using Products class)
  • Memory consumption using Product class = 82,656 (BEST)

So, no matter how you turn it, strongly typed custom classes are your best bet in terms of memory consumption!

http://weblogs.asp.net/paolopia/articles/dsvscustomentities.aspx

2) BIZ and DAL are written by people different from the presentation layer group, so they have different knowledge about the data structures

http://www.4guysfromrolla.com/articles/051805-1.aspx

While DataSets are an easy way to return data, I think they are less than ideal for a couple of reasons. First, they add a lot of bloat to the returned XML payload since DataSets return not only the data they contain but also the data’s schema.

In my original article one of my main thrusts for not using DataSets was the performance disparity between DataSets and DataReaders. As I cited from A Speed Freak’s Guide to Retrieving Data in ADO.NET, when bringing in several hundred or thousands of records, a DataSet can take several seconds to be populated, where as a DataReader still boasts sub-second response times. Of course, these comparisons against several hundred to several thousand records are moot if you are working with a much smaller set of data, say just 10 to 50 records in total. For these smaller sized result sets, the DataSet will only cost you less than a second (although the DataReader still is, percentage-wise, much more efficient).

http://swap.wordpress.com/2007/07/10/dataset-vs-custom-entity/

Benefit with Custom Entity Classes

- Take advantage of OO techniques such as inheritance and encapsulation
- You can add custom behavior
- Object-Relational Mapping
- Mapping Custom Collections
- Managing Relationships between two entities in Object oriented way

http://stackoverflow.com/questions/1679064/should-i-use-entity-framework-dataset-or-custom-classes

I would agree with Marc G. 100% – DataSets suck, especially in a WCF scenario (they add a lot of overhead for handling in-memory data manipulation) – don’t use those. They’re okay for beginners and two-tier desktop apps on a small-scale maybe – but I wouldn’t use them in a serious, professional app.

http://www.rosscode.com/blog/index.php?title=datasets_vs_custom_objects&more=1&c=1&tb=1&pb=1

Solution:

So, in summary, as per my understanding, performance, maintainability, and serialization point of view entities looks more promising than DataSet.

Few of my guidelines:

You should use DataSet when:

1. Project is small.
2. Only Single person is going to work on all layers.
3. Data size is small.
4. Application is not going to get changed in future. (Mainly Database structure).
5. You are not worried about Maintainability.

You should use Custom Entities when:

1. Project is big.
2. Different people will be working on different layers.
3. Data size is big.
4. Application is going to get changed in future. (Mainly Database structure).
5. You are worried about Maintainability.
6. If you love to follow OOPs concepts.

These all are my views, and they might look biased toward Entities. Because as i told earlier, I’m big fan of custom entities. But if you would like to use DataSet and have good reasons to use it. Don’t worry go for it!

Happy Coding! :-)

Posted in .NET, ASP.NET, GoodToKnow | Tagged: , , | Leave a Comment »

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occured because all pooled connections were in use and max pool size was reached.

Posted by kiranpatils on June 21, 2011

Challenge:

Have you seen following error?

timeout-expired-the-timeout-period-elapsed-prior-to-obtaining-a-connection-from-the-pool-this-may-have-occured-because-all-pooled-connections-were-in-use-and-max-pool-size-was-reached

Then this post is to solve it!

Solution:

As per the error your code has not closed the opened SqlConnection properly. For example

SqlConnection conn = new SqlConnection(

myConnectionString);
conn.Open();
doSomething(); /*  If some error occurs here — Next line will not get called and it will leave connection open */
conn.Close();

Solution:

1.
SqlConnection conn = new SqlConnection(myConnectionString);
try
{
conn.Open();
doSomething(conn);
}
finally
{
conn.Close();    // This line will get called in any case — success/failure
}

So, open your solution in Visual Studio and search in entire solution for all open connections and for all the code implement above suggested solution.

Just a note : If you have written Data Access layer code in code behind file then you are in trouble here. You have to do changes at N number of places. If you would have created separate Data Access layer (Technically Class Library) and Method to do DB operation then your task would have been easy enough!
2) You can raise the connection pool size in the connection string.  For example, you can add “Max Pool Size=100″ to your connection string to increase the pool size to 100.

Implement above solutions. You should not see any issues any more.

Good to read :
http://blogs.msdn.com/b/tolong/archive/2006/11/21/max-pool-size-was-reached.aspx
Happy DB Access! :-)

Posted in .NET, ASP.NET | Tagged: , , | 2 Comments »

ASP.NET Session with proxy server

Posted by kiranpatils on June 21, 2011

Challenge:

Y’day I came across with nice issue. Basically there is one Web Application developed using ASP.NET and deployed on IIS Server. Now, this application will be accessed by more than 2-3 people from Local area network. So, far so good.

This application uses Session and here issue comes — For all users across different machines were getting access of different persons session data — which should not be the case. Because as per theory “session” is unique for each user. But my dear friend theory is theory in real life you have to face lots of challenges like this. :-)

Solution:

So, I jumped in to this issue and first tried to understand what is going on [The basic stuff -- which I always do!].

To quick check the Session ID and other Session related information. I decided to code one page which will print my session info on page and it should show me some direction. I opened my favorite tool — Visual Studio and added one page using single file model — which I can deploy easily on server.

The code looks like below:

<%@ Page Language=”C#” AutoEventWireup=”true” %>

<%@ Import Namespace=”System” %>
<!–DOCTYPE html PUBLIC “/-/W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
xmlns=”http://www.w3.org/1999/xhtml”>
<script language=”C#” runat=”server”>

// new line
private const string breakLine = “
“;

// Strong Start
private const string strongStart = ““;

// Strong End
private const string strongEnd = “”;

private const string sessionTimeKey = “SessionTime”;

protected void Page_Load(object sender, EventArgs e)
{
// generate string with all required information
StringBuilder sessionInformation = new StringBuilder();

if (Session[sessionTimeKey] == null)
// Current Time
Session[sessionTimeKey] = DateTime.Now;

// IsCookieless
sessionInformation.Append(strongStart);
sessionInformation.Append(“IsCookieless : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.IsCookieless.ToString());
sessionInformation.Append(breakLine);

// IsNewSession
sessionInformation.Append(strongStart);
sessionInformation.Append(“IsNewSession : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.IsNewSession.ToString());
sessionInformation.Append(breakLine);

// Session.Keys.Count
sessionInformation.Append(strongStart);
sessionInformation.Append(” Total Keys Count : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.Keys.Count.ToString());
sessionInformation.Append(breakLine);

// Mode
sessionInformation.Append(strongStart);
sessionInformation.Append(” Session Mode : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.Mode.ToString());
sessionInformation.Append(breakLine);

// SessionID
sessionInformation.Append(strongStart);
sessionInformation.Append(” SessionID : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.SessionID);
sessionInformation.Append(breakLine);

// Timeout
sessionInformation.Append(strongStart);
sessionInformation.Append(” Timeout : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Session.Timeout.ToString());
sessionInformation.Append(breakLine);

// Session Value
sessionInformation.Append(strongStart);
sessionInformation.Append(” Session Value(DateTime) : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Convert.ToString(Session[sessionTimeKey]));
sessionInformation.Append(breakLine);

// SERVER_NAME
sessionInformation.Append(strongStart);
sessionInformation.Append(” SERVER_NAME : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["SERVER_NAME"]);
sessionInformation.Append(breakLine);

// SERVER_PORT
sessionInformation.Append(strongStart);
sessionInformation.Append(” SERVER_PORT : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["SERVER_PORT"]);
sessionInformation.Append(breakLine);

// LOCAL_ADDR
sessionInformation.Append(strongStart);
sessionInformation.Append(” LOCAL_ADDR : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["LOCAL_ADDR"]);
sessionInformation.Append(breakLine);

// REMOTE_ADDR
sessionInformation.Append(strongStart);
sessionInformation.Append(” REMOTE_ADDR : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["REMOTE_ADDR"]);
sessionInformation.Append(breakLine);

// REMOTE_HOST
sessionInformation.Append(strongStart);
sessionInformation.Append(” REMOTE_HOST : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["REMOTE_HOST"]);
sessionInformation.Append(breakLine);

// SERVER_NAME
sessionInformation.Append(strongStart);
sessionInformation.Append(” SERVER_NAME : “);
sessionInformation.Append(strongEnd);
sessionInformation.Append(Request.ServerVariables["SERVER_NAME"]);
sessionInformation.Append(breakLine);

Response.Write(sessionInformation.ToString());

sessionInformation.Append(breakLine);
Response.Write(“———-SESSION CONTENT——————-”);
Response.Write(breakLine);

foreach (string item in Session.Contents)
{
if (Session[item] != null)
{
Response.Write(string.Format(“Key :{0} – Value : {1}”,
item,Convert.ToString(Session[item])));
Response.Write(breakLine);
}
}

}

protected void btnRefresh_Click(object sender, EventArgs e)
{
Response.Redirect(Request.Url.ToString());
}

</script>
<head runat=”server”>
<title>Session Check Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnRefresh” runat=”server” Text=”Refresh” OnClick=”btnRefresh_Click” />
</div>
<br />
</form>
</body>
</html>

Basically, this page is my favorite page. Before a year using this page’s code only. I fixed one Live issue [Sticky Session was of on Load balancer on our web farm environment]. If you see the code of page it is quite simple. But very useful!

What I check there is Session ID, LOCAL Address and Session value which I store on page load’s not postback only. And it has one nice button called “Refresh” which redirects on same page.

We deployed this page on Server and started accessing it from different – different machines. And we started clicking on “Refresh” button which shown us few strange thing as below:

1. SessionID was changing on each Refresh button’s click – This should not be the case. Because Session ID will be unique till session expires or user closes the browser.

2. Session’s value was also changing on each refresh.

3. REMOTE_ADDR was coming same on 2-3 machines.

Now, we started removing possibilities one by one.

For issue#1 — We checked Web.Config and found that StateNetworkTimeout property has been assigned, frankly it should not cause an issue. But we thought better to remove it. So, we removed it.

#2 ,#3 – Then we realized that we are using Proxy on our LAN and REMOTE_ADDR’s IP address was IP Address of proxy server.

So, we found that Proxy is causing us an issue. To resolve it we removed proxy server’s setting from Internet explorer’s settings for few machines from which we need to access this application.

Isn’t it simple?

Happy Coding! :-)

Posted in ASP.NET | Tagged: | 6 Comments »

Debug Your ASP.NET Application that Hosted on IIS

Posted by kiranpatils on January 13, 2011

Challenge:

One of my friend asked me that how we can debug Website which is hosted on IIS? The answer was quite simple and I am using it since so long. But I thought I should document it and that’s why putting the information on this blog. So when you guys need to do this, you can do it!

Solution:

First I thought to write my own article. But suddenly thought some one might have already written on this, and I found following nice article:

http://www.codeproject.com/KB/aspnet/ProcessAttache.aspx#9

Article is so nice — Good Job Blog Author!

Just two things I would like to add to it which is as below:

  1. Shortcut for Attach to process menu is CTRL + ALT + P.
  2. If you are using windows XP then you will not find “w3wp.exe“. You will find “aspnet_wp.exe

If you found this post helpful say thanks to CodeProject article author.

Happy Debugging! :-)

Posted in ASP.NET, IIS | Leave a Comment »

SharpZipLib is not working When compression is enabled on IIS

Posted by kiranpatils on December 13, 2010

Challenge:

Before so many months back I was facing problem related to SharpZipLib. Basically Using SharpZipLib we were zipping a file at runtime and allowing users to save that zipped file at his/her local machine. It works fine on my local box. But when we roll it out on another IIS server it was not working. [General developers problem :) ].

When we delved more in to that, then found that another IIS server has been configured for “HTTP Compression“.

Solution:

Okay, so now we were knowing that Issue is due to IIS Server which has HTTP Compression enabled. Unfortunately we can’t disable it as it will affect the performance. So, now we just have one way to make it working which is through code. We tried lot and finally we found a way to do it, it was just one line change in our Response’s ContentType.

Before we see working code, let’s see the code which was having a problem:


private void DownloadZip(byte[ bufferzip)
 {
 // Load Zip file
 if (bufferzip != null && bufferzip.Length > 0)
 {
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.ClearHeaders();
 HttpContext.Current.Response.CacheControl = "public";
 HttpContext.Current.Response.ContentType = "application/zip"; //This line was causing a problem!
 HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
 HttpContext.Current.Response.Flush();
 HttpContext.Current.Response.BinaryWrite(bufferzip);
 HttpContext.Current.Response.End();
 }

}

Now, it’s time to see a working code!


private void DownloadZip(byte[ bufferzip)
 {
 // Load Zip file
 if (bufferzip != null && bufferzip.Length > 0)
 {
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.ClearHeaders();
 HttpContext.Current.Response.CacheControl = "public";
 HttpContext.Current.Response.ContentType = "application/octet-stream"; // This is real Hero!
 HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
 HttpContext.Current.Response.Flush();
 HttpContext.Current.Response.BinaryWrite(bufferzip);
 HttpContext.Current.Response.End();

}

}

Now, if you compare the working and non working code you will see the difference. HttpContext.Current.Response.ContentType = “application/zip”; was causing an issue and changing it to HttpContext.Current.Response.ContentType = “application/octet-stream”; solved it!

Reference links:

http://community.sharpdevelop.net/forums/p/10467/28859.aspx#28859
http://www.jlaforums.com/viewtopic.php?t=7295390
http://support.microsoft.com/kb/841120

Happy Coding! :-)

Posted in .NET, ASP.NET, SharpZipLib | 1 Comment »

Would like to provide take snapshot of URL/Page in your ASP.NET application?

Posted by kiranpatils on December 11, 2010

Challenge:

Few days back, my colleague asked me that how he can have functionality using which user can take snapshot of provided URL in his ASP.NET Application.

Solution:

I did also not know, but found the requirement very interesting. So. As usual had a chat with my best friend Google and found one nice tool named as IECapt.

I am not going to write how to use it, because someone has already done that. You can read it from here:

http://www.enestaylan.com/eng/post/2010/01/05/Taking-Snapshot-in-ASPNET.aspx

IECAPT Home Page: http://iecapt.sourceforge.net/

Just a note: IECapt# dll is also available. But it is not working with ASP.NET application. So, recommended way is to use IECapt.exe only!

Happy Sharpshooting! :-)

Posted in ASP.NET | Leave a Comment »

Could not load type ‘System.Web.UI.ScriptReferenceBase’ from assembly ‘System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Posted by kiranpatils on November 10, 2010

Challenge

If you are getting following error:

Could not load type ‘System.Web.UI.ScriptReferenceBase’ from assembly ‘System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Then you are on the right article

Solution

It’s highly likely that you compiled your code using .NET 3.5 Service Pack 1 but deployed to a system that has .NET 3.5 without Service Pack 1.

ScriptReferenceBase is a new class for Service Pack 1, clearly a refactoring of ScriptReference to allow common code for the new CompositeScriptReference class. If you compile your code using SP1, you will include a reference to this class, which does not exist in .NET 3.5 pre-SP1. When the non-SP1 runtime tries to load the class, you will receive the exception above.

Solutions are:

  • Compile using .NET 3.5 without SP1.

OR

  • Install SP1 on the target system

 

Posted in ASP.NET | Leave a Comment »

Awesome DataAccess Tutorials

Posted by kiranpatils on June 6, 2010

Hello All, Today while looking at my some old data i found very good ASP.NET DataAccess Tutorials. Which i was using a lot when i was totally newbie[Even today also I'm newbie only :) ]  in ASP.NET this tutorials contains everything and the content and the way tutorial teaches is really awesome. You must be thinking this guy is prasing and just keep talking about tutorials but where are the tutorials? Here you go : http://www.asp.net/data-access/tutorials And all tuorials are available in PDF Format for Download :-)

I hope this tutorials help the same way it helped me. Thanks to the Author for writing such a nice tutorials!

Posted in ASP.NET | Tagged: | 2 Comments »

Would like to set Session Timeout?

Posted by kiranpatils on May 31, 2010

Challenge:

Before so many months back i have been assigned for a task where we need to set a session timeout for our whole application. Some enthu guys will tell it is 2 mins. job just go in web.config and do the configuration and it’s done. But let me tell you it’s not that much easy :( . Because there are two things which affects on session timeout Forms Authentication Timeout and Session Timeout

Forms Authentication Timeout Configuration


<system.web>
 <authentication mode="Forms">
 <forms timeout="50000000"/>
 </authentication>
</system.web>

Session Timeout Configuration

<pre><configuration>
   <system.web>
      <sessionState mode="InProc"
                    cookieless="true"
                    timeout="20"/>
      </sessionState>
   </system.web>
</configuration></pre>

Solution

Unfortunately at tha time i haven’t written blog on it[I'm sorry for that]. But Here is the link where someone else did that already[Thanks to him!]:

http://dotnethitman.spaces.live.com/Blog/cns!E149A8B1E1C25B14!210.entry

http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx

http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.all

Posted in ASP.NET | Tagged: , | Leave a Comment »

Good To Know on ASP.NET Application Restarts

Posted by kiranpatils on May 25, 2010

You all may heard about ASP.NET Application restart. If no then it’s really good to know. Today i got few good links which i would like to share with you guys as well:

http://fuchangmiao.blogspot.com/2007/11/aspnet-application-restarts.html

http://blogs.msdn.com/b/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx

http://blogs.msdn.com/b/johan/archive/2008/02/18/monitoring-application-pool-and-application-restarts.aspx

Hope this articles clear all your questions on ASP.NET application restart. If not feel free to drop a comment here.

Posted in ASP.NET, GoodToKnow | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 102 other followers