Archive

Archive for the ‘.net 2.0’ Category

Handling Sessions Objects with a Custom Session Manager

September 18, 2008 Comments off

I try not to abuse Session objects too much—keep them simple types, not too many, etc.  However, on a recent project where there was a few of us dinking with the code, it became an issue with how the keys were named, where they were created, etc. 

To correct the problem on future projects, I tossed together a little class in the mix to manage the “keys”.

public class SessionManager

{

protected HttpSessionState session;

 

       public SessionManager(HttpSessionState httpSessionState)

       {

              session = httpSessionState;

}

 

public SessionManager()

       {

              session = HttpContext.Current.Session;

}

 

       public void Dispose()

       {

              session.Clear();

              session.Abandon();

       }

 

       public bool IsFoo

       {

              get { return

session[“IsFoo”].ConvertTo<bool>(); }

set { session[“IsFoo”] = value; }

}

 

       public string FooId

       {

              get { return

session[“FooId”].ConvertTo<string>(); }

set { session[“FooId”] = value; }

}

}

The two constructors allow the consumer to either accept the default HttpContext.Current session object or provide their own.  From there, the “keys” are coded within this page rather than in every code block throughout the site. 

To use the SessionManager:

I inherit all of my pages from a default page (DefaultPage, for lack of a better name) and place the session manager as a public field.

DefaultPage.cs:

public class DefaultPage : Page

{

public SessionManager CurrentSession;

      

protected void Page_PreInit(object sender, EventArgs e)

       {

              CurrentSession = new SessionManager();

}

}

To use the CurrentSession field, simply reference it.  This makes reading/writing to session easy on the inheriting pages.

private List<Foo> GetFooList()

{

var foo = sessionManager.IsFoo

              ? Foo.GetFooById(sessionManager.FooId)

: new List<Foo> { Foo.GetEmptyFoo() };

return foo;

}

Still tweaking to do, but it works and seems clean enough.

Suggestions or better ideas? ๐Ÿ™‚ 

Tweaking .NET Machine.Config For Production Deployments

September 17, 2008 4 comments

I recently rolled out an enterprise wide app to a pilot group (which, since pilots are silly or so I’m told, that means we rolled it out to EVERYONE or ~1200 users).  Not a huge amount by any means, but without a pilot, we didn’t have a good baseline to gauge performance settings.

I remember reading an article by Peter Bromberg ages ago about tuning IIS 6.0.  After a bit of Googling, I found it again and, one-by-one, started tweaking various settings on our development environment and hitting it with 500–1000 concurrent load users.

Here’s what I came up with that seemed to give the best bang for the buck.

  <system.net>

    <connectionManagement>
      <add address=”*” maxconnection=”100″ />
    </connectionManagement> 

  </system.net>

maxconnections – This sets how many outgoing connections the ASP.NET service can make FROM the server, such as to databases, web services, etc.  Increasing this can increase the number of concurrent connections are available to your application.

  <system.web>

    <deployment retail=”true” />

    <processModel
                autoConfig=”true”
                memoryLimit=”75″
                maxIoThreads=”100″
                minIoThreads=”30″
                minWorkerThreads=”40″
                maxWorkerThreads=”100″
                clientConnectedCheck=”00:00:05″ />

    <httpRuntime
                minFreeThreads=”352″
                minLocalRequestFreeThreads=”308″
                enableKernelOutputCache=”false”
                maxRequestLength=”10240″ />  

  </system.web>

deployment/retail – Setting retail=”true” essentially forces all web applications on that machine to compile without debug.  This is extremely helpful for those rare cases that you forget to set debug=”false” on a web project.  In a production environment, debug files should rarely/never be needed, so this blankets the server.

processModel/autoConfig – autoConfig sets everything to the defaults except what I explicitly set below.  Just at time saver.

processModel/memoryLimit – This is a percentage of how much memory a web process can consume before it splits off into another process.  Since our production servers ONLY run IIS and web servers, then it should be safe to set this to 75% of the total memory on the box.

