Adsense

Wednesday, November 14, 2007

DNN Forums Upgrade - The type initializer for DotNetNuke.Modules.Forum.DataProvider

I was getting this error after trying to upgrade my DotNetNuke Forums module from a 3.* version to a 04.04.03. The error refers to a dll that is no longer valid from the old version. After spending some time trying to figure the error out, I ended up having to uninstall the old version and then install a fresh copy of the new version.

(WARNING - Unless you do some backing up and restoring of your Forums data, you will probably lose your existing posts. Keep this in mind.)

Anyone know of an easier way of getting the new version installed without having to uninstall the old one?

Monday, November 05, 2007

SQL Server 2005 Error - An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

You may receive this error when trying to remotely connect to your SQL Server 2005 (or Express) database. (Even when connection remotely from a service running locally, such as an ASP.NET website.) The first thing to check is the most common cause of this error. You must enable Remote Connection manually to SQL Server 2005 installations because they are disabled by default. To do this, check the following.

Enable remote connections for SQL Server 2005

  1. Open the SQL Server Surface Area Configuration tool. (You can find this in your start menu under SQL Server 2005.)
  2. Expand "Database Engine"
  3. Click on "Remote Connections"
  4. Enable Remote Connections (TCP/IP, Named Pipes, or Both)
  5. Click on Service under "Database Engine" and Stop then Start your database for the changes to take affect.

Test your connection now. For most people this will be sufficient to correct the problem. In my case, my company is using a connection string that did not specify the port when connecting to the database. I had just reinstalled Microsoft SQL Server and received this error and didn't want to have to change anything in the project to get it working again. I found that I had to statically set it for the server to SQL Server's default value of 1433. To do this, perform the following.

Set the port to be used with TCP/IP connections

  1. Open the SQL Server Configuration Manager
  2. 2xpand SQL Server 2005 Network Configuration and select "Protocols for YOURDBSERVERNAME"
  3. Right click on "TCP/IP" on the right and choose properties
  4. Click on the "IP Addresses" tab
  5. Set the TCP Port property for the entry with IP Address "127.0.0.1" or any other that you need and click "Apply".

In our case, this fixed the problem and allowed us to use our connection string unmodified.

Saturday, October 06, 2007

"Windows Live Messenger" or "Windows Media Player" has stopped working - APPCRASH / StackHash Error - Fix

If you are getting either of the following two error messages when staring Windows Live Messenger or Windows Media Player, I might know of a couple of things that could be causing the problems. This may only affect people who are getting the error in conjunction with errors in Fault Module Name StackHash_XXXX.
----- ERROR MESSAGES -----
Windows Live Messenger has stopped working
Problem signature:
Problem Event Name: APPCRASH
Application Name: msnmsgr.exe
Application Version: 8.1.178.0
Application Timestamp: 45b12d6a
Fault Module Name: StackHash_ed38
ETC...
Windows Media Player has stopped working
Problem signature:
Problem Event Name: APPCRASH
Application Name: wmplayer.exe
Application Version: 11.0.6000.6336
Application Timestamp: 46a16548
Fault Module Name: StackHash_5255
ETC...
----- /ERRORS MESSAGES -----
Possible Fix 1: nVidia nForce driver components
I have an EVGA i650 Ultra motherboard in my system with the nForce drivers installed. Either of the two following nForce driver components / features might cause this problem in Vista.
  1. nVidia MediaShield
  2. nVidia - ForceWare Network Access Manager
Uninstall them to see if it clears up the issue. I uninstalled both of them and it was fixed, so it could be either.
Possible Cause 2: Vista's DEP Protection
To fix this issue, you might need to disable DEP in Vista. To disable DEP, perform the following (found these steps HERE.)
1. Click Start
2. Click All Programs
3. Click Accessories
4. Right Click on Command Prompt
5. Left click on Run as Administrator
6. Click the Allow button if it asks you for permission
7. Type or copy and paste this into the command prompt window:
bcdedit.exe /set {current} nx AlwaysOff
8. You should see the message "Operation Completed Successfully"
9. Reboot and DEP should be off.
For more information regarding DEP, what it is and how it affects your web-based applications. Checkout this link.
Possible Cause 3: Administrator Mode
You may also want to try running the application as an administrator. You can do this by right clicking on the short-cut, selecting properties and checking the "Run as administrator" box.

Tuesday, September 18, 2007

Visual Studio - Item Template Editing (Class, WPF, Forms, ETC...)

I've been working in Visual Studio for a few years now, and have created hundreds of classes, user controls, windows, forms, pages... You get the picture. I'm also the type of developer that likes to keep my code organized and generally start off with a couple of standard code regions (Fields, Properties, Events, etc...) in my classes and code-behind files.

I always imagined that there would be a simple way to override the default templates for these files to make my job easier, and today I finally spent the time to track it down...

Visual Studio Item Templates are located in the following directories...

Item Template Files

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates

Item Template Cache Files

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplatesCache

Within each of these directories you'll have folders for CSharp, VisualBasic, etc. These folders hold all of the Item Templates for the named language. To edit the base implementation of the Class.cs file, you would browse to "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplatesCache\CSharp\Code\1033\Class.zip" and load up the Class.cs file. This file would look something like this by default.

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
    class $safeitemrootname$
    {
        public $safeitemrootname$()
        {
        }
    }
}

