Welcome to Tech-Review.Org Sign in | Join | Help

.net_2.0

My coding blog entries. Typically will either be more complex coding examples or overcoming product issues / troubleshooting resolutions.
Unable to Install SP1 for Vista?

Today, trying to update Vista Ultimate to SP1 (released today), I ran into a bizarre error message:

 

"Service Pack can not be installed.  System does not have required supporting Langauge Pack."

 

All of the language packs were installed but there was a exclamation point on the English one, in the Control Panel -> Regional  and Language Options -> Keyboard and Languages -> Remove.  Note that main tab indicated English was set as preference.

 

To correct.

 

Using the afore mentioned navigation - click Remove - and de-install ALL of the lanquages.  This effectively removes the MSI for installing the languages. 

 

Next install from Microsoft Downloads: Language Pack

 
Reboot.  Be patient on the boot-up, it takes approximately 15-30 minutes for the 3 of 3 updates to install.

 

Your language pack files should now be properly installed (English only) and you can download (In my case the SP1 would not install via Microsoft Update) SP1 and install it manually from:

X86 SP1:

X64 SP1:

 

Hopefully that helps someone else in this situation. 


 

Unable to use ASPNET_REGIIS -I for installing Asp.Net 2.0 on Vista / Windows 2008

Vista and Windows Server 2008 have radically re-shaped the simplistic handling of IIS functions and features in terms of both interface and ability to capitalize on cmd line options.  In the previous blog entry I outlined the issues I had with uninstalling the Microsoft Device Emulator to properly install VS 2008 on a x64 system.  During that process - I uninstalled .Net 2.0 which rendered IIS useless for hosting my applications.

 

The issue is - >Net 2.0 does not recognize IIS7.  With IIS 5 and 6 it was common to do the command line aspnet_regiis -i and re-install or repair .Net 2.0.  Since .Net 3.0 and 3.5 are integrated into Vista and Windows Server 2008, one can install .Net 3.0 no problem but there are no such commands for .Net 2.0.  CMD line options will indicate that that a supported IIS server is not found. 

 

So the work around is as such:

 

Open Server Manager

Scroll to Roles Summary

Click on the Web Server(IIS) Icon 

It will open up a new WMI interface

Scroll down to Role Services

Select remove - to uninstall IIS.

Repeat to Install IIS - in which case now .Net 2.0 will also be installed if you select the appropriate Application Develoment -> ASP.Net  option....

 

Unfortunately I know of no other short-cut...but that will allow the re-install of Asp.Net 2.0 (Not it does not install .Net 3.5 on its own - just core 3.0 and 2.0 files)... 

 

Can not uninstall Microsoft Device Emulator 3.0 on 64 bit Vista / Server 2008

I recently upgraded from Windows Server 2003 to Windows Server 2008 on my Quad Core server. 

 

Note keyword was upgraded.  Other than having to grab Vista Drivers for the 3 NVIDIA graphics cards, was relatively painless. 

 

Visual Studio 2008 Beta Version was already installed.  It ran fine for the last week or so but I decided to revisit the Ajax coding in one of my projects and found that with the latest bits for the Ajax Toolkit (targeting .Net 3.5) - too many issues occurring (after all everything worked fine targeting 2.0 and using the 2.0 Toolkit bits).  I deduced that probably not having the RTM version of VS was the most likely culprit (SPs and hotfixes had been installed on top of the VS Beta so...), or at least responsible for the inability to properly debug.

 

I was able to uninstall all the previous components that were recommended on the blogs with the exception of Microsoft Device Emulator 3.0 (X64).  This naturally did not allow the install of Visual Studio to install the remote debugger and other related X64 components.  I tried the tool for removal, tried installing both the 32 and 64 bit versions of the Device Emulator...nothing would work....  For whatever reason the Control Panel on Server 2008 would not allow the uninstall of the previous 3.0 version of the Device Emulator...

 

Here is how I fixed it:

 

In the Documents and Settings\All Users\Microsoft\ directory delete the folder: Microsoft Device Emulator

Next use RegEdit to find all occurances of Microsoft Device Emulator in the registry and delete the entries (about 25 total)

Reboot

Either Re-Install/Repair VS 2008 or after launching VS 2008 installer - select / deselect an option under "Add Additional" and the installer should be able to install the remote debugger.   

 

You should now be able to launch the remote debugger when using a X64 Vista or Longhorn (Windows Server 2008) OS...

 

Also note that when using the Ajax Toolkit that is targeted for .Net 3.5 - you must also make sure that the System.Core, System.Web.Extensions, and System.Web.Extensions.Design - references added - target version 3.5 and not version 2.0. 

 