processModel/maxIoThreads – Based on Bromberg’s recommendation, this controls how many IO threads are allowed to the web process.  minIoThreads is the other side of the scale.

processModel/maxWorkerThreads – Based on Bromberg’s recommendation, this controls how many worker threads are in the pool for each web process.  minWorkerThreads is the other side of the scale.

processModel/clientConnectedCheck – An excellent setting that tells the server to check every 5 seconds to see if the client is connected.  If not, trash their queued requests (since they’re not there to receive it anymore).  According to this source, this also helps for those situations where users get “impatient” and machine-gun click the mouse trying to get a response.

httpRuntime/minFreeThreads – Based on Bromberg’s recommendation, a setting that tells the machine what the minimum number of threads in the pool must be in order for incoming requests to be processed.

httpRuntime/minLocalRequestFreeThreads – Same as the prior, but for the local machine (localhost)—good for locally hosted web servers; however, I’m not sure if it’s smart enough to know if “localhost” and a registered DNS entry are the same (I never refer to a machine as localhost).  It’s set, but more research required here.

httpRuntime/enableKernelOutputCache – This is set to FALSE for me, though most everything recommends true.  Why?  Kernel Mode caching is great—it’s speedy and a good way to speed up pages; however, we’ve had several issues in the past (on IIS 6) where it caused sessions to “merge” across authenticated users.  The issue is described here in KB917072.  Setting this for the machine just solves the problem overall.  Honestly, unless I can guarantee a way that the sessions/cookies won’t cross, I’ll give up a few milliseconds of performance in the day to guarantee a user experience.

httpRuntime/maxRequestLength – The default request length is 4096K; however, for uploading large file into the system, that becomes the limit.  A few of our applications allows users to upload documents, PDFs, etc. and attach them—we need a larger limit.  ~10MB seems to work well.  You “could” set this in the web.config; however, we base our production server at 10MB and then ramp up from there.

As with all tweaks, your mileage may vary—as mine does every single day.  I’d be interested to hear of other tweaks for higher performing web sites as well as feedback on the above (especially if I misinterperted a setting and simply haven’t seen the failure yet).

Review: ANTS Profiler 4.0 Beta

August 11, 2008 2 comments

A few months ago, I purchased ANTS Profiler 3.2 and have loved it.  It’s really helped me dig into some of my code, find performance hang-ups, and (I think) turn out better code and learn (it’s sometimes hard to find “do betters” in a single dev environment).

I played around with a few of the 4.0 builds and they were nice, but I honestly didn’t have time to dig into them.After a busy weekend, I sat down and spent some quality time with the 4.0 beta (b 4.0.0.740) of ANTS Profiler and am blown away.

Installation

Installation was a breeze.  The 4.0 installer saw my existing 3.2 install and “upgraded” it; however, I was a bit surprised to find that the 3.2 sat side-by-side with 4.0.  That’s PERFECT, actually, and I hope they plan to keep it that way.

ANTS 4.0 -- Installed!

First Run Through 4.0

I’d like to start off by saying the new profiler startup UI is fantastic.  The prior “multi-step” wizard was great and easy to work through; however, I really like seeing everything on the first page.  Simply set the options and click Start. 

Profiler Settings - click for full image
(click for full image)

In addition, the quick access to additional performance counters, such as page requests and memory usage is really helpful.  I’m curious if additional performance counters can be added or if the list (see below) is the only ones handled by ANTS. 

Once things are rolling, the results come pouring in.  Just like with 3.2, 4.0 has detailed line level data—percentages per called line, hits, etc.  Very useful information.

However, the new call trees are sweet!  Why look at spreadsheets and lines when a graphical representation is available?  I have to find ways to boggle coworkers with these. ๐Ÿ™‚

My understanding is (I haven’t RTFM’d yet) is that the call trees display both your code (those that are bolded) and the managed code from .NET and called libraries (those that are tinted).