You might end up modifying this file like so to add a few regions by default...

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
    class $safeitemrootname$
    {
        #region Fields & Properties
        #endregion

        #region Constructors
        public $safeitemrootname$()
        {
        }
        #endregion

        #region Private Methods
        #endregion

        #region Public Methods
        #endregion
    }
}

The next time you add a Class.cs file to one of your projects, it will come complete with the regions that you added to the template. You can also customize these templates further using other template parameters (i.e. '$clrversion$' for the Current version of the common language runtime (CLR).)

You can find a list of template parameters HERE....

Friday, September 07, 2007

Windows Vista - Window Focus - Alt + Tab Feature Tweaks

One of my favorite Vista features is their implementation of the Alt + Tab hotkey for switching window focus. Unlike Windows XP which would allow you to press Alt + Tab to cycle through your open windows. Windows Vista allows you to hold in Alt + Tab and then click on one of the displayed thumbnails to change focus.

Such a simple change, but with how often I use the hotkey to switch window focus. I find it much easier to hit the hotkey and quickly click on the window I want rather than cycling. My only problem with the feature is how small the icons are, especially on high resolution monitors. I found this great post which explains how to tweak this feature with a registry entry to make the displayed thumbnails any size you wish.

Save the following snippet to a text file with a .reg extension. Double-click the file you created to update your registry. This is optimized for my laptop's resolution of 1440X900, but feel free to tweak the settings for your resolution. You can tweak the size of each thumbnail, and the spacing between them...

(TIP:  Use a Hexadecimal Converter to get your values right. Like This One)

#### Snippet ####

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\AltTab]
"OverlayIconPx"=dword:00000023
"OverlayIconDXPx"=dword:00000000
"OverlayIconDYPx"=dword:00000000
"ThumbSpacingXPx"=dword:00000004
"ThumbSpacingYPx"=dword:00000004
"SideMarginPx"=dword:00000004
"BottomMarginPx"=dword:0000000a
"MinThumbSizePcent"=dword:00000064
"MinWidthPx"=dword:0000012c
"TopMarginPx"=dword:00000020
"MaxThumbSizePx"=dword:000000c8
"MaxIconSizePx"=dword:000000fa
"TextBottomPx"=dword:000001f4
####/Snippet####

To revert back to the original settings, remove the added key. "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\AltTab"


I also use a Logitech mouse that has 6 buttons. The mouse comes with it's own Document Switch feature, but I hate how they implemented it. A comment on the post I mention above recommended assigning this hotkey to a mouse button to make changing window focus even easier. On my Logitech mouse, I replaced their document switch button with the Ctrl + Alt + Tab hotkey (as recommended) which keeps the Alt+Tab selection window open indefinitely, so that you can click a thumbnail at your leisure... Very handy!


I am now using both of these tweaks and switching windows focus has never been easier, faster, or more intuitive. You should try it out.

Thursday, September 06, 2007

WPF - Error 3 API restriction: The assembly 'file:///C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStu

I was getting any annoying error (see below) in Visual Studio 2008 (Team System) Beta II after doing an SVN update. Every time I would try to compile our solution, I would get an error in our UnitTest project. The error was complaining that the UnitTestFramework.dll was being loaded from two different locations within the same appdomain.

"Error 3 API restriction: The assembly 'file:///C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll' has already loaded from a different location. It cannot be loaded from a new location within the same appdomain."

The problem was that two of the projects in our solution were referencing UnitTesting DLLs. For some reason someone added references to the following two libraries in our DAL project, and the compiler was throwing a fit that the UnitTestFramework dll was getting loaded from two different locations within the appdomain.

  • Microsoft.VisualStudio.QualityTools.UnitTestFramework
  • Microsoft.VisualStudio.TeamSystem.Data.UnitTesting

Removing these two (unneeded) references from our DAL project fixed the issue, but the error seemed a bit vague.

(NOTE: You may need to close and then reopen Visual Studio since the library might still be loaded...) =( Took me 10 minutes to figure this out...)

Thursday, August 16, 2007

xkcd.com Excuse for legitimately slacking off Comic

A coworker passed this around the office the other day. I thought it was great, so I figured I'd share.


Check it and others out at xkcd.com!

Wednesday, August 01, 2007

Microsoft Messenger Scam/Hoax/Virus - www.messengerstatus.biz

If you get an instant message with the following message, don't click on it. If you MUST click on it, don't enter your username and password.

"Did someone delete you from their MSN? Check http://www.messengerstatus.biz it's really good and it works!!!"

The site asks for your Microsoft Messenger username and password, then I believe that it promptly logs onto your messenger account and sends the same message to all of your contacts.

If you HAVE registered. Change the password of your Messenger E-mail account ASAP, and be more careful!

I've gotten a lot of these IM's today from people on my contact list, and figured I'd post a warning...

Sunday, July 29, 2007

Impressive HTML Skills...

In this video, some kid creates a picture by hand coding HTML. Impressive if you've got any experience with HTML. I wonder how long this must have taken him?

Check it out here...

Friday, July 27, 2007

Visual Studio 2008 Beta 2 Released!

The Beta 2 release of Visual Studio 2008 has been released and is available for download from the HERE. This release sport the following new features.

  • VS 2008 Multi-Targeting Support
  • VS 2008 Web Designer and CSS Support
  • ASP.Net Ajax and JavaScript Support
  • Language Improvements and LINQ
  • Data Access Improvements with LINQ to SQL
  • And much much more...