If the only issue is that can not rid the Emulator - the steps above should fix your problem and save you a ton of effort... The running of the VS 2008 Beta removal tool did nothing that was referenced on some of the blogs really did not work for me...It took approximately 3 de-installs, re-installs of VS 2008, 3 attempts to install the Device Emulator separately hoping it would fix the uninstall issue (wouldn't install or de-install the app)..when none of the normal tactics seemed to work I resorted to old school tactics as not being able to attach a debugger is well - I wasn't going to do a complete re-install of the OS...

 

Hopefully this saves someone the same frustration.... 

 

 

 

 

Debugging TIP of the Day

If you are like me, you probably have a overall project that consists of many solutions.  For whatever reasons it doesn't make sense to have the various solutions and projects  all included into a single solution.  That makes debugging rather difficult - especially difficult when say solution #2 only gets invoked when a web project, console application, or other is 'live'.

 

With VS2005 and above you can actually multi-select the wp3svc, service hosts etc and the debugger of whatever solution will go into a pull down mode where it will allow you to step through the other projects in the other solutions via the particular solution you are working with.  Naturally, all of the other solutions should already be compiled in debug mode and the corresponding meta data from the debug symbols can be stepped through.

 

If using VS on a 64 bit system, the only way to actually change code on the fly during debugging is if the code being changed is referenced from an outside solution.  However, please not that any code changes you make will still have to be made to solution being pulled down.  For whatever reasons if the solution you open on a 64 bit system, can not be directly modified if the debug attach process is within that solution.  Confusing - you'll get it if you try it.  

 

The multi-select is a great way to debug as it it means no fancy footwork has to be done to step through the various application that requires multiple solutions.

 

Simply Select "Debug" - "Attach To Process" and multi-select whatever the various solutions use.  

 

 

.NET 3.5 issues on 64 bit Windows 2003 Server

Recently I decided to forgo using my laptop for developement and instead put together a brand new system that has six monitors and a dual core Intel 64 bit system.  Since Vista would not install - I opted to go for Windows Server 2003 instead, as I will probably reire my older web server once 2008 comes out.  A fresh install was done, with all of the updates and service packs. 

 

I installed Visual Studio 2008 Beta - and everything was working fine, with exception when I tried launching my site / project in IIS>  I got a :

 

Could not load file or assembly 'PresentationCore' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'PresentationCore' or one of its dependencies. An attempt was made to load a program with an incorrect format.
 

 

 This blog entry that most resembled my issue:  http://blogs.msdn.com/heaths/archive/2007/07/13/kb928365-for-ms07-040-leaves-some-managed-applications-sluggish.aspx

 

While his issue and mine were different I ran the command he recommended:

%WINDIR%\Microsoft.NET\Framework\v2.0.50727\ngen.exe executeQueuedItems

- and I kept getting a file not found exception, although it was obvious the queue had entries.

 

I changed the target directory to point to the 64 bit version of the framework:

%WINDIR%\Microsoft.NET\Framework64\v2.0.50727\ngen.exe executeQueuedItems

 That at least got rid of the queued items (That I didn't know about).  But the problem persisted.

 

Finally, after a few hours of combing the net for a possible solution, I went into the bin directory of my application - and noted that a previous Beta .Net 3.0 runtime version of the PresentationCore.Dll was in the bin (how or why it was copied local - no idea - but it was there).  Deleted the files and wallah - everything was back to normal.

 


 

When the Random() Function always returns 0 and not a random number

While working with Greg on the .Net Trade 6 refresh update, we ran into a bizarre behavior.  The load balancing is accomplished by using the .Net random method based upon the number of servers in the list.  Part of the testing we do, is a ton of fail-over scenarios and it is kinda my responsibility to wreck havoc on the system, to actually break it - and then identify where.

 

In the scenario which we discovered the bug, was having four - five Business Service Hosts handling the web requests.   Downing the BSLs, usually provided the anticipated fail-over behavior, except sporadically - all the sudden only one BSL would start handling ALL the requests (the first one in the load balancing list).  All other active BSLs stopped receiving load.  Even if other BSLs were added, the behavior would be the same.  In the configuration manager - all the BSLs were listed and noted as active.

 

Closer analysis indicated that when this condition occurred - the random function was always returning zero.  This of course explained why the first BSL in the list would get all the load.

 

So, we wrote a test application to troubleshoot and reproduce the issue.  Sure enough, when using a random seed value of 5, the multi threaded test application would get into a condition where every random result would suddenly default to zero.  If the seed value was say 5000, it took longer to reproduce.  Our analysis of it was, that since the random function uses the System.DateTime.Now, that when all threads were synchronized due to a global locking condition - the result would just return zero.  This behavior was re-produced on a Vista machine(32 bit), as well Windows 2003 (X64) and Longhorn (X64).   Whether or not it is a bug or designed behavior for the Random method, is beyond the point - simply put: if you use random() generation for a small set of numbers and wonder why it appears nothing is randomly generated, the culprit will be that all of the threads are active within the instant the random function is called.  This symptom does not appear typically with a single thread and for obvious reasons.  With the speeds of the processors and especially using dual and quad processors - it is now more likely that if heavy use of the random method is used - the more likely a greater number of threads will generate the same random number when the threads get closer to being simultaneously executed.  However, if all threads call the random function at the same time - it bizarrely just returns 0 as the random number generated. 

 

Since the .Net Trade load balancing and updates to config changes to servers of a cluster require a siginificant amount of locking to to be thread safe, we have opted now to use a round robin approach.   

 

I'll put a sample test application up here a bit later perhaps if anyone is interested in re-producing it.  I decided to write this blog entry on this non random randomness of returning zero as a result - as I couldn't find any one else that had reported such and it is a bizarre and totally unexpected behavior.  


 

VS 2008 - It does increase productivity...

It has been two weeks or so, with using VS 2008 (Beta) exclusively and to date have not used the VS 2005 to do any coding.

 

While I really see no use for LINQ and some of the other newer technologies (mainly because I code for performance and not ease of coding such as using master pages etc - instead I would rather craft the code to do what it needs to do with the least amount of perf hit as possible).. there are some really cool productivity enhancements with VS 2008.

 

 

The first: The split view of code and design when working with .aspx and ascx files.  It was always a issue with earlier versions that one couldn't switch to design view because of some code behind or missing control.  Now with VS 2008 you can display both and find and correct issues without worrying about the 30 second pause and message dialogs... The designer even includes a intelligent 'refresh' button for the designer so you can verify in real-time that designer and the code are in sync.

 

Secondly:  The ability now to not have declare private variables for public variables.  The old: private int _myTest; public int  MyTest { get _myTest, set _myTest = value} is now simply public MyTest{get;set}. 

 

What a savings on coding... see Scott Gu's blog for details..

 

Third.. Compiling huge projects is incredibly faster.  One solution I have under VS 2005 would take 5 minutes to compile, with VS 2008 - less than 30 seconds... no more having to brew a cup of coffee to await the results...

 

Find and Replace however still suffers the same issues as previous versions.  When you click on Quick Replace, and then Replace in Files - it will change the selection for whether it should target solution, project, selection, etc.. and in some cases replace what is supposed to be replaced (in the dialog) with the previous replace text...  A somewhat major annoyance at times but the undo does actually work more efficiently than previous versions...

 

The one thing I wished was there would be some kind of breaking changes document describing what is different with 3.0 / 3.5 and the changes to the core 2.0 (as it applies the service pack)...One of the decent things at least the whole Ajax implementation did between versions - was outline breaking changes, and new features..  The Visual Studio section on Microsoft's site really doesn't provide such info in a simple document...

 

Overall though, fairly pleased with VS 2008... 

My Biggest Beef with -Vista: Uninstall doesn't un-install anything

If there is one thing about advertising I despise - is when any manufacturer advertises better reliability from other versions to justify the upgrade. 

 

The opening tone is serious because this is a serious issue, because unlike subscribing to take the risks with a BETA or Pre-Release version of some software product - I shelled out money to have to have Vista Ultimate.  And while less the issues with video drivers, I could be happy with Vista less this one MAJOR issue...

 

Uninstalls are not uninstalls.

 

 

Yep, thats right.  I have not yet to successfully uninstall any software product that I decided I could do without.  The same software that I can install under XP - actually uninstalls under XP - but not in Vista.

 

One case in point: Yahoo Messenger.

 

I used the uninstall feature after realizing that I had mistakenly installed the Yahoo toolbar.  I hate those toolbars that Google, Microsoft, and Yahoo insist on offering as part of some messenging application installation option.   So, I did the Add/Remove programs from Vista - and uninstalled the toolbar, and subsequently the Yaho Messenger.  Guess what....

 

All of the registry entries remained, the folder still remained with the actual application in Program Files, and now every time I use Firefox - I get a object leaked error any time a site spawns a new window and I close it.  The leak comes from a ytoolbar chrome overlay error.

 

You would think then - must be an issue with Firefox.  No sir (or ma'am)...

 

15 other applications have been installed and un-installed and while the start menu may be devoid of the application shortcut and folder, the apps still remained in the registry and the file system.  The same apps installed on XP - got rid of everything as you would expect from an uninstaller with no lingering footprint of the applications.  

 

Even running applications such as CCleaner after un-installs (and after rebooting) verifies the issues...  And as a note - all of the applications used InstallShield or Microsoft's own MSI installer...and in one of the 15 cases included Microsoft Office (which now I can't get rid of as the uninstaller ran and something happened but it decided it uninstalled correctly - leaving everything still there with no actual uninstall occurring (and even worse left the taskbar / programs with all the shortcuts but only portions of the uninstall ran so nothing works anyways).  The same occurred with un-installing Microsoft's Live One-Care - its all still there even though it was un-installed...So, it is not a random event with rogue applications - it is a Vista core issue...

 

For a $$$ Operating system - this is one of the quality control checks that obviously got missed, and makes my own use of Vista unreliable because why should I have to manually comb through the registry and file system to remove a application that supposedly un-installed successfully... 

 

 

 

 

 

 

 

 

 

 

 

 

Orcas - Are you getting the most out of it...(Conversion Process)

Since my exposure of playing with Ajax during all the Beta cycles, and ending up so frustrated - I kinda stepped back and stopped participating in anything related to a Beta.  So, it may be a surprise that I actually installed Orcas (Beta of VS 2008) and unlike my terrible experiences with converting my projects to VS 2005 - surprise - all converted without any drama what so ever (less one where when I started VS 2008 the first time it crashed during applying settings).  That is good news.

 

There is a word of caution however, that needs to be observed for anyone converting their solutions / projects.  

 

For the most part most of us realize that .Net 2.0 is not actually replaced with a new version with the release of Visual Studio 2008, instead .Net 3.0 and .Net 3.5 are more or less just extensions to the core .Net 2.0 framework.  In my opinion the whole 3.0 naming is a marketing nightmare and a severe confusion for developers and plenty of blogs out there that echo that sentiment.  It gets equally confusing when you load up a Visual Studio 2005 solution / project and convert it. 


The assumption would be that by default it would convert and optimize those solutions and projects to .Net 3.5 or 3.0 depending.  It doesn't however, and instead by default the target .Net version is still .Net 2.0 during the conversion process.  This would explain the reason why there where no conversion issues with any of the 155 projects I had in my solution(s) (versus the ton of issues migrating from .Net 1.0 to .Net 2.0 back in the day).  

 

To target a specific version for compiler / CLR efficiency and more importantly to gain the enhancements... some work will need to be done on your behalf.  In my opinion the Conversion Wizard SHOULD give an option during the conversion process (or perhaps explain before conversion if it automatically detects and chooses the proper framework) - to target which .Net Framework to convert a solution / project to.  I had assumed the conversion would optimize to the most recent version (ie 3.5).

 

If you have converted a VS 2005 solution to Orcas then you need to open up the properties page for each (or just one for this example) project in the solution:

 

 

 

 Note where it says: TARGET FRAMEWORK

 

That is a drop down selection and .Net 3.0 and .Net 3.5 are listed below the .Net 2.0.  

 

By default the conversion process defaults to .Net 2.0, which means that nothing really changes...Less the fact the .Net SP2 incorporation....Then again - since 3.0 and 3.5 are just extensions to the core framework (2.0) - and I do believe there may be no overlapping functionality between the three.... so begs the question why is there a selector for the framework? It was explained to me that by default the CLR will use the highest framework available and work its way down, and since 3.5 and 3.0 require 2.0...
 

 

Since I am working with the .Net Trade 1.1 refresh release, one of the tests we are conducting is to see what enhancements Orcas / Longhorn give us in terms of performance.  And cursory initial tests just running a converted version of .Net Trade - indicated no real perceptual performance benefits.   However, since the conversion defaulted to .Net 2.0 (as confirmed by bringing up the properties pages for the projects) - it would be safe to assume that no gains would have been had to begin with.  So, in the upcoming week - we'll be trying out the targeting of a specific (.Net 3.5) compilation of .Net Trade to see what gains will be had if any. 

 

However, the goal of this blog is to make you aware that there are many new options for how Visual Studio compiles the end dll.  And while one can take the stance of the compiler will figure it all out - if a project is compiled with the target framework set to .Net 2.0 (the default) - then you will get no real gains with having used Orcas (Visual Studio 2008) in terms of perf or features... by just merely converting a project / solution...

 

 

 

 

Images and working with a DAL

Most examples of working with saving images to a SQL Server database within a application that does not implement a DAL, usually work off only a HTTPPosted file and looks kinda like this:

 

           //create a stream
 

            Stream imgStream = proposedFile.InputStream;

 

            //get the length of the http posted file


            int imgLen = proposedFile.ContentLength;

            //now loop through the stream and assign it to the byte[] (which is an array)


            byte[] imgBinaryData = new byte[imgLen];
            int n = imgStream.Read(imgBinaryData, 0, imgLen);

             //now do the SQL portion



            SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
            SqlCommand cmdAdd = new SqlCommand(spToUse, conPortal);
            cmdAdd.CommandType = CommandType.StoredProcedure;

            cmdAdd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
            cmdAdd.Parameters.Add("@communityID", CommunityGlobals.CommunityID);
            cmdAdd.Parameters.Add("@imageID", imageID);
            cmdAdd.Parameters.Add("@imageName", imgFileName);
            cmdAdd.Parameters.Add("@contentType", imgContentType);
            cmdAdd.Parameters.Add("@imageData", SqlDbType.Image).Value = imgBinaryData;

            conPortal.Open();
            cmdAdd.ExecuteNonQuery();
            conPortal.Close();

 

This process works well without the DAL abstraction because everything is all contained in a single method.  When one tries to implement this using a DAL there is a latency disconnect and at times (sporadic) , the bytes[] may (I shall emphasize MAY) get truncated.   Interestingly enough, during my testing of a DAL implementation, each subsequent request for saving the object resulted in a longer byte length transmitted... 

 

My real issue however, was doing some performance improvements on my image handler.  Originally, I was retrieving a full size image and re-sizing it in memory - to a defined thumbnail image size for display.  While, I was implementing caching - the initial rendering was simply slow.  Additionally, the thumbnails are used for lists or menus and I also wanted the ability to modify the thumbnails so that met certain defined requirements and may not be direct representations of the original posted file.   Perhaps all done in sepia tone, image would be cropped, or water marks would be applied for example.  

 

If there is one thing - that we must be careful of when manipulating images - is any manipulation decreases the quality of the image.  So, my performance goal at sake of database storage (there is always a trade-off) - was a new table - that stored the thumbnails.  My ImageHandler checks for thumbnails in the database, if one doesn't exist then it grabs the original image - and performs the resize - and saves it to the database.

 

What made the issue more complex was that I am enforcing the use of my custom DAL, which for the afore-mentioned  reasons,the issues of latency needed to be addressed as well..The previous example merely illustrates how the code looked prior to doing the whole n-tier deal.

 

 Here is the revised code:

 

       public void SaveImage(int imageID, string ContentType ,string ImageName,string CMDTEXT,Image image, int SID)
        {

             // Update the image in the database
            MemoryStream imgStream = new MemoryStream();

            //ContentType is a string passed into the method. GetImageFormat converts the string to the

            ImageFormat enumerable required.  image is type of Image.


            image.Save(imgStream, GetImageFormat(ContentType));
 

            //Instead of doing the whole calculate stream length (which is a heck of alot easier to do with

            //HttpPostedFile than a Image type...  we call GetBuffer() - this fills the byte[] variable with

            //the image bytes[] (basically it is all now an array.... )


            byte[] imgBinaryData = imgStream.GetBuffer();
    

            //the rest here is based on previous blog posts and is how I handle my DAL and pass

            //parameters...
            List<ParmInfo2> PARMS_TOPASS = new List<ParmInfo2>();
            PARMS_TOPASS.Add(new ParmInfo2("images", "CID", CommunityGlobals.CommunityID));
            PARMS_TOPASS.Add(new ParmInfo2("images", "CPID", imageID));
            PARMS_TOPASS.Add(new ParmInfo2("images", "SID", SID));
            PARMS_TOPASS.Add(new ParmInfo2("images", "imagename", ImageName));
            PARMS_TOPASS.Add(new ParmInfo2("images", "CType", ContentType));
            PARMS_TOPASS.Add(new ParmInfo2("images", "Data", imgBinaryData));
            
            dalGlobals.ExecuteNonQuery(CommandType.StoredProcedure, CommunityGlobals.ConnectionString, CMDTEXT, PARMS_TOPASS);

//TIP: ALWAYS dispose of the Image or MemoryStream when used in a method...

   imgStream.Dispose();
   image.Dispose();
            
The DAL now properly handles the saving of images, with the use of the GetBuffer().   Additionally, it also saves three lines of code (not that that is an important reason - but less code is well less code...)..The above code also demonstrates how to save images when the image is based off a an existing image imported from the file system or a data store with a DAL in place. 

 

 

 

 

 

 

 

 

 

 

Latest Benchmark Source Code Released: .Net StockTrader

I am happy to report that the .Net StockTrader Benchmark Application (and subsequent source code) are now released. 

 

Visit:  http://msdn2.microsoft.com/en-us/netframework/bb499684.aspx

 

 Also, this is one of the first times that a benchmark application has an associated forum to discuss installation issues, coding strategies, and overall perceptions of the code / application.  This is Rev 0 (so to speak) and overall - should be a very stable application for most users that install it and play around with it.

 

What should excite you about this benchmark is that it can be adapted to future WCF, SOA, or other disconnected system designs you may want to adopt or currently involved with on a development project.  As typical, with Microsoft Benchmarks that are related to G. Leake - all of the source code is provided and you are invited to test the code yourself as well as examine the inner workings....

 

 

A quick summary (quoted from Microsoft's MSDN site):

 

Technologies Demonstrated by .NET StockTrader

  • Service-oriented, n-tier design with ASP.NET and WCF
    • Clean separation of UI, business services and DB access
    • Design and tuning for performance
    • Horizontally scalable via dynamic clustering
    • Centralized configuration management of clustered service nodes
  • .NET 3.0 with Windows Communication Foundation
    • Interoperability with J2EE/WebSphere Trade 6.1
    • Incorporates alternative designs for performance comparisons
    • Loosely-coupled, message-oriented design with WCF and MSMQ
    • Achieving assured message delivery with transactions
    • Self-hosting WCF Services
    • Custom WCF Behaviors
    • Service host failure detection and automatic restarts
  • .NET Enterprise Application Server Technologies
    • ASP.NET 2.0
    • ADO.NET 2.0
    • .NET Transactions
    • MSMQ 3.5 (Windows XP/Windows Server 2003)
    • MSMQ 4.0 (Windows Vista/"Longhorn Server CTP")
    • Transaction batching with WCF and MSMQ


As you can see, un-like PetShop, Nile, and ITS - this benchmark application showcases a incredible array of technology wrapped up in one download.  I'll be participating on the forums to help assist with issues and answer questions as I was limitedly involved during the development of this benchmark application.  Please do check out the application and series of reports that accompany this release of the .Net Stock Trader application...

 

 

 

The IDataReader - Frustration in DAL land and other frustrations

 The problem with programming sometimes is learning the annoyances that plague a development language.  I was troubleshooting my SQL DAL, which instead of using the "it COULD work with every data provider" (the caveat being - if the only data relationships are those you generate from drag and drop IDE)...has a semi-generic abstract base, but utilizes generics such that parameters and provider specific annoyances can be fully exploited and not merely addressed.

 

Most DAL implementations either go to one extreme where an incredible use of reflection is utilized to cast types back and forth.   The other extreme is creating a DAL that uses the ever limited SQL Helper class that comes from DAAB but yet for every Business Method there is an equal corresponding DAL method.  My approach is using a dictionary in the DAL that contains the specific DataProvider commands for parameters.  The BLL passes over a LIST<T> that contains a key value that matches a key in the Data Provider specific DAL and contains the value to populate it once the translation is made. 

 

The reason for that approach, is that I can either pass a SQL stored procedure, auto-generate a sql text based on few sets of parms, or execute a a pure ADO command text that is passed in based on a key pair match.  Ultimately, it eliminates the need for the BLL to manage anything data related.. ALMOST..

 

Gripe 1.  You can do ExecuteNonQuery, ExecuteScalar, but not  ExecuteReader  in a manner that the DAL actually handles closing the underlying connection.   The flaw lies in the underlying  Interfaces.  For instance calling specifically the SQL Data reader, you can manage the connection within the DAL, however if you use the IDataReader - you specifically have to provide the Close and Dispose (but not the open)  and mark the DAL with IDisposable.  Otherwise, you will get nothing but a conjucture of "Parameter is already contained within another collection"... which to mean indicates that if you call the parameters.Clear() - it should take of it - and it doesn't leaving the taste there thread safety issues...

 

Gripe 2.  Try .. Catch.. statements..  Sadly, you cannot do something like this:

 public object MyClass(something something)

{ try

{ myObject obj = DAL.something;}

catch(Exception ex)

{

 //log this

}

Finally

{

Dal.close() 

 Dal.dispose()

}

return obj;
 

Sadly a object reference to an object occurs with returning the obj as it is declared in the Try statement.  So instead, you would have to init the obj before the Try statement.  Now, I now this has been around for ages and that we all deal with it... but does it really make sense?  Programming wise, it is a waste of allocating objects first only to find you can't do something with it anyways... Secondly, if the Try succedes shouldn't whatever is declared be accessible outside the scope of the trapping?

 

Which brings me to Gripe #3

 

Even when specifying a Dispose, Close, and Open in the DAL / IDAL and calling it within the BLL - when an error occurs within the DAL (say a SQL Parameter mismatch) - the connections never get disposed in the finally statement EVEN though it is explicitly called from the BLL.  I spent a better part of all day tracking down "Parameter already contained in a  collection" error - only to discover the real error was that I had renamed the variables used as passed parameters.  (from @sectionid to @sid)..

 

Even with it wrapped in proper try / catch and  finally blocks, when the error occurred, the connection was never closed or disposed even though the Dispose and close methods of the DAL were called in the finally block.  They work properly when everything goes without an exception being caught..

 

This to me is contrary to the way the whole exception handling is supposed to work.  And what is worse - since this is the method documented for handling errors - this has to be a bug..

 

Secondly, using the IDatareader reader.. do something (CommandBehavior.CloseConnection) does not work although intellisense gives you the option to use it. I had thought the whole purpose of this was to allow the not explicitly closing a reader but allowing the reader to automatically close the connection when no more data is being read.  It works naturally if you use the SQL reader but not the lower level IDataReader which is a requirement if you are designing n-tier structures...

 

Just a rant for the day... 

 



 

System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs:

Adding Event logging works the same with VISTA as it does in XP.  Unfortunately there is no programmic method to make it work the first time.

 

The symptoms are you check and check the event logs to see where your entries are but alas nothing.  Under VISTA you will see a sporadic "Uable to find Type Initializer"  in the event logs.  The later is an indication that you have not yet performed the following:

For XP , 2003, and Vista

1.  Right Click on "My Computer"

2.  Select "MANAGE"

3.  Select "USERS AND GROUPS"

4.  Drill Down on "GROUPS"

5.  Double-Click on "ADMINISTRATORS" and select "ADD" on that property sheet.

6.  Click on "ADVANCED" and then "FIND NOW"

7.  Select "NETWORK SERVICE" and ADD - OK...

Illustration here:

 

 

Fire up your application and now it should create and start recording your log entries assuming you have code implemented similiar to such:

 

 public void LogMessage(string exMessage)
        {
            EventLog EventLog1 = new EventLog();
            try
            {
                //replace EVENT_LOG with a configurable value
                string EVENT_LOG = "Sites-Easy Web Application";
                if (!EventLog.SourceExists(EVENT_LOG))
                    EventLog.CreateEventSource(EVENT_LOG, "Application");
                EventLog1.Source = EVENT_LOG;
                EventLog1.WriteEvent(new System.Diagnostics.EventInstance(1, 1), new string[] { exMessage });
            }
            catch (Exception ex)
            {
                throw ex;

 


            }
        }

 

Once you have verified that the logging is taking place, for security purposes you SHOULD repeat the process and REMOVE the NETWORK SERVICE from the Administrative group.  The error only occurs when there is no Event Log that matches the name requested and the application code is trying to create one.  Otherwise, if the event log is found IIS has enough rights to write entries.  Having NETWORK SERVICE as part of the Administrative group is potentionally catastrophic if some third party tool is installed and has malware, spyware, or other anti-productive qualities written within...

 

If you haven't checked out the series of articles Peter Bromberg has written on "Fire and Forget" Asynchronous pattern - you should.  Most notably - the easiest of the series to adopt to your own code is :


Fire and Forget Fun: RPC Pings, GET, POST and more.
By Peter Bromberg
Printer Friendly Version

 

I had tried his other article on Logging but since I use alot of interfaces I found it nearly impossible to adapt.  However, the before mentioned article, clued me on what to do when trying to invoke a method that is in a dynamically loaded assembly.  Create a stub, that once the assembly is loaded - the delegates will work as intended. 

 

For instance:

 

In an interface you can not declare:

 

delegate void LogMessageDelegate(...some parameters)...

 

The IInterface doesn't accept it and so you should create what I call a stub method:

 

For example in the Interface (IDAL) 

void LogMessageAsynch( some parameters)

 

In the class being invoked...

 

then you can do the:

 

public delegate void LogMessageDelegate(string exMessage); 

         public  void LogMessageAsynch
        (
            string briefEntry,
            string fullEntry,
            Severity severity,
            string module,
            string additionalInfo
        ) {
            HttpContext Context = HttpContext.Current;
            // Get section ID
            string displayMessage = (severity.ToString() + module + ": " + briefEntry + "<br />" + fullEntry + "<br />" + additionalInfo + "<br />");
            BackgroundProcess(new LogMessageDelegate(LogMessage),
                             new object[] { displayMessage });

 

The above code implements the logging logic earlier in the article.  I will say transforming my logging to do the ASYNCH process, as Peter suggests, did improve the perf of the display of the pages while using SQL Profiler.  SQL Profiler indicated that the majority of log entries occurred AFTER the loading of the page - and before pages would wait and wait until all of the activity logging was committed.  This actually is a decent benefit for those writing logging functions for debugging code as well as in a production site where seeing entries in real-time anyways would not be possible any how.

 

 

 

 

The SqlParameter is already contained by another SqlParameterCollection

A few days ago, I closed the laptop lid on my Toshiba  and went to where I was going.  It never came out of standby and as a result - had to cold power it.  Unfortunately for me, I had Visual Studio open, and when I re-opened my solution - only 36 of the 90 some projects were showing.  Considering a majority of the projects are module specific DALs, I realized that after spending 6 hours getting the projects back into the solution and properly configuring them, that the time was now and not later to consolidate all of those DALs to use the Generics based 'global' DAL that I had created. 

 

In the process, I needed to write some form of a generic method that would handle populating a dataset from multiple queries - using the least bit of code.

 

Example:

 

 public DataSet ReturnDatasetFromStoredProcedure(ArrayList SP_AND_TABLENAMES, List<ParmInfo2> SELECT_PARMS)
        {   SqlDataAdapter cmd = new SqlDataAdapter();
            DataSet dst = new DataSet();
            int i = 0;
            try
            {
                foreach (string p in SP_AND_TABLENAMES)
                {  

// [0] is the table name [1] is the name to assign the table when we do a fill


                    string[] args = p.Split(',');
                    cmd = new SqlDataAdapter(args[0], CommunityGlobals.ConnectionString);
                    foreach (ParmInfo2 item in SELECT_PARMS)
                    {

                        cmd.SelectCommand.Parameters.Add(item.SQLPARM);

                    }

               cmd.SelectCommand.CommandType = CommandType.StoredProcedure;
                    cmd.Fill(dst, args[1]);

 

Using the code above - generates a:  "The SqlParameter is already contained by another SqlParameterCollection" error." (see bold highlight in the code above).

You would figure that by calling:  cmd = new SqlDataAdapter(args[0], CommunityGlobals.ConnectionString);

Would clear automatically the parameters associated with.  Practically every other new() something does.  Not the case here and so a quick search and a discusion thread pointed out that adding a cmd.SelectCommand.Parameters.Clear(); after the cmd.Fill, would allow me to re-use the parameter.

 

It worked.

 

An interesting discussion on why here this is an issue but when using some of the other ADO commands - you can re-use the parameter assignment... 

 

see: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=339961&SiteID=1
                 

 

Sample Applications you should learn from.. c# / VS Studio 2005

In the world of adopting .Net as a programming language of choice, the ultimate question is, "Where are the samples I can learn from".

 

If you are reading this, you learned your basics maybe on your own or from some programing class, but you probably actually learned the advanced stuff from dissecting sample applications and code snippets off blogs.   What you may not know, is that the published 'sample' apps differ greatly from the 'benchmark' applications that are also published.  The former address the simplicity of design, which works for the hobbyist developer.  The latter, challenges the want to be or already hardcore developer with proven coding methodologies that provide performance and reliability with or without out going gung ho on on all the PAG recommendations.. as most developers fall in between the serious and the hardcore set.  The generic you can drag it from the IDE - approach is easy and romantic but is not always the most performant approach - but may be the easiest to design approach.  Which, unfortunately doesn't yield the backbone of designing mission critical applications.

 

For the casual developer that has no real ambition to create the next MYSPACE.COM... the sample applications off of ASP.Net are fine...

 

For the developer that is seeking a more technological example to learn from, then check out the following:

 

http://msdn2.microsoft.com/en-us/netframework/bb499684.aspx - This is the latest performance oriented application.  At time of this writing the download will be online in a few days if not already.  It illustrates:

 

  1. Using WCF with a variety of protocols and bindings
  2. Designing a load-balanced SOA design
  3. Writing a Windows Application as a self hosted WCF service, or hosting it all withing IIS( for examples of using a Windows Console - contact me..)
  4. Use of delegates, reflection, n-tier design and PAG style programming.
  5. Interoperability between databases and service types... WAS to .Net, or using Oracle versus SQL...


Other .Net benchmark examples include:

 

Petshop: http://msdn2.microsoft.com/en-us/library/aa479070.aspx

 

For studies and benchmark results of several performance oriented application samples see: http://msdn2.microsoft.com/en-us/vstudio/aa700836.aspx 

 

Most of all the studies include the source code.  The big difference between the benchmark studies and the regular examples on ASP.net is that the regular samples are designed around the premise of designing an application quickly (It is easy to develop using our technology).  A benchmark application is geared to getting the most out of your buck and supporting large scale enterprise solutions.  This involves a bit more lower level and greater understanding how .Net works.  For the last seven years or so, I have been involved with Microsoft and other companies to evaluate and validate benchmark studies (from designing the networks and labs they run these benchmarks on to actually performing the benchmarks and writing the methodology the benchmarks must adhere to) - and from my own personal perspective I have learned more of how to do the right thing by dissecting the benchmark applications over the sample applications when it comes to my own coding.

 

The reason is that ease of use versus performance, portability, and reliability weighs heavily on how to design the next big thing, and the quick design IDE  approach may not yield the results you want when going live.  For prototyping or low impact application, one programming method works quite well , while supporting a huge number of users or complex coding - another method works way better... a hybrid helps those create a application that can mature with minimal re-work.

 

The latest benchmark from Microsoft - is the .NET Stock Trader Application. If you have not yet considered adopting WCF - this one benchmark sample may change your mind.  I invite you to check it out.  If you happen to have issue using it, and lack an answer on the forums - feel free to contact me at jody @ cn2technology.com or post a comment on this thread and I can see what I can do for you - time forgiving.  I am not directly associated with the project - however, may be of assistance in your evaluation of it once the source code is released..

 

None the less, I have included a variety of links of additional samples that may satisfy those looking for a more sophisticated demo app to learn from...The key to programming and doing it well is digesting all of the samples produced.  Coding style changes from person to person and the more you know the greater your awareness is to interacting with developers of lessor or more knowledge than yourself...

 

Enjoy 

 

 

 

More Posts Next page »