From here, I can see that a good deal of my slow down querying AD is coming not from the top level code, but from the Ldap code in System.DirectoryServices.Protocols and that the wait caused by that is the biggest hold up in all of Session_Start.

Another cool feature is the live performance counter view while you’re profiling.  This perfmon look into your application’s performance allows you to pause and checkout spikes (or unexpected dips) in any of the locked counters.

Counters graph.

To see the line-by-line details, simply drag the mouse along a section of the graph to select it.  ANTS will zoom in on just that area.  You can see the “highlighted” area below in blue.

Line Graphs, Zoomed In

That spike can be diagnosed in the line view—one of our methods is that doesn’t call very often (42 times) is taking a HUGE amount of time due to another that is calling 1000+ times.  Time to drill into that code and find a way to unloop it.

Conclusion

ANTS 4.0 seems quite a bit faster than 3.2 profiling the couple of .NET 3.5 web projects that I had sitting around in development.  In the past, I tended to avoid running ANTS against local Cassini projects; however, this kept up pretty well (though I think it does explain the LdapConnection latency).

It also appears that 4.0 can profile remote IIS instances (at least it doesn’t refuse it like 3.2 does); however, I haven’t quite gotten that working with the port settings (more to learn).

I haven’t hit all of the features yet, but I’m very impressed with the new look and feel, added “while you profile” live features, and the call trees. I can’t wait for the next beta and/or gold release—it’s looking good!

Resharper 4.0.1 Beta Released

August 4, 2008 Comments off