Check out Scott's post here for more details...

Tuesday, June 26, 2007

Vista, IIS7 & DotNetNuke - NullReferenceException at GetEnabledLocales()

Upgraded to Vista with IIS7 and started getting an error when trying to run an existing DotNetNuke ASP.Net project I've been working on.

Here's a snippet from the stack trace...

DotNetNuke.Services.Exceptions.PageLoadException: Object reference not set to an instance of an object. ---> System.NullReferenceException: Object reference not set to an instance of an object. at DotNetNuke.Services.Localization.Localization.GetEnabledLocales()

Was able to figure this one out after playing with the IIS7 settings for a while. You need to update your IIS application to use a different application pool than the default. Right click on your application in IIS and select Advanced Settings. Under Behavior change the Application Pool from DefaultAppPool to Classic .NET AppPool.

That should clear up this issue for you.

Monday, June 25, 2007

Pandora's Box - Play Pandora minimized or in your system tray...

If you have read my post about iTunes vs Pandora, you'd know that I dig the new online service for streaming tunes at work. The only problem with the service, in my opinion, is that you need to leave a browser window open while listening...

I started to look for a solution to allow you to either minimize your Pandora or play it in your System Tray. I found a cool little app that lets you do just this. You even get a nice context menu from the system tray icon that allows you to issue commands to Pandora without having opening it.

Makes Pandora even better IMO! Check it out.

Installing Infragistics on Vista Ultimate with IIS 7.0

I just upgraded to Windows Vista this weekend and am trying to get my development box up and running. We us Infragistics in a couple of our ASP.Net projects and I'm finding that it's not quite as straight forward to install it on Vista.

I found a great site with a walk-through of how to setup your Vista and IIS to allows Infragistics to install correctly.

Basically you need to do the following...

  • Disable User Account Control (UAC)
  • Restart your machine
  • Edit the path of your IIS WWWRoot folder in the registry
    • Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\PathWWWRoot
    • Change "%SystemDrive%\inetpub\wwwroot" to "C:\inetpub\wwwroot"
  • Enable IIS 6.0 Compatibility in the "Turn Windows features on or off" section of the Programs menu (make sure to check all the child boxes)

That should allow you to get your infragistics installed on Windows Vista Ultimate and IIS 7.0.

Developing on Windows Vista

I recently took the plunge and installed Vista Ultimate on my Dev box. I'm sure this will have it's ups and downs, but on the bright side... It will most definitely spawn lots of blog posts.

I will be installing Orcas soon and playing around too. I will also be focusing as much as I can on WPF, WCF, and WWF, so I'm sure I will have a lot of fun stuff to blog about for the next few months (after I get back from my Honeymoon that is. Yay for Hawaii...!)

Wednesday, June 20, 2007

Oracle - Returning newly inserted row's primary key using "returning" keyword. Using a select statement instead of values and getting &q

This goes along with my last post. We were trying to use the returning statement to return the value of a newly inserted row when using an OracleDataAdapter and Parameter.Direction = ParameterDirection.ReturnValue. The difference is, we were using a select statement instead of values() as our input parameters.

Here is a simple example...

OracleDataAdapter oda = new OracleDataAdapter();
oda.InsertCommand = RemedyMD.CreateCommand();
oda.InsertCommand.CommandType = CommandType.Text;
oda.InsertCommand.CommandText =
"INSERT INTO users (name, email) (select name, email where firstName = :firstName) returning userID into :out";
oda.InsertCommand.Parameters.Add("firstName", OracleType.VarChar);
oda.InsertCommand.Parameters["firstName"].Value = firstName;

oda.InsertCommand.Parameters.Add("out", OracleType.Number);
oda.InsertCommand.Parameters["out"].Direction = ParameterDirection.ReturnValue;

oda.InsertCommand.ExecuteNonQuery();

When you try to execute this query, you will get an oracle error. ORA-00933: SQL command not properly ended. After researching this for a couple of hours trying to figure out how to get it to work, I found out that there is NO way to get it to work. Either you have to use Values() instead of your select statement, or perform a second statement to retrieve the newly created primary key value.

Oracle - Getting the primary key value of a newly inserted row using the "returning" keyword and an OracleDataAdapter

I learned how to use an OracleDataAdapter Parameter as an "out parameter" by setting it's direction = ParameterDirection.ReturnValue. Using this with an insert statement is a great way to return the primary key value of the newly inserted row.

Here is a simple example...

OracleDataAdapter oda = new OracleDataAdapter();
oda.InsertCommand = RemedyMD.CreateCommand();
oda.InsertCommand.CommandType = CommandType.Text;
oda.InsertCommand.CommandText =
"INSERT INTO users (name, email) VALUES (:name, :email) " +
"returning userID into :out";

oda.InsertCommand.Parameters.Add("name", OracleType.VarChar);
oda.InsertCommand.Parameters["name"].Value = userName;
oda.InsertCommand.Parameters.Add("email", OracleType.VarChar);
oda.InsertCommand.Parameters["email"].Value = userEmail;

oda.InsertCommand.Parameters.Add("out", OracleType.Number);
oda.InsertCommand.Parameters["out"].Direction = ParameterDirection.ReturnValue;

oda.InsertCommand.ExecuteNonQuery();

After executing the query, you can then pull the returned value out like this...
int  newUserId = -1;

