free geoip Jayson's Blog - jaysonKnight.com
jaysonKnight.com
Welcome to my corner of the internet

Jayson's Blog

  • CS Tidbits #19: Enable Tag Cloud Topic Count

    No lengthy screencasts today, just a quick and easy way to add an enhancement to your site that I believe users will appreciate.

    I'm all about numbers, I don't know why.  I like to see how many posts a blogger has made to their site, how many comments have been made, etc.  It's a useful barometer (for me at least) so see if it's an active blog or not, i.e. if someone has made a bazillion posts but only has 5 comments, then something is obviously wrong.  If there are only 50 posts but it has a bazillion comments, more than like the owner has given up due to comment spam.  Etc.  Only the finest blogs make it to my aggregator, and the following is (a one of many) useful metric to gauge what's going on over at a particular blog.

    In this evening's tidbit (which will be the first of a Tidbit mini-series to add this type of statistical information in various places on your site) we'll add a Topic Count counter to each tag in your tag cloud.

    It's dead simple.  Any control that declares a <Blog:TagCloud> control (or any type of tagcloud, i.e.<CS:TagCloud>, <Galleries:TagCloud>, etc) exposes a ShowTagCounts property, which they inherit from the CommunityServer.Controls.BaseTagCloud control.

    To enable the topic count, find any TagCloud control in your /skins/<skinThatContainsTagCloud> and find the TagCloud control declaration.  Add the following attribute: ShowTagCounts="true" before the closing wicket and topic counts will show up similar to the image on the left.  It's that easy.

  • Blog Stats Take a Huge Dive -- Did Google Reindex?

    [Update]:  Apparently I am in violation of Google’s Free Search Agreement by adding my own custom search box querying google without including a Google logo. By the time I realized I needed to include the logo, it was already too late..  So, search removed…hopefully I’ll be reindexed soon.  Whatever google.

    I’m confused.  I’ve been averaging ~350 unique visitors a day for the past few weeks; upon checking my stats for the day (via StatCounter), I’m at a whopping 16 uniques for the day.  Furthermore, after googling a few keywords that I know I’m number 1 for (or at least in the top 10), I’m nowhere to be found (try either ‘jayson blog’ or ‘jayson knight…I’ve owned those number 1’s pretty much sense the inception of this blog)…what gives man?  Furthermore, using the ‘Search this site’ functionality that I added a few days ago (sends a search to google using the inurl google keyword) for something as mundane as ‘string’ (which should yield a dozen or so hits from my blog) points towards someone’s blog I’ve never heard of, and certainly has nothing to do with strings.  Even stranger than that, when you click the link in google, it just goes to my main feed page, not the mentioned post in the summary, and the link listed below (www.travisnelsa.com/…) is irrelevant.  I’ve changed nothing on my site to effectively have had it vanish from google completely.  Anyone have any idea wtf is going on?  It’s quite maddening…

  • ASP.NET Performance Tuning/Analysis

    A role at my workplace that I've noticed a huge need for is one of a performance architect/analyst, which is a role I have been attempting to play a more active part in.  By the very nature of the .Net framework and how much work it does for us, I think many of us throw performance considerations by the wayside and just assume that it will work when rolled out into production.  Perhaps more times than not this is indeed the case initially, but inevitably performance issues are going to crop up and it will be time to fire up a production debugger/profiler and some of the CLR performance monitor counters.  A little background may be in order...and this is from a corporate IT slant.

    There are developers that get their jollies by designing slick interfaces/GUI's as invariably this is the only part of the application that the end user is going to see, and 9 times out of 8 when giving a demo to a corporate sponsor, the only remarks that will be made about the application concerns the GUI, i.e. “it looks great!” or “can it do this?”, etc.  I am not one of these developers, mainly because I cannot design my way out of a cardboard box.  I am not saying that frontend design/performance isn't important, but usually that kind of stuff is in the “here and now”, and can be dynamic in nature and easily changed.  What can't be changed down the line is the plumbing of an application, and this is where I feel most at home.  Every application needs built in tracing/logging functionality, diagnostics abilities, and performance monitoring facilities.  Peformance guidelines need to be adhered to, tests in labs will never simulate the real environment in which your application will roll out.

    Recently, an IIS cluster of ours started misbehaving badly and the aspnet_wp needs to be killed and restarted half a dozen times a day to get everything running smoothly again.  The only way our infrastructure team knew what was going on is when the phone calls started coming in.  This kind of reactive “user based monitoring” simply isn't acceptable.  The culprit of this was the aspnet_wp racing the processor and consuming quite a bit of memory on the machines, and the server becoming unresponsive.  Through no fault of their own, our infrastructure team simply didn't have the knowledge as to how to troubleshoot .Net CLR/ASP.NET production issues.  Given that this is something I've always been interested in, I decided to step in and have a look around.  There are numerous ways an ASP.NET application can be tuned up post-deployment via the machine.config file, in addition to guidelines that should be followed pre-deplyoment while coding.  I will go over a handful of both.  In this situation, the first step we took was to try and isolate the issue by removing layers of complexity one by one (we don't have a full blown test lab here, so we had to do this in production, both after hours and during a full load to get reliable numbers).  Our cluster is only 2 machines watched over by Application Center 2000 (of which I am most certainly not an expert, however one thing I did learn about app center is that while it does replicate the IIS 5.0 metabase around, it does not replicate the machine.config to member machines...I wonder if this is different with IIS 6.0 as the machine.config file's processModel section is built in, my guess is that these settings would indeed be replicated in IIS 6.0), so the first thought was to remove app center and isolate the issue down to one machine.  Enter the machine.config file, and the processModel section.  Here is some useful information concerning machine.config and how it relates to ASP.NET performance tuning, followed by a brief overview of some of the .NET CLR performance counters that ship with the .NET framework.

     

    Reactive Performance Monitoring Guidelines

    ASP.NET Configuration Settings:

    The processModel section cannot be overridden in either an App.config or Web.config file, it is system wide and applies to every web application on IIS 5.0 (6.0 introduces application pools which alleviates this constraint).  Also, when any other section of the machine.config file is changed, aspnet_wp will recycle itself...this is not true with the processModel section as it's read by the unmanaged aspnet_isapi.dll.  Editing the processModel section requires an IISRESET command to be issued on that machine.  Standard HTML comment syntax within the processModel section is not allowed, and will result in a parsing error, I learned this the hard way a while back, so it's worth mentioning here.

    I'll be honest, the default values for each processModel process recycling related attribute suck.  These should not be used in a production environment as they lend themselves to the aspnet_wp spiraling rapidly out of control.  In fact, the only attribute with even some semblence to a normal configuration value is memoryLimit, and even this is way off (the default value is 80% of physical RAM before the aspnet_wp recycles itself, for a bare bones web server that *might* be enough, but I doubt it).  Lowering this value to 60% or less is what I would recommend.  The aspnet_wp recycling itself (although resource intensive in it's own right) is much more graceful then getting out of memory errors.  A quick note about the aspnet_wp recycling itself:  any requests executing on the recycled thread will be served before the aspnet_wp is quietly killed off, and all new requests are immediately dispatched to the newly spawned thread, this is completely transparent to the end user as they won't lose session state, and applications state is transferred over to the new thread.  For initial troubleshooting in my case, I set this value to 20%, which on this machine is ~200 megs of memory.  The issue still persisted though, more on that later.  There are a couple of other recycling related attributes worth mentioning, as their default values IMO are unacceptable (bear in mind that while our web apps are 24/7, they are only heavily traficked for about 12-15 of those hours).

    The most common processModel attributes to tweak are:

    • timeout -- the default value is “infinite“, meaning the aspnet_wp will never be restarted automatically.  Again, while it is expensive resource-wise to spawn a new aspnet_wp process, in order to look out for its own health, the aspnet_wp needs to be recycled on a pre-determined basis.  When left to its own devices, something can and will eventually go wrong.  Only careful monitoring can determine this value, though I recommend nothing less than 60 minutes unless things are really going haywire, in which case it is probably time to visit other steps that I will mention in a bit.  This is probably the best proactive setting in the processModel section. 
    • idleTimeout -- the default value is “infinite“, meaning the aspnet_wp will never be restarted, even if it's at a standstill.  In my case, I know when an acceptable time to kill off the aspnet_wp is; it's a safe bet that after 20-30 minutes of inactivity on our machines, no one is hitting them (and it's probably late in the night), so I can safely shut down the aspnet_wp after this amount of time.  Obviously, this would not work for a full blown 24/7 operation, thus this attribute is meaningless for that scenario. 
    • requestLimit -- once again, the default value is “infinite“, meaning the aspnet_wp will serve as many requests as are coming in.  For obvious reasons, this value needs to be profiled for and set accordingly per server resources.  In my case, I knew this didn't need too much fine tuning as this box never saw more than 200 concurrent requests (given the resources on the machine, 200 cocurrent requests should be handled easily). 
    • responseDeadlockInterval -- I personally have only run into issues with this setting once, and it was due to a long running SQL query running on the aspnet_wp thread.  The default for this setting is 3 minutes, however the query ram longer than that, so eventually it timed out.  Of course the real fix for the issue there would have been running the query as a .bat file, firing it off asynchronously, etc. but I thought it was worth mentioning; by default, any process taking longer than 3 minutes on the aspnet_wp thread will cause issues.

    Our web server is a dual processor machine, however due to the fact that the machine.config file was in its' default state, this meant that the webGarden attribute was set to “false“ and only one processor was being utilized.  Glancing at the Processor performance counter verified this.  This is not something that can just be switched on in production though, there are a couple of caveats of enabling a web garden for ASP.NET, the most important of which is InProc session state will not work on a webGarden, you must use either StateServer (aspnet_state.exe) or SqlServer to persist session state.  This is due to the threading model introduced in SMP systems, and is not a shortcoming of ASP.NET.  This also means that the Session_End event in Globas.asax isn't fired correctly, so if you have any cleanup code there, it will need to be moved elsewhere, as a caveat of this, Session.Abandon of course will not fire Session_End.  A nice side effect of using either of the out of process models is that they are durable through aspnet_wp recycles and IISRESETS.  If you choose to use a StateServer, make sure you configure the ASP.NET State Server Service to start up automatically, and to use either a domain account or a network account for logging on to the network.  Some other considerations for using a StateServer are:

    • In a web farm, make sure you have the same in all your web servers. See KB 313091 on how to do it.
    • For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm. See KB 325056 for details

    If you decide to go with SQLServer session state, take note of the following:

    • If you specify integrated security in the connection string (e.g. "trusted_connection=true", or "integrated security=sspi"), it won't work if you also turn on impersonation in asp.net. Unfortunately, this bug
      isn't reported in KB yet. (There is a QFE fix for it.)
    • For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm.
      See
      KB 325056 for details.

    Offloading session state to another machine will also free up valuable resources on the web servers, albeit at a performance hit for cross process marshalling calls.  Of course, SqlServer session state is the most durable, but suffers from the biggest performance hit, this would only be used in the most critical of applications.  In any event, choosing to enable the webGarden attribute will need to be tested thoroughly, and if you are on 1.0 of the framework, be mindful of this article (if an object is not marked as Serializable, trying to session it will result in an error...this has been remedied in 1.1).  We are still in the conceptual phase for rolling this out at work, though I have successfully implemented it elsewhere.

    ASP.NET/CLR Performance Counters:

    After tuning up your processModel section, the need for benchmarking is apparent.  The .Net CLR ships w/ dozens of performance monitoring counters.  I will attempt to give a high level overview of what counters to use, what to look for, and guidelines that have served me well.

    In our case, it appeared to be a memory issue, so after throttling aspnet_wp to only consume 20% of physical memory it was time to see what was going on under the hood memory wise.  A common assumption is that since the CLR is garbage collected, memory “leaks“ cannot happen.  Generally speaking this is correct, however if improper allocation of objects is made via code, or improper caching implemented, or InProc session state/ViewState abused, memory issues will indeed crop up.  The best counter to monitor for memory consumption is Process/aspnet_wp/Private Bytes.  These bytes are privy only to the aspnet_wp and cannot be shared among other processes.  If this number rises and the .Net CLR Memory #Bytes stays flat, this is a good indication of a memory leak.  An excellent paper by Thomas Marquardt should be read by anyone needing to gather information from .Net performance counters, and does a more thorough job of explaining the monitoring process than I could ever hope to do.

    Essential performance counters include the following: 

    • .NET CLR Exceptions/# of Exceptions Thrown and # of Exceptions Thrown per Second.  Exception handling is expensive, and the old adage of only throw exceptional exceptions holds true here.  Be advised that HttpResponse.Redirect, Server.Transfer, and Response.End all throw an uncatchable ThreadAbortException, so use these counters in conjunction with ASP.NET Applications/Errors Total to see if the exceptions being thrown actually bring the application down.  Generally speaking, the # of Exceptions per Second should be around 5% of the ASP.NET Applications/Requests per Second counter. 
    • .NET CLR Memory/# Bytes in All Heaps (use this in conjunction with Private Bytes) /% Time in GC (this average should be 5%, though spikes are not uncommon) and /Large Object Heap Size (any object over 20kb at time of creation is stored on this heap, and they are not promoted through the GC's generations of collection, an abnormal ratio of this size to #Bytes in All Heaps should set off a flag).  In addition, the # Gen 0,1,2 Collections counters should be monitored.  The ratio of collections should be 10 gen 0's per every gen 1, and 10 gen 1's per every gen 2.  Gen 2 collections are very expensive, and also suspend all threads until it has completed.  Note that there is a way around this, which I will mention later (the framework actually ships with 2 GC's, one geared towards workstations, and one geared towards servers, workstation is used by default). 
    • ASP.NET/Request Excecution Time and Worker Process Restarts.  These are pretty obvious in their functionality and can be used to identify a bottleneck/processModel inflicted restarts respectively.  In particular, Worker Process Restarts can be used to fine grain the processModel tuning mentioned earlier. 
    • ASP.NET Applications/Errors Total, Pipeline Instance Count, Requests Executing, and Requests per SecondErrors Total represents the number of unhandled exceptions resulting in a runtime error, this number should be low in comparison to # Exceptions ThrownPipeline Instance Count can be almost any reasonable number, however it should remain virtually unchanged, if this number climbs rapidly it's a sign of bottlenecks downstream (i.e. SQL Server denying connections).  Requests Executing and Requests per Second can be used to identify server issues, these numbers should be low and consistent. 
    • ASP.NET Applications/Cache [all].  These counters will give some insight as to how effeciently Caching is being utilized, and is a good indicator as to where the application can be further tuned for caching effenciency.  I will speak more about page caching in a future post, but it bears mentioning that if the Output Cache Hit Ratio is low (below 80%), the application needs some work on Page caching.  The Cache Total counters reflect both internal ASP.NET caching as well as external use of the cache via the exposed API's.  The Cache API entries reflect only the external use of the exposed caching API's.  The main key to remember here is high ratio, and low turnover.  Caching objects/pages is a good thing, but if taken to an extreme can do just as much harm as good.
    • Memory/Available MBytes.  If the GC is doing its' job correctly, this number should fluctuate around a consistent number (+- 100 megs or so), this counter is impacted by number of connections, and the thread pool for database connections (among other things).  A spike in number of web connections or excessive database connections will cause this number to climb.  A sharp spike from time to time won't be uncommon, just monitor the GC counters if you notice an influx of activity on this counter.
    • Process/aspnet_wp/% Processor Time, Private Bytes, and Thread Count% Processor Time can be used to identify cases in which the aspnet_wp is racing the processor.  Prolonged values above 75% should be monitored closely.  I believe if you have more than one processor, the value can actually exceed 100%, but this needs to be divided by the number of processors (i.e. if you have an 8 processor box, and see a value of 400%, it's actually utilizing 50% of the cumulative processors' time).  Private Bytes should remain steady, a slow increase in this number needs to be watched very carefully and correlated with .NET CLR Memory counters.  Thread count should remain at steady number if your application is single-threaded.  Excessive locks or asynchronous calls in your code could cause this number to fluctuate...too many threads will severely hinder performance. 
    • Web Service/Current Connections.  This is a baseline to see just how busy your server really is.  In the controlled corporate IT world, this number is predictable and can be used to calculate various server resource consumption metrics.
    • It's also a good idea to monitor all of the .NET CLR Data counters.  There is a known issue of these counters freezing, if you close the monitoring window for 1-2 minutes, they should start back up again.  This is a good way to check and see if connection pooling is behaving correctly.  The number of connection pools should roughly equal the ASP.NET/Applications Running counter, if it's substantially higher than this, something is wrong with the way your applications are building the pool.  Remember, .Net uses a kind of primitive way to lump connections together into a pool; it looks for connections using the same connections string.  If you are dynamically building connections strings and they don't match 100% to another string (even if it's hitting the exact same database), .Net will spawn a new thread pool, and this is expensive resource-wise.

    In addition to monitoring these counters:

    • A stable benchmark for comparison needs to be gathered.  Do not do this in the lab or a controlled environment, use your production server(s).  Performance counters are indeed invasive, but this is something that must be done prior to monitoring an unstable machine.  If you only monitor a server when it is misbehaving, you won't have anything to compare it to.  I recommend 2 baseline benchmarks; one at a near idle (in my case, I came in on a Sunday and sampled 2 hours of data), and one during a normal stress load (don't do it before lunchtime...towards the end of the day is usually good).  Microsoft performance counters can be exported to Excel, so you have a wealth of data manipulation at your fingertips right there.
    • If you are running a multi-processor server, use the server GC that ships with the .Net Famework (mscorsvr.dll).  Two articles here and here give more details on when/how/why to do this.  Here is a newsgroup posting on how to do it with an environmental variable.  I have no experience with this and only just learned of it recently, but it seems like a good idea, and I know of at least one blogger who has had some luck with it.
    • In the end, experience monitoring both healthy servers and unhealthy servers is the key.  While I'm not suggesting that you run out and attach every performance counter you can to your servers, it's a good idea to start monitoring early and regularly.  You can schedule logs to run at given intervals and notify operators of issues using the performance monitoring tool (perfmon).  And of course, .Net provides classes to build your own counters if you wish, but that is outside the realm of this post.

    I still haven't isolated exactly what is going with the server in question, but through a series of monitoring sessions it's been easy to eliminate what is not the issue.  In the end, I believe the issue is going to relate to this Q article.  If not, then it's back to the drawing board.  At least I'm armed with the tools I need to track down whatever the underlying issue really is.

    In a future post I will go over some proactive coding best practices to prevent some of the situations mentioned in this post.

    Useful Links:

    CLR Memory Performance Counters

    Performance Counters for ASP.NET

    Microsoft .NET Framework Performance: Tips, Tools, and Techniques

    Performance and Diagnostics

    processModel Element

    Configuring Session Cache Servers

    ASP.NET Performance Monitoring

    Performance Considerations

    Operating .NET-Based Applications

    Production Debugging for .NET Framework Applications

  • Common .Net Interview Questions

    Here is a list of some common questions I ask potential candidates when screening for interviews (and no, I don't expect answers as in depth as I've listed here):

    What are some of the objects exposed by the .NET framework that lend themselves to asynchronous method invocation, and what are a few ways architecturally to use these objects? What is the name of the interface used primarily as a way to check on an asynchronous method call?

    The simplest way to execute a method asynchronously is to start it with BeginInvoke, do some work on the main thread, and then call EndInvoke. EndInvoke does not return until the asynchronous call completes. This is a good technique to use with file or network operations, but because it blocks on EndInvoke, you should not use it from threads that service the user interface.
    Waiting on a WaitHandle is a common thread synchronization technique. You can obtain a WaitHandle using the AsyncWaitHandle property of the IAsyncResult returned by BeginInvoke. The WaitHandle is signaled when the asynchronous call completes, and you can wait for it by calling its WaitOne. If you use a WaitHandle, you can perform additional processing after the asynchronous call completes, but before you retrieve the results by calling EndInvoke. Bear in mind that the call to EndInvoke will block the calling thread unless the asnychronous method call has completed.
    You can use the boolean IsCompleted property of the IAsyncResult returned by BeginInvoke to discover when the asynchronous call completes. You might do this when making the asynchronous call from a thread that services the user interface. Polling for completion allows the user interface thread to continue processing user input, thus this is the preferred way for a GUI to call an method asynchronously.
    If the thread that initiates the asynchronous call does not need to process the results, you can execute a callback method when the call completes. The callback method is executed on a ThreadPool thread. To use a callback method, you must pass BeginInvoke an AsyncCallback delegate representing the method. You can also pass an object containing information to be used by the callback method. For example, you might pass the delegate that was used to initiate the call, so the callback method can call EndInvoke. If a callback has been specified on the BeginInvoke, it will be called when the target method returns. In the callback, the EndInvoke method is used to obtain the return value and the in/out parameters. If the callback was not specified on the BeginInvoke, then EndInvoke can be used on the original thread that submitted a request.
    Name a design pattern you've used on a regular basis, and explain why you've used it and how it lent itself to accomplishing the programming task you were trying to accomplish. (there are numerous answers, if they name one and can talk about it for a minute or 2, that should suffice). Common ones will be Singleton, Factory, Observer, Asynchronous, Disposable, and Controller.

    What are the similarities/differences between interfaces and abstract classes? When and why would use either one, and name a specific instance when you would use one and not the other?

    Interfaces support multiple inheritance, whereas you can only inherit from one abstract class.
    Abstract classes support partial to full implementation, whereas interfaces only define a contract with no implementation.
    If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
    If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
    If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
    If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


    What are 2 ways to facilitate the passing of objects across application domains via reflection? IE, there are 2 seperate programming constructs that can be used to enable objects to passed across application domains, a default class by itself cannot be passed across app domains. HINT: one is an attribute, the other is a base class.

    You can mark the object with the Serializable attribute. Bear in mind that this will in turn make each and every member of the class serializable as well. If you need to implement partial serialization, inherit from ISerializable and just serialize the members you need to...or use the NonSerializable attribute on those members. An object that is serialized across application domains is done so as a copy of the object (similar to ByValue), so this can be an expensive proposition with larger objects.
    If you inherit from MarshalByRefObject, you will get the same desired end result, however instead of a copy of the object being transported to the remote application domain, a proxy will be created that facilitates communication between the objects. When an object derives from MarshalByRefObject, an object reference will be passed from one application domain to another, rather than the object itself.


    What are the 2 transport protocols that can be used in .NET remoting? What are the 2 transport payload types? What network scenarios are each combination best suited for?

    SOAP payload via HTTP protocol. The HTTP channel uses the SOAP formatter by default and hence can be used in scenarios where clients will access the objects over the Internet. Since this approach uses HTTP, accessing .NET objects remotely through a firewall is enabled by this configuration. Objects exposed in this way can easily be configured as Web Services Objects simply by hosting these objects in IIS. Clients can then read the WSDL files of these objects to communicate with the Remote object using SOAP. There is an associated performance hit as SOAP payloads are quite a bit larger than their binary counterparts.
    Binary payload via TCP protocol. The TCP Channel uses the binary formatter by default. This formatter serializes the data in binary form and uses raw sockets to transmit data across the network. This method is ideal if your object is deployed in a closed environment within the confines of a firewall. This approach is more optimized since it uses sockets to communicate binary data between objects. Using the TCP channel to expose your object gives you the advantage of low overhead in closed environments. This approach cannot be used over the Internet because of firewall and configuration issues.

    Last one...what are some of the key fundamental differences between C# and VB.NET?

    VB.NET doesn't support operator overloading.
    C# is case sensitive.
    C# instrinsically supports code comment sheets via XML tags.
    You can write unsafe (C/C++ style) code in C# code blocks.
    More explicit casting is necessary when writing in C#.
    VB.NET supports optional parameters.
    In VB.NET, parameters are passed by reference by default, whereas in C# parameters are passed by value.
    Method level vars must be initialized in C# (even if it's with a null type), whereas in VB.NET there is some leniency with this.
    VB.NET supports the With [typeName] construct, allowing for multiple actions to be performed on a type in one block.
    VB.NET does not support unsigned numeric primitives.
    VB.NET supports re-allocating an array (ReDim).

    Nothing too too complicated, but i feel they are .NET fundamentals.  Comments are welcome!

  • Incredible Commercial (Honda's Cog Spot)

    This is one of the coolest 2 minutes of video i have ever come across.  It's actually a bit dated (came out about a year ago).  It's a short spot for honda that features a virtually impossible scene using only parts from a honda car (no animation, no strings, 100% real, and the final cut is all 1 take, no edits).  Apparently it took 606 takes, which is amazing in itself.  It aired first in the UK, then spread on to other countries around the world, however it never made it to the US.  If you lived in the UK at the time it aired, you could have actually called the UK honda subsid, and they would have sent you a free DVD copy of it.  I have no idea why the US was left out of the fun.  I would think that the commercial would have done extremely well here, and i'm almost insulted that it never made it over.  It's impressive nonetheless, and I also have a high resolution version.  You get bonus points of you can (without digging up the answers on the internet):

    1. Figure out how they made the wheels roll impossibly uphill (50 points)
    2. Figure out how the windshield wipers move on their own (25 points)
    3. Name the celebrity voice-over at the end (100 super cool points)

    There is also a related movie floating around somewhere out there that features over an hour and a half of similar material, however i long ago lost the link to it...if anyone comes across it, please let me know.  Enjoy.

  • Using Anonymous Methods For Control.Invoke/Control.BeginInvoke

    One commonality shared by most Windows Forms applications is the need for a responsive UI; this means implementing some sort of threading scheme so that processes can run on background threads so as to not interrupt the user's workflow while using the various controls placed on the UI itself.  The caveat to this is that the CLR does not allow cross threading updates to classes that inherit from System.Windows.Forms.Control, i.e. the control cannot be updated from a thread that wasn't responsible for the creation of the control.  There is a pattern exposed by the BCL that enables this kind of programming:  You need to declare a delegate which will act as the pointer to the method to update the control, then in your main code block check for Control.InvokeRequired, and finally call Control.BeginInvoke passing in your delegate as the argument.

    The end result ends up looking something like this:

     

    public class Foo : Form { public static void Main() { Application.Run(new Foo()); } public Foo() { InitializeComponent(); } private delegate void ConsoleWriterDelegate(); private void DoSomeWork() { if (this.InvokeRequired) { this.BeginInvoke(new ConsoleWriterDelegate(WriteToConsole)); } } private void WriteToConsole() { Console.WriteLine("Writing to console via explicit delegate "); } }

    In this case, we've really just written a delegate simply for the sake of creating one.  You'll also notice that we aren't passing any parameters to the WriteToConsole method.  This is a simple programming idiom made more complicated than it actually should be.  Fortunately there's a delegate exposed by the BCL just for cases like this, System.Windows.Forms.MethodInvoker.  Couple this delegate with anonymous methods in C# 2.0 and we can make the DoSomeWork method from above much simpler:

     

    private void DoSomeWork() { if (this.InvokeRequired) { this.BeginInvoke(new MethodInvoker(delegate() { Console.WriteLine("Writing to console via anonymous method. "); })); } }

    For simple cross thread calls that need to interact with controls, this pattern is much simpler to implement and we get the added performance gains of using MethodInvoker.  This code idiom will also work with Control.Invoke.

  • CS Tidbits #26 -- Harness The Power Of Config File Overrides

    Now that Community Server 2007 has been released, it's time to fire up the CS Tidbits category again and see what I can come up with. Coming tidbits will still be geared towards site admins (making your site easier to use, simple tweaks and additions, etc), but I'll also go into some details about Chameleon, CS's long awaited skinning engine overhaul.

    Today's tidbit is one of the most commonly requested scenarios (I've covered it before): "I want to add a new menu tab/add a second blog/etc to my CS installation, how do I do that?" Fundamentally the concept is the same as in previous versions of CS...you need to modify your SiteUrls.config file which is where all the magic of URL rewriting is laid out. CS 2007 introduces the notion of override.config files, which in their simplest of forms take on the name of *_override.config where * is the name of the config file you wish to modify (of course you cannot apply any overrides to the web.config file seeing as it's a special file for the asp.net runtime), and you then use XPath notation to manipulate (or add) tags to your config files. I am by no means an XPath expert, if you are curious about the syntax and rules there are numerous resources on the web at your disposal, plus an entire army of experts over on CS.org who are happy to help out.

    The scenario I ran into was the following: I needed my CS site to remain unchanged at the root (http://jaysonknight.com shows the aggregate page), needed /blog to point towards my main blog, and have /feeds map to my external news section without having the application key in the URL. Note: this post assumes you've already configured both blogs in Control Panel before doing anything else.

    The first thing we need to do (which remains unchanged from previous versions of CS) is add the physical menu tab which links to the second blog. You must specify this value in the actual SiteUrls.config file, it cannot be specified in an override file. All override files are actually processed first by the CS runtime, so if you specify a new menu tab location in an override you have no control over the order it will appear in the menu, meaning it will show up first. In my case I needed it to be 3rd, so just add it after the first 2 <link> elements. Here's the line to add to the <navigation> element in SiteUrls.config:

     

    <link name="feeds" resourceUrl="feedshome" text="External News"
    roles="Everyone" applicationType = "Weblog" />

    Now we need to do the actual URL manipulation, so create a blank file called SiteUrls_override.config and add the following:

     

    <?xml version="1.0" encoding="utf-8" ?>
    <Overrides>

    <Override xpath = "/SiteUrls/locations/location[@name='weblogs']" mode = "change"
    name = "path" value = "/" />
    <Override xpath = "/SiteUrls/locations/location[@name='weblogs']" mode = "new"
    name = "physicalPath" value = "/blogs/" />

    <Override xpath = "/SiteUrls/locations/location[@name='weblogs']/url[@name='webloghome']"
    mode = "update">
    <url name = "webloghome" path="blog" pattern="default.aspx"
    physicalPath="/themes/default/common/" vanity="{2}" page="home.aspx" />
    <url name = "feedshome" path="feeds" pattern="default.aspx"
    physicalPath="/themes/default/common/" vanity="{2}" page="home.aspx" />
    </Override>
    </Overrides>

    All we're doing is resetting the URL of the weblogs link element to '/' (root), then mapping all requests to be routed to the physical /blogs/ directory in your CS installation (where all the dummy .aspx pages are located to pass the request off to the asp.net runtime), however you will still need to create a directory for each of the <url> elements named with the value in the path attribute, and put a blank default.aspx page in them. You'll notice the mode attribute specified a couple of times above...the accepted values should be fairly self explanatory...it's this value that tells the override parser what to actually do with the XPath statements, how to apply them to the existing config files. Lastly we do the actual URL rewriting in the mode=update block of XPath by mapping the url names to the links specified in the <location> element, and then telling CS what to display, in this case generating a url in the root/applicationKey format (since the path was reset to /, we specify the new path as /blog or /feed, etc). In our case we want home.aspx to display rather than postlist.aspx (the default). Following this pattern you can add as many blogs to your site as you are licensed for.

    As should be fairly obvious, the power of config files means simplicity, reusability, and portability of your config file customizations without having to actually edit the config files themselves. A bit of trial and error might be necessary for the uninitiated, but the benefits of having a system like this in place should be obvious.

  • Executing a DTS Package From .NET

    A discussion between some peers of mine came up the other day about executing a SQL Server DTS package from an ASP.NET web page.  The actual best practice is to invoke a stored procedure that in turn calls the DTS package you wish to run, however thanks to the simplicity of creating a RCW (runtime callable wrapper) via the VS.NET IDE on the legacy unmanaged Microsoft DSTPackage Object Library (located in your SQL Server installation directory in Tools\Binn\dtspkg.dll, also listed on the COM tab in the Add Reference dialog in the IDE), you can invoke a DTS package directly from code if you so wish.  Just as a refresher, adding an RCW from the IDE is accomplished by:

    1. Project references dialog (right click references, add reference)
    2. Find Microsoft DTSPackage Object Library in the exhaustive list of objects on the COM tab
    3. Select it, add it...voila.  The IDE automagically generates the correct interop assembly and places it in the bin folder, ready for instantiation

    The actual code itself is straightforward, here is an example:

    using System;

    using System.Runtime.InteropServices;

    using DTS;

     

    namespace DTSPackage

    {

          ///

          /// Summary description for Class1.

          ///

          class Class1

          {

                ///

                /// The main entry point for the application.

                ///

                [STAThread]

                static void Main(string[] args)

                {

                      Package2Class package = new Package2Class();

                      object pVarPersistStgOfHost = null;

                      try

                      {

                            package.LoadFromSQLServer("SERVER_NAME", // server name

                                  null, // server username

                                  null, // server password

                                  DTSSQLServerStorageFlags.DTSSQLStgFlag_UseTrustedConnection,

                                  null, // if the package has a password, otherwise null

                                  null, // probably null

                                  null, // probably null

                                  "PACKAGE_NAME",  // name of the DTS package

                                  ref pVarPersistStgOfHost);

                            

                            package.Execute(); // execute the package

                      }

                      catch

                      {

                            throw;

                      }

                      finally

                      {

                            package.UnInitialize(); // unwrap the package

                            System.Runtime.InteropServices.Marshal.ReleaseComObject(package); // tell interop to release the reference

                      }

                }

          }

    }

     

    I still recommend calling DTS packages via stored procedures (or via a scheduled SQL Server job), but in a pinch, or for prototyping, testing, etc, the above code should work nicely.  I am assuming that with the release of Yukon, there will be a managed class for this, but you know what they say about assuming.

  • For All The Massive Attack Fans Out There

    I'm sure there has to be a couple of Massive Attack fans who visit this site, and if you're not (or have never heard of them) it's never too late to give them a shot. They helped pioneer the trip hop movement which set the stage for many later bands to follow (Portishead comes to mind, among many others). It's nice and dark, soothing, dubby, and just an all around bad ass style of music.

    A 5 hour mixed set of nonstop Massive Attack tunes has been making the playlist rounds over on the DI.fm Lounge channel for several months now; recently the author of the compilation has finally made it available for download: "This Is Massive Attack (mp3)" compiled by DJ Finny. Snag the download, queue it up in your media player of choice, and enjoy the nonstop sounds of Massive Attack.

  • doh...

    So, there you are...sitting somewhere with the woman of your dreams...or perhaps about to win your the game you've been playing for 48 straight, whatever...just plug in your dream situation. then it hits you...FUCK, I WROTE THAT CLASS WRONG!!! that is just what happened to me, except i was in the middle of a seinfeld episode i had never seen before (yeah, i am lame)

    so, i wrote that singleton object that exposes all the elements of a config file via static properties...DOH! that was the wrong way to do it! erase all of the static keywords in AppConfiguration, and replace any calls to the singleton class w/ AppConfiguration.Getconfig (the previous way was simply AppConfiguration.[whatever]...

    live and die by the code
    j
1 2 3 4 5 Next > ... Last »

Copyright © :: JaysonKnight.com
External Content © :: Respective Authors

Terms of Service/Privacy Policy