Since the 4.0 release, the JetBrains team has been working diligently towards the 4.0.1 release.  According to Confluence, there are several hundred bug fixes between 4.0 diamond and the current build (#917) of 4.0.1.

What’s new with 4.0.1?  According to a newsgroup post from Ilya, the 4.0.1 updates revolve around bugfixes; I haven’t found any indication of additional features.  I haven’t scanned through all of the JIRA cases yet, but there’s a huge volume of “fixes”—which surprises me.  R# 4.0 has been running like a dream for me.

I’m installing 4.0.1 beta (marked “works here”) now; the joys of testing!

IQueryable Methods on ActiveReports ControlCollections

I’m currently working on a project with an extremely complex, multi-page report.  Unfortunately, a customer requirement was EXACT typography to the “Excel” report and there are hundreds (literally) of data points randomly on the page. 

There isn’t a good way to iterate through the results (it’s a very detailed grade card for elementary students) and still match the layout requirements.

So, I went about “drawing” it out—lots of Label controls, lines, boxes, and such.  To save myself a bit of time assigning DataFields, querying results, etc., I opted for a different kind of iteration—control iteration.

My schema was simple: q#i#, for the quarter and the primary data point of the report, the indicator Id.  Since my business object, a Report, was already assigned to the ActiveReport document, I could simply iterate away!

Unfortunately, if you try to determine if the detail.Controls (a ControlCollection) contains a control and it doesn’t exist—it doesn’t simply return null, it throws an exception.  In addition, the ControlCollection doesn’t have an Exists or a FindControl method.  So, you’re stuck catching exceptions.

foreach (var indicator in _indicators)

{

try

{

var indicatorHeader =

string.Format(“i{0}”, indicator.Id);

((Label)detail.Controls[indicatorHeader]).Text =

IsSpanish                                                                           

? indicator.SpanishText                                                                          : indicator.EnglishText;

}

catch (Exception)

{

continue;

}

}

Unfortunately, that destroys performance—especially with hundreds of iterations (of indicators).

There’s a way around this, at least in my opinion.  Instead of addressing the controls as part of the details.Controls ControlCollection, use a custom IQueryable collection.

Begin by adding a private variable to the report to hold the controls.  In my case, all of the controls I’ll be modifying are Label (of ARControl) controls.

private IQueryable<Label> _controls;

On my ReportStart (I’m sure I could use another method, but since these are static controls, that seemed a good place to start), dump all Label controls into a generic List object (because you cannot add into an IQueryable).

var controlList = new List<Label>();

foreach (var control in detail.Controls.OfType<Label>())

{

controlList.Add(control);

}

_controls = controlList.AsQueryable();

OR, if you want to get fancy and save a few objects:

_controls = detail.Controls.OfType<Label>().AsQueryable();

At this point, your _controls object has all of the standard LINQ goodness.  Our foreach now looks like:

foreach (var indicator in _indicators)

{

var indicatorHeader =

string.Format(“i{0}”, indicator.Id);

var indicatorControl =

_controls.SingleOrDefault(x => x.Name == indicatorHeader);

if (indicatorControl != null)

       {

              indicatorControl.Text = IsSpanish

? indicator.SpanishText

: indicator.EnglishText;

}

}

The entire block can be wrapped in a try/catch—rather than each “object check”.  The report also runs almost 100x faster.

IE6 Causes Z-Index Nightmares…

Rather than update the post from yesterday, this chaos deserves it’s own post.

Yesterday, I discussed layering Modal Popup Extenders with the Update Progress controls.  In IE7, FF3, and, well, most everything except IE6, it works like a champ as-is.

The “bug”?  After quite a bit of research, the problem revolves around the following issues:

  • lack of support for the { position: fixed } property,
  • lack of support for the { right; bottom} properties,
  • … unreliable suport for {height: 100%, width: 100% } properties,
  • general pain and suffering
  • <SELECT> tags (or ASP:DropDownList objects) exist above any other z-index,

I’m sure there were other issues.  Really.

After spending a good part of the day trying code, looking it up on QuirksMode, and trying again, I have somewhat of a solution; however, I still greatly dislike how it works in IE6.

On the MasterPage, I have a single UpdateProgress that isn’t associated to a specific UpdatePanel.  Therefore, it’ll catch all Async postbacks (and I only have ONE UpdateProgress control).

<asp:UpdateProgress

runat=”server” DisplayAfter=”100″ ID=”UpdateProgress”>

<ProgressTemplate>

<div class=”UpdateProgressModalBackground”></div>

<div class=”UpdateProgressPanel”>

<h3>Please wait…</h3>

<img src=”Images/ajaxbar.gif”
alt=”Please wait…”

style=”text-align: center; width: 100%; height: 10px; />

</div>

</ProgressTemplate>

</asp:UpdateProgress>

This, again, references our UpdateProgressModalBackground and UpdateProgressPanel styles.  These two styles are unchanged from the post yesterday.  Here they are again for reference:

/* UpdateProgressPanel is above EVERYTHING ELSE,

even other modal popups */

.UpdateProgressPanel

{

       z-index: 99999999;

       background-color:#fff;

       color:#fff;

       width: 200px;

       text-align: center;

       vertical-align: middle;

       position: fixed;

       bottom: 50%;

       left: 45%;

       padding: 10px;

       border: solid 2px #5D7B9D;

}

 

.UpdateProgressModalBackground

{

    z-index: 99999998;

    background-color: #6D7B8D;

    position: fixed;

    top: 0;

    left: 0;

    height: 100%;

    width: 100%;

    min-height: 100%;

    min-width: 100%;

    filter: alpha(opacity=50);

    opacity: 0.5;

    -moz-opacity: 0.5;

}

The UpdateProgress and these two classes work just fine in IE7+, FF2+.  So, now to fix IE6..

So, what’s the difference in IE6?  Well, we can’t use the positioning attributes in the above classes–-they won’t work properly. 

Issue #1 – Fitting the Popup and Background Without Positioning Attributes

Searching the web, I found an article by Damien White discussing his his same pains with this.  His solution involved using the IE-specific CSS “expressions” to calculate the height and width of the window.

height:

expression(

        document.documentElement.scrollTop +

        document.documentElement.clientHeight + “px”);

 

width: expression(document.body.clientWidth + “px”);

However, at least for me, Damien’s expressions wouldn’t handle scrolling down the page.

Damien explains:

The thinking behind this was to take the window height (which document.documentElement.clientHeight gives us) and then add the scroll top position, which will give us the upper portion if the user scrolls up.  The problem shows itself when the user scrolls down; that area is not covered.  The good thing about this is that I didn’t need to mess with the body height, but the solution isn’t optimal in the long haul.

That’s a bad deal because that’s the whole point!  Reading a bit more, there was a comment from Kunal Mukherjee on Damien’s post that solved the problem.

Kunal’s expressions looked at the scrollHeight of the window as compared to the offsetHeight and returned the larger.

height: expression(

document.body.scrollHeight > document.body.offsetHeight
? document.body.scrollHeight
: document.body.offsetHeight + ‘px’ )
;

Actually, that works really well. Cool.

Finally, I’d recommend, as Damien did, breaking out your CSS into two files—one for “IE6” and one for everyone else.  This is easily done using the IE-specific conditional statements.

<!–[if lt IE 7]>
<link rel=”stylesheet” type=”text/css” href=”App_Themes/ie6/ie6.css” />
<![endif]–>

I also included !important flags on each of the properties in the ie6.css file—just to be safe.

Issue #2 – IE6 Pushes <SELECT> tags above everything else…

This is where the solution gets dicey; however, I’m relying on Kunal’s solution again.  In his comment, he pointed out a way to hide <SELECT> tags in IE6 without causing the disappearing act that the ModalPopupExtender causes—cover them with an IFRAME.

To me, this hack seems… sketchy at best, but it works.

In the ProgressTemplate of the UpdateProgress control, add in the IFRAME.

<iframe id=”UpdateProgressHideSelect”></iframe>

In the default.css (or the non-ie6.css, whatever you’ve called it), I recommend setting the iframe’s style to {display: none}—it isn’t needed outside IE6, don’t render it. ๐Ÿ™‚

On the ie6.css, add the UpdateProgressHideSelect in—along with another expression to place the iframe over the entire page (like the standard BackgroundCssClass of a ModalPopupExtender):

#UpdateProgressHideSelect

{

    z-index: 15000;

    position: fixed;

    top: 0;

    left: 0;

    background-color: #fff;

    border: none;

    filter: alpha(opacity=0);

    -moz-opacity: 0;

    opacity: 0;

    height: 100%;

    width: 100%;

    display: inline !important;

}

 

* html #UpdateProgressHideSelect

{

    position: absolute;

    height: expression(

document.body.scrollHeight > document.body.offsetHeight

? document.body.scrollHeight

: document.body.offsetHeight + ‘px’);

}

The z-index of 15000 for the iframe ensures that it appears above the normal 10000 of a ModalPopupExtender panel; however, under our crazy high UpdateProgress control.

Problem solved—for now.

Here’s how they look, side by side.

FireFox 3:

FireFox 3 Output

Nice and clean, properly centered given the size of the box and window size.  Can see drop down lists and MPE behind the UpdateProgress, but cannot access them.

IE 7:

IE7 Output

Output as expected and where expected.  Can see drop down lists and MPE behind the UpdateProgress, but cannot access them.

IE 6:

IE6 Output

Output as expected—basically where expected.  Drop down lists are hidden behind the IFRAME to prevent input.  Other controls are visible, including the MPE, but behind the background.

What fun!

AnkhSVN 2.0 Released – How’s it look?

When I first started using Subversion full time for all of my personal projects, I stuck with the VisualSVN server and AnkhSVN as a Visual Studio client.  Both were free, easy to install, and easy to use.

However, after a few weeks, the AnkhSVN client could almost be called “annoying.”  It trampled over the existing SCC plugins for SourceSafe (for work) and made a mess out of several of my project uploads.  I ended up going back to using TortioiseSVN and doing everything through Explorer.

When AnkhSVN 2.0 was released, I figured I’d give it another shot.

The site claims quite a bit—including several unique additions:

  • Pending changes window; subversion status and commands available in one place
  • Full support for Visual Studio 2005 and 2008; AnkhSVN is now a SCC package instead of just an addin
  • Better log viewer
  • Merge support
  • Property editor
  • AnkhSVN now supports most project types previously unsupported via the SCC api
  • All solution explorer actions (rename, copy&paste, drag&drop) keep subversion history now
  • Enhanced build process and setup
  • Automatic check for updates
  • And last but certainly not least end user documentation

All of those look great—especially the SCC package and changes window.  But how does it compare once installed?

After installation and starting up VS2008, everything looks normal.

Brief Look

Pending Changes Window

The new pending changes window is FANTASTIC—much improved over the old 1.x versions.  I did run into a snafu when trying to resize the window where the scrollbars didn’t update on the screen; however, I’m not sure if it’s a VSS or AnkhSVN issue.

SCC Package

Under Options > Source Control, AnkhSVN shows up just like it should.

What does boggle me is that all of the Subversion commands and menus are available no matter what—even when the VSS SCC is enabled.  It still has the stink of VSS and SVN trying to step on one another (“pick me! control your project with me! no, I’m better! pick me!”).

Log/History Viewer

I really like the new history viewer.  It’s clean and easy to read; however, if you change the options at the top—there doesn’t appear to be a way to “change it back” and see the history again, close the view and review.

Annoyances

  • Opening a project from Subversion (File > Subversion > Open from Subversion) will open a project just fine, copy it down, but never opens it.  You have to go back and open the solution after it’s created the local structure.  Not huge, but annoying.
  • When viewing history; you cannot view the history of a single file (that I’ve found) in the Repository Explorer. 

I’m still planning to give it a whirl for the next couple of weeks and see what happens.  Hopefully over a couple weeks I’ll have more time to code—it’s been a busy July so far!

Wrapping TabPanel Tabs With A Simple CSS Change

July 10, 2008 1 comment

The last few weeks have been filled with taking an old ASP legacy application and updating it to ASP.NET.  Fun stuff and not to challenging.

However, a “feature” of the AJAX Control Toolkit’s TabContainer finally hit a nerve.  In the past, I’ve ignored the fact that I couldn’t “wrap” the tabs or set how many rows of tabs to create.  I chalked it up to an annoyance and designed applications with this in mind.

After hunting through the Control Toolkit’s source code, the problem is simple.  There’s a line in the CSS explicitly telling it not to wrap.

Well, recompiling the toolkit can get annoying and hurts mobility of your applications—it’s no fun to bundle “custom” copies for a simple styling change.

.ajax__tab_header

{

    white-space: normal !important;

}

That will override the nowrap that is built into the Toolkit’s CSS.

Hopefully, someday, this will be a boolean property on the TabContainer control.

ReSharper 4.0 – Cool Features

There are quite a few new features to ReSharper 4.0 that are great, but it’s the little things that really can impress and speed up usage.  A few of my favorites are below.

camelHumps. ๐Ÿ™‚

ReSharper now supports Go To > and statement completion according to camel casing.  If you’re like me, you tend to write normal sentences in camel case—it’s just habit.

Using the camel casing, it picks up the variable I just created, not the class.

Lambda support.

I’ve become addicted to the simplicity of lambdas—they express intent and you can read them like sentences.  ReSharper 4 does an excellent job of digging into the anonymous type and pulling up IntelliSense information.

ResponseChoicesController()

.SelectOne(x =>

x.IsDefault &&

x.ResponseTypeId == responseTypeId)

From the ResponseChoicesController, select one that meets the requirements that IsDefault is true and ResponseTypeId is equal to the specified responseTypeId.  To me, and I’m sure I’m odd, that is easier to read than the “written” LINQ code.

Convert Static to Extension.

This is FANTASTIC for revamping existing code to take full advantage of the .NET 3.5 Framework.  I’ve been working on a project the past few weeks to migrate a .NET 2.0 project using Enterprise Library 3 up to 3.5 and LINQ-to-SQL and this addition has been fantastic to move data and business logic into controllers and the LINQ data context.

 

ReSharper 4.0 is now RC!

June 5, 2008 Comments off

The first RC for ReSharper 4.0 is out—pick it up! Nice!