if(int.TryParse(oda .InsertCommand.Parameters["out"].Value.ToString(), out newUserId)){

// Perform additional query that required the newly inserted row's primary key

}

It was fairly hard for me to find (google) this information, so I figured I'd post it in hopes that it would help someone else.

World of Warcraft /Played Total - Can you beat this...?

I quit playing World of Warcraft (WoW) a while back after playing off-and-on since release. I was determined to quit for good, so I actually canceled my account, logged onto my character and sold everything of value, sent it to a good friend who played and deleted all of my characters (mainly a decently equipped 70 rogue.) This astonished many of the people I work with who play WoW, and I thought the reactions I got were truly amazing (and hilarious.) At the time of my rogue's deletion, I think he had a /played in the high 40's (days.) That's a lot of time to have played a video game, even if it was over 2.5ish years... (p.s. I know that I could have sold my account for some decent $$, but I didn't really want someone else playing my toon. Call me crazy. =) )
Back to the point of this post... I have a friend (we'll call him Bob) that I went to school with, and now work with. Bob has played WoW since it was released on November 23, 2004, and continues to play to this day. Most people I know who have played WoW at one point or another got a single character to 60 (now 70) and then mainly played that character with a few sporadic alts here and there. Not Bob...
Bob has 11 character over the level of 60. That's fairly impressive and got me thinking. Just how much time has Bob spent playing WoW since releases. I asked him to get the /played totals on each of his characters so that we could add them all up. I asked a few people around the office to venture a guess at just how much time he's played WoW. I started it off with a guess of 250 Days played.
The rest of the guesses looked something like this...
250, 215, 190, 285, 280, 260, 260, 330, 150, 331, 332 DAYS played!
By this time, the rest of the office had gathered around in awe at our guesses. How could someone play a game "that" much...?
Here is what his characters and /played values look like...
Character # Level Days Hours
1 62 8 18
2 61 8 22
3 65 8 10
4 63 14 19
5 66 17 17
6 70 24 7
7 65 30 7
8 70 24 19
9 70 38 17
10 69 19 5
11 70 62 10
Totals 252 151
Interesting Information Based on these numbers!
Total Days Played: 258.29
Total Hours Played: 6199
WoW Release Date: November, 23, 2004
Date We Did This: June, 19, 2007
Total Days/Hours in between: 938 / 22512
% of time that Bob played WoW during this time: 27.54%
That means... In a span of about 2 years and 7 months, Bob was playing WoW about %27 of the time!
All I can say is... wow. Can anyone out there post more impressive numbers...? I know you guys are out there. The uber gamers!!! Hell, you might be reading this while raiding RIGHT NOW.... We want your numbers! =) Add a comment below...!

Thursday, June 14, 2007

iTunes radio streaming vs Pandora...!

I've been a long-time iTunes user (ever since I stopped using winAmp religiously a few years ago...) I have a ton of MP3s, an iPod, and have been a huge fan of streaming radio feeds while at work or home and not into anything I have in my playlist. There are a ton of stations to choose from, almost any genre, style, country of origin... You name it an you can probably find it on iTunes'...

I heard about Pandora a few months ago and just barely got around to trying it out. I must say, from the second I entered my first artist into Pandora, I've loved it. It started playing one of my favorite songs by that artist immediately and the sound quality was amazing. As I started to fiddle with the site, the power of the idea hit me. Not only play the songs and artists that I suggest to you, but infer what else I might like by my choices... Why didn't they have this years ago...?

If you really like or dislike a new song that comes up, click on the up or down thumb icon and it will update your preferences and modify what comes next... Pandora starts to learn what you like by your interactions with the site. Wether you're adding new songs or artists, or just rating the new stuff they throw at you, you are helping Pandora send you just the types of music you want to hear!

I've only been using the site for one full day now, but I'm already a fan... I've only loaded up iTunes once and that was to update my iPod for a workout. =) We'll have to see if Pandora takes over my streaming audio needs, and even pulls me away from my MP3s. What better way to be introduced to new artists and songs that you might love as much as your preferred artists...

You can even create new Pandora "Stations" which you can customize to a certain type or style of music. I have one for Hard & Fast, Soft & Chill, and Techno so far and can imagine quite a few more that I would want to listen to based on my mood...

If you haven't yet, check it out. =)

Virtual Stock Trading anyone...?

I've been participating in a company game of Virtual Stock Exchange (VSE) that we have running at my current employer. We have about 12 people in the game and it's pretty fun to see how everyone invests, and how well it pans out. If nothing else, it's good to get a better understanding of the markets.

The game is somewhat realistic because it's based off the market and only lags a bit behind. Josh and I setup an Open Game of VSE that anyone can join and participate in. If you're interested, come and create an account and invite your friends and family!

Use the information and directions below to join the game.

Game ID: ezcomeezgo
Game Password: ezcomeezgo

  1. Open this link and read the competition summary:
    http://vse.marketwatch.com/Game/StartViewGame.aspx?id=ezcomeezgo
  2. Click on the 'Join Game' link.
  3. If you are an existing Virtual Stock Exchange member, enter your Email address and Password in the login panel and get set to trade. If you are a new user, follow the link to register - it's easy!
  4. Follow the instructions and start trading!

Join now, and see if you can win my Open Game competition! The more participants the higher the level of competition.

Web Services, IDictionaries and Serialization... Oh My!

I have been building some .Net web services lately and created one that was trying to return a generic IDictionary. (IDictionary<int, int>) To my surprise and ultimate disappointment, I was presented with the following Server Error when trying to access my webservice...

"The type System.Collections.Generic.Dictionary ..<removed babble>.. is not supported because it implements IDictionary."

It looks like the XmlSerializer is unable to serialize objects that implement IDictionary. How annoying! I use a lot of generic dictionaries and it's a bit of a pain work around this XmlSerializer limitation. I was able to find a solution from this Aaron Skonnard post on the msdn site.

The solution shows you how to write a class that actually wraps your dictionary object. The values of your dictionary are copied to an array of serializable objects which are allowed to be passed through your web service and then deserialized on the other end. Pretty handy and worked really well in our solution.

Aaron warns that the IXmlSerializable interface is undocumented/unsupported feature of the .Net Framework and is subject to change at any time.

Tuesday, June 05, 2007

Apple announces new and improved MacBook Pro...!

The MacBook Pro gets a Face-Life (not that it needed one.) Apple announced that it's MacBook Pro line will be getting a boost with bigger processors, beefier graphics and more space for memory!

The new stats for the three models are...

  • A 15.4-inch version for $1,999
    • 2.2 GHz Intel Core 2 Duo
  • A 15.4-inch version for $2,499
    • 2.4 GHz Intel Core 2 Duo
  • A 17-incher for $2799
    • 2.4 GHz Intel Core 2 Duo

All versions of the new MacBook Pro can support 4GB of RAM instead of just 2GB like the last generation. The newly available video card is Nvidia's GeForce 8600M GT card. The upgraded processors are Intel's latest version of the Centrino, code-named the "Santa Rosa".

I find that I'm having a really hard time NOT being able to justify buying a MacBook Pro, and this new announcement makes that decision even harder! They are sexy, powerful, and have the ability to run both Windows and Mac operating systems. What's not to love...!?!

Friday, June 01, 2007

Firefox 2 - Saved Password Security

Do you use the "Remember passwords for sites" feature in Firefox 2...? It sure is nice to not have to enter your password into those pesky "secure" sites out there like your Banking, E-mail, or other such sites...
It's also great that I don't even have to enable this feature, it just prompts me to start storing passwords after I start using Firefox for the first time! Firefox is great! So lets just assume that the 2nd most popular web browser is appropriately handling this extremely sensitive data.
Or should we...?
How simple could it be for someone to get access to these stored passwords...? As it turns out, using Firefox's default settings (Which I'm sure MOST people are), it's EXTREMELY easy.
All a person needs to do to gain access to your stored passwords in Firefox, assuming that they have a moment's access to your workstation is to perform the following steps...
  1. Click on Tools
  2. Select Options
  3. Click the Security Tab
  4. Click Saved Passwords
  5. Click Show Passwords
This handy-dandy feature supplies the user with a list of web site addresses, user names, and Password (in PLAIN TEXT no less!) This gives a potentially malicious user direct access to everything that they need to find and log into any sites that you have setup to "Remember my Password"! The worst part about all of this is that this is the DEFAULT behavior in Firefox!
This, in my humble opinion, is a huge security flaw in Firefox and I'm blown away by how easy it is for people to unknowingly expose their user names and password to anyone with a few seconds access to their browser...
Posting this information is a double edged sword. On one hand, it alerts potentially "malicious users" to a way to gain access to your passwords. That is not my intentions. On the other hand, getting this information out to as many people as I can (and please help me ein this effort) should allow you to protect yourself from this vulnerability.
So, how can I protect myself?
In Firefox
  • Disable the "Remember password for sites" feature or Setup the "Use a master password" feature in Firefox! These can both be setup in the same place as the "Show Passwords" option listed above!
In General
  • Always lock your workstation when you walk away from it. I never assume that I can trust anyone with free access to my workstation, and I recommend that you do the same!

How to sort a generic IList<T>

Sorting a generic IList
I was trying to sort a generic IList<> and found a fairly simple way of doing it.
Step 1
You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.
public class LanguageDto : IComparable {
private String name;
public string Name { get { return name; } set { name = value; } }

public LanguageDto(string name) {
this.name = name;
}

#region IComparable Members
public int CompareTo(object obj) {
if (obj is LanguageDto) {
LanguageDto language = (LanguageDto)obj;
return this.name.CompareTo(language.name);
}
throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString()));
}
#endregion
}

STEP 2

Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so...

ArrayList.Adapter((IList)languages).Sort();
Note: languages is of type "IList<LanguageDto>"
Languages should then be a sorted list of your type!

Thursday, May 31, 2007

Windows Live Writer Beta 2 Now Available

And what better way to test it than to post a new blog announcing it! If you're reading this, then it works FINE!

Get your copy HERE!

Tuesday, May 29, 2007

Web Service Security (Invalid URI: The format of the URI could not be determined)

Ran into an issue today while trying to connect to a Java Web Service from a .Net environment. It looks like this happens when Web Service Security is enabled in the application server of the web service and uses the ActorURI attribute. .Net's Web Services Enhancements feature does not support relative URI's for this attribute and basically FUBAR's on you. Therefore, you must us an absolute URI.

An example of an absolute URI is "http://LoginWebService" while an example of a relative URI would be "LoginWebService"... You must configure your Application Server to using either the Rational Application Developer or the Application Server Toolkit.

  1. Open the Web Service Editor, click the Extensions tab and expand Server Service Configuration.
  2. Enter the full absolute URI in the Actor field.
  3. Expand Response Generator Service Configuration Details > Details.
  4. Enter the full absolute URI in the Actor field.

Source

Saturday, April 28, 2007

Firefox and Memory Usage

Firefox can be a memory hog, but is the browser really to blame...? I am currently waiting for my second gig of memory at my new job, and I've had to do a few tweaks to keep this baby humming along with it's single gig. I've noticed that Firefox has been quite the memory hog lately with an average memory usage around 170 megs. I did a bit of research and found a couple of things that seem to help.

Add-Ons

Not all add-ons are created equal...! I use a few Firefox add-ons every day at work, and never really thought that they might be causing problems. Some add-ons straight up contain memory leaks (cybernetnews) that will eat up your available memory when using them in Firefox. Just having a few add-ons "enabled" in Firefox is enough to bloat your memory usage, even if they are only used every once in a while. You might want to play around with enabling and disabling your favorite (or not so favorite) add-ons to see which might be causing the bulk of your Firefox related memory issues.

Config

I also found a helpful tip (here) that allows you to specify that Firefox should not be loaded into memory when minimized. Just by minimizing firefox, you can clear up a lot of the lost memory (look at firefoxes memory usage before and after a minimize.)

  1. Open Firefox and go to the Address Bar. Type in about:config and then press Enter.
  2. Right Click in the page and select New -> Boolean.
  3. In the box that pops up enter config.trim_on_minimize. Press Enter.
  4. Now select True and then press Enter.
  5. Restart Firefox.

Firefox might maximize a bit slower with this fix because the browser will be moved from memory to your HD but I haven't noticed any difference.

I have a friend that constantly has at least three firefox windows open with about 10million tabs open in each. I'd imagine that a fix like this might help out a bit on his firefox memory usage. =) I'm not nearly that bad, and it's already helped a ton...

Sunday, March 04, 2007

Sending mail through Gmail Programatically - C# .Net VS2005 Gmail

I was implementing a simple Contact Us form for a friend's website that would allow users to shoot him an E-mail message from the site. You can send E-mail directly from a .Net application using an SMTP server, but most free web-based E-mail companies wont allow you to use their SMTP servers for stuff like this. I was delighted to find that you could get this working with Gmail. I'll show you a quick sample method that will allow you to do this.
Information You'll Need...
  1. Your Gmail information (Username, Password)
  2. The Gmail SMTP server address (smtp.gmail.com)
  3. The port Gmail uses (465 or 587)
Namespaces used...
  1. System.Net;
  2. System.Net.Mail;
  3. System.ComponentModel;
Key Objects...
  1. MailMessage
  2. SmtpClient
Your Configuration File
<appSettings> <add key="pswd" value="YourGmailPassword"/> <add key="account" value="yourUserName@gmail.com"/> <add key="host" value="smtp.gmail.com" /> </appSettings>
Implementing a simple SendMail method
public void SendMail(string host, int port, string userName, string pswd, string fromAddress, string toAddress, string body, string subject, bool sslEnabled) { MailMessage msg = new MailMessage(new MailAddress(fromAddress), new MailAddress(toAddress)); // Create a MailMessage object with a from and to address msg.Subject = subject; // Add your subject msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.Body = body; // Add the body of your message msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = false; // Does the body contain html SmtpClient client = new SmtpClient(host, port); // Create an instance of SmtpClient with your smtp host and port client.Credentials = new NetworkCredential(userName, pswd); // Assign your username and password to connect to gmail client.EnableSsl = sslEnabled; // Enable SSL try { client.Send(msg); // Try to send your message ShowMailMessage("Your message was sent successfully.", false); // A method to update a ui element with a message Clear(); } catch (SmtpException ex) { ShowMailMessage(string.Format("There was an error sending you message. {0}", ex.Message), true); } }


Calling your SendMail method

public void imgSubmit_Click(object sender, EventArgs e) { string pswd = ConfigurationManager.AppSettings["pswd"]; // Your Password string account = ConfigurationManager.AppSettings["account"]; // Your account name (username@gmail.com) string host = ConfigurationManager.AppSettings["host"]; // Your smtp server name (smtp.gmail.com) int port = 587; // The port used to connect to your host if (string.IsNullOrEmpty(pswd) || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(host)) // Validate App Settings ShowMailMessage("Unable to send your message. Configuration Error.", true); else { SendMail(host, port, account, pswd, txtFrom.Text, account, txtBody.Text, txtSubject.Text, true); } }
That's pretty much all there is to it. Your user fills out the form and clicks submit, and you get an E-mail in your Gmail box, send through your Gmail Account

Debugging ActiveX Controls in VS2005 (Attaching To a Process)

I already wrote a post about creating ActiveX controls in Visual Studio 2005. To make life a bit easier, I'm going to tell you how you can debug an ActiveX control that you have built and embedded into your web page.

I deployed my web page to IIS and then bring it up in the browser (http://localhost/ActiveXTest/Default.aspx.) Once you have the page up and can see your ActiveX control, switch to Visual Studio and click on the 'Debug' menu item. Click on 'Attach to Process'.

On the Attach to Process screen, click on 'Select...' next to the Attach to: label. Select Managed Code and click on 'OK'. In the Available Processes section, select 'iexplore.exe' and click on 'Attach'.

That's all there is to it! You should now be able to place break points into your control and debug. (Assuming that there are no issues with your implementation that would prevent you from even getting to the control.)

Creating ActiveX Controls using C# in VS2005

This will be a short tutorial on how to create a simple ActiveX control that opens a windows forms Message Box while living in an aspx page. Pretty useless, I know, but it will illustrate the basics of how to create and interact with an ActiveX control from a web page in Visual Studio 2005.
A co-worker and myself worked on this for a current project and found bits and pieces of this information and figured it would be a great resource to compile it all into one location. It can get a bit tricky (especially if you add in security issues when handling ActiveX control events) but its not too bad.
Step 1
This first step in this tutorial is to create a web project in Visual Studio. I called mine ActiveXTest.
Step 2
Next, add a new Windows Control Library project to your solution.
This project is where you will develop your ActiveX control. Rename the default user control cs file and double click on it to open up the designer. You can build your control just like you would any other Windows User Control by adding controls and code-behind as necessary. This example doesn't need any controls, but I'll add a picture box just so that we can see it on the aspx page.
Step 3
Now that our project is setup with a web project, a Default.aspx page and a Windows Control Library with our new User Control in it, we are ready to turn the User Control into an ActiveX control by exposing and implementing an interface.
Next, create in interface that will expose parts of your ActiveX control to the browser.
public interface IComInterface { string Msg { set; } // Exposes the Msg property through the interface }
Implement this interface in your User Control.
public partial class MessageBoxControl : UserControl, IComInterface { // Implement IComInterface public string Msg { // Implement the Property set{ MessageBox.Show(value); } // When the property's set is called, show the message box } public MessageBoxControl() { InitializeComponent(); } }
You have just created an ActiveX control that is ready to be embeded in a web page and exposes a property (Msg) to COM through an interface (IComInterface).

Step 4

The next step is to embed your newly created ActiveX control in your web page (Default.aspx.) To do this, you will use the <object> tag like this.
<object id="MessageBoxControl " name="MessageBoxControl " classid="ActiveXControls.dll#ActiveXControls.MessageBoxControl "> </object>
The id and name should be self explanatory. The class id is comprised of the name of your dll file, a # sign, and the namespace.classname of your control. That's all it takes to embed the control into your page. There are a couple of thing you will need to do to allow this to happen, but the coding is done.

Other things to consider...

1. You must have a copy of your Windows Control library dll on the same level of your web project as the default.aspx page. The dll cannot contained in the bin folder.
2. Add your local computer as a trusted zone through Internet Explorer. This will help bypass some of the security issues inherent with ActiveX controls. Do this through the Internet Options of Internet Explorer.
3. You may need to increase the trust level of your assembly before it will load correctly in Internet Explorer. You can do this from the .Net Configuration Tool located in the Administrator Tools of the Control Panel. (Configure Code Access Security Policy -> Increase Assembly Trust)
4. Strongly name your ActiveXControl assembly. (Note: You can do this through the properties page of the project.) This must be done prior to registering the dll in the gac.
5. You may also need to register your assembly/dll in the gac before it will work. You can do this by using gacutil from the command line from the directory of your dll. (gacutil /i ActiveXControls.dll) (Note: You might have to do this after every build of the project.)
6. Modify your AssemblyInfo.cs file and change the ComVisible attribute to true. ([assembly: ComVisible(true)]) This is maily when you want to expose ActiveX control events to your web page.
7. Set ISS so that Execute Permissions on your Virtual Directory are set to "Scripts Only". This is the only option in ISS that would work for me when deploying the ActiveX control and accessing it remotely and was a pain to track down.
Step 5

You can then access properties of your control exposed through your interface by using JavaScript on that page. Something similar to this.
<script type="text/javascript"> function showMessageBox(){ var control = document.getElementById('MessageBoxControl'); control.Msg = document.getElementById('txtMsg').value; } </script>
Tips/Tricks

You can add a build event to your Windows Control Library project that will automatically copy it's dll to the web project when you build it. Open the properties of the project by right clicking on it and add a line like this to the build events.

copy "$(TargetPath)" "C:\Projects\vs2005\ActiveXTest\ActiveXTest"

Creating ActiveX Controls using C# in VS2005 (Intro)

We recently had a need to handle communication between an existing windows service (Running on client machines) and the current ASP.Net web application that we are working on. We chose to implement this feature using .Net Remoting and an ActiveX Control that would live on one of our aspx pages.

Implementing an ActiveX control in VS2005 using C# isn't difficult, but there are a lot of little issues that a co-worker and I encountered along the way.

I'll try and list the results of my research and a walk-through of creating a sample project. This will probably span several posts.

The steps that I will cover... Check it out HERE!

1. Create a C# Web Application project

2. Create a Windows Control Library project

a. Note: The Windows Control Library DLL file must be located in the same directory as the aspx page and NOT in the bin folder.

3. Add a user control item to the class library project

a. Creating the user control

b. Implement an Interface on your user control that will exposes members, methods, and events of your user control to COM

4. Create an object in your aspx page that embeds your user control

5. Handle communication between your web application and your ActiveX control using JavaScript

6. Expose and raise/handle user control events using javascript

7. A brief overview of configuring the .Net Framework and zone permissions to allow your web application and ActiveX control to communicate

8. Configuration issues with IIS (set to allow scripts only, not scripts and exes)

9. How to view IE7 error messages to get the exact exception that might be causing you problems.

Check it out HERE!

"Unrecognized configuration section 'connectionStrings'" .Net 2.0

If you get the following error when trying to bring up your IIS hosted web page, you might need to configure IIS to use .Net 2.0 instead of 1.1.

""Unrecognized configuration section 'connectionStrings'" .Net 2.0"

You can do this through the Internet Information Services configuration. (click on RUN from the start menu, type in 'inetmgr' and hit enter.)

Bring up the properties for your web page or virtual directory and click on the ASP.NET tab. Change your ASP.NET version to the appropriate value and try again.

Monday, January 29, 2007

Centering an Element via CSS vs JavaScript...

We recently ran into a situation where we were dynamically showing and centering model popup windows in an ajaxified environment. Our initial implementation had one down side.

We were showing and dynamically centering our div/panels via JavaScript. The windows would very briefly show up in its default location before jumping to center. Not a huge problem, but very annoying.

Our initial approach looked something like this. Statically build a hidden div/panel and when the user triggers a pop up dialog, call the CenterPanel method from JavaScript and show the panel. We were calculating the screen height and width and making it available globally.

The JavaScript process looked something like this...


CenterPanel("<%= SendToGeneralQueuePopupPanel.ClientID %>");


function CenterPanel(panelId){
var panel
= document.getElementById(panelId);
if (panel) {
panel.style.top
= ((screenHeight / 2) - (GetSize(panel.style.height) / 2)) + 'px';
panel.style.left
= ((screenWidth /2) - (GetSize(panel.style.width) / 2)) + 'px';
}
}

The result was a panel that would show up, then jump to the center of the screen. (Annoying)

After getting a bit of time to think about the issue, I remembered a much simpler way to center a control with pure CSS rather than dealing with problematic JavaScript at all. I'd used this technique in other projects and it makes things quite a bit more simple and stops the panel from jumping around the screen.

The CSS method...

We define a Panel to use as the pop that applies our modalPopup CssClass. Notice that the panel's Width is 200 and it's Height is 60.

<asp:Panel ID="PanelPopup" runat="server" CssClass="modalPopup" Width="200" Height="60">
<div style="text-align:center;">
Are you sure you wish to continue?

</div>
<div style="text-align:center;">
<asp:Button ID="ButtonYes" runat="server" Text="Yes" OnClick="ButtonYes_Click" />

<input id="ButtonNo"
type="button" value="No"
onclick="return HidePopupPanel('PanelPopup', '<%= PanelPopup.ClientID %>');" />
</div>
</asp:Panel>

The modalPopup CSS...

.modalPopup{
//Other CSS
left:50%;
margin-left:-100px;
top:50%;
margin-top:-30px;
}

The CSS above sets the left edge of the panel to be aligned with the center of the browser and then adjusts the left margin of the panel by subtracting 100 pixels (which happens to be half of the panel's width.) This centers the panel horizontally. In the same way, the panel is centered vertically by setting the top of the panel to the middle of the screen and then adjusting the top margin by subtracting 30 pixels which is half of the panel's height.

You can do a lot of fun stuff by using this technique. Setting the left, top, right or bottom of a control and then modifying the margins. Play around with it...

Friday, January 26, 2007

Session Management - Facade Pattern - C# .Net VS2005

State Management is a big part of any web application and using the session variable in ASP.NET is one way to persist data throughout a user’s session. Interacting with the session variable is fairly straight-forward…
Session["UserId"] = user.Id;
int id = (int)Session["UserId"];
Session[
"FirstName"] = user.FirstName;
string fName = (string)Session["FirstName"];
You can store any object or primitive into the session variable and retrieve the value at any time throughout the user’s session.

As you might imagine, your project could get fairly convoluted if you are accessing the same (or many different) session variable across many different pages throughout your application. Using explicit string values as your keys can also cause problems if you accidentally typo when entering them or decide to change one later. Throw several developers into the mix and this can turn into a nightmare.

You can alleviate some of this frustration by using an enum that contains all of your session key values. This allows you to make changes much easier, provides a quick reference to what objects you have in the session, and makes calls to the session variable consistent. The new session calls (with the help of an enum) would look like this.
enum SessionKeys {
UserId
= 1,
FirstName
= 2
}
Session[SessionKeys.UserId .ToString()]
= user.Id;
int id = (int)Session[SessionKeys.UserId .ToString()];
Session[SessionKeys.FirstName .ToString()]
= user.FirstName;
string fName = (string)Session[SessionKeys.FirstName .ToString()];
Taking this a step further, you could wrap this functionality into a static class in your project and route all session traffic through this class. By wrapping session calls in properties within this class, you can ensure type safety and make it much more easy to work with the session object.
public static class SessionFacade {
public static int UserId {
get {
return (int)Session[SessionKeys.UserId.ToString()];
}
set {
Session[SessionKeys.UserId.ToString()]
= value;
}
}
public static string FirstName {
get {
return (string)Session[SessionKeys.FirstName.ToString()];
}
set {
Session[SessionKeys.FirstName.ToString()]
= value;
}
}
}
Sessions calls would then look like this.
int id = SessionFacade.UserId;
SessionFacade.UserId
= user.Id;
string fName = SessionFacade.FirstName;
SessionFacade.FirstName
= user.FirstName;
The SessionFacade class acts as a Facade between you and the session object and alleviates much of the frustrations mentioned above. No more misspelled keys, no more huge updates if you want to change a key. Type safety... Who could ask for more?