Posts

Showing posts from 2009

Asp.Net MVC, Forms and Missing Values

Remember, Asp.Net requires that you use the Name and not just ID on your form controls. If you don’t, they don’t come along for the ride to your controller.

RedBox “Verify Your Subscription” Emails

Anytime I get an unsolicited email saying “verify” something, I’m suspicious. I’ve gotten three of these emails lately. Checking the links, they seem to be genuine. I also found this on Facebook, that seems to indicate they are real. Did notice that lady hadn’t been able to use her code. Think I’ll give it a try and see what happens.

Cache and Compress in Asp.Net MVC

Image
Found a good entry on caching at the user browser and compressing the response. Note: It’s from some early beta stuff so be sure to change FilterExecutingConext to ActionExecutingContext. More on that here . Enjoy! Subscribe in a reader

Dell Inspiron 1525, Sleep Mode and Magentic Bracelets

File this in the Hmmm category. Apparently Dell uses a magnet for detecting if the lid has been closed. If you (or your wife) is wearing a magnetic bracelet and it gets close to the sensor, your computer will go to sleep. Leading your wife to yell in frustration. I do need to give her credit, she did figure out it was the bracelet.

Silverlight 3 Page Not Found error

I was working on a project when all of the sudden I started getting a “Page Not Found” error. Of course the page is there and it had been working fine. Turns out it was the templates infrastructure hiding the error from me. When you create a new SL Navigation Application, you’ll find the following in your MainPage.xml.cs. // If an error occurs during navigation, show an error window private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { e.Handled = true; ChildWindow errorWin = new ErrorWindow(e.Uri); errorWin.Show(); } This nice little piece of code hides the real cause of the error so that all you see is Page Not Found. Bryant Likes has some code that will give you a better idea of the error. // If an error occurs during navigation, show an error window private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { Exception ex = e.Exception; while (ex.InnerException != null) { ex =

Nice Drop Shadow Border in XAML

I was working with Silverlight 3 and created this drop shadow border. Enjoy. <Style x:Key="DropShadow" TargetType="Border"> <Setter Property="Background" Value="WhiteSmoke" /> <Setter Property="CornerRadius" Value="5" /> <Setter Property="BorderThickness" Value="1,1,4,4" /> <Setter Property="Margin" Value="10" /> <Setter Property="Padding" Value="6" /> <Setter Property="BorderBrush"> <Setter.Value> <LinearGradientBrush> <GradientStop Color="#ccc" Offset="0" /> <GradientStop Color="#ddd" Offset="1" /> </LinearGradientBrush> </Setter.Value> </Setter> </Style>

Using Interfaces, Generics and the Repository Pattern

Image
I’ve been using the repository pattern to insulate my apps from the LINQ to SQL so that I can easily change when (or if) MS kills L2S. The nice thing about this is that I can write a generic repository the encompasses some of the tasks so that the code is consistent for all repositories. A little background first. We name all our tables the plural of the objects contained and the first column is an integer primary key named in the singular followed by a “Key” suffix. For example, the Customers table has a first column of CustomerKey. This key name is then used in all related tables as the foreign key column. This makes it very easy to come in behind someone and figure out the data structure. This convention gets in the way of making life easier for me because all items have a different name for the primary key. To fix this, created an interface called IPrimaryKey, shown below. public interface IPrimaryKey { int PrimaryKey { get; set; } } In my database model, I change the

Black Screen Of Death (KSOD) and a possible cause

I’ve run into my second instance of a KSOD (black screen with mouse pointer and nothing else). Both are laptops and both had similar circumstances. User closed lid and attempted to restart on the next day. Both got Windows started but then encountered problems, shutdown and met the KSOD. Theory: I believe what is happening is that the user has the system set to hibernate on the lid closing. This hibernation is occurring when an automated Windows update is in progress. The update then fails because of the hibernation and corrupts the system. Both systems get to CRCDISK.SYS and then die. The only solution I’ve found is to reimage or reinstall. I tried all of the registry changes, sticky keys and booting from another source. No luck. Solution: Upgrade to Win7, turn hibernate off and teach users to shutdown.

Jquery for Select All Checkbox

A very common interface is a list of items with a checkbox to select each and them you perform an action on those selected. Typically you have a checkbox at the top to toggle all of the list. This script will take care of everything for you. You can exclude elements by checking the ID or name properties. $(document).ready( function () { $( "#selectAllCheckBox" ).click( function () { var checked_status = this . checked ; $( "input[type=CheckBox]" ).each( function () { if ( this .id != "pleaseSkipMe" ) { this . checked = checked_status; } }); }); });

Ajax Call Issue

When making an Ajax call, remember to make sure that your target element can accept the result of your call. For example, if I return a string from my call to a target element of <p>, everything is fine. Replace that with a table and you’ll get the lovely message “htmlfile: Unknown runtime error”. Change to a <div> and everything is fine.

Asp.Net MVC Unit Testing Authorization

Asp.Net provides the Authorize attribute for checking to make sure you have an authenticated user and that they are in the correct role(s). Since this is part of the framework, I don’t need to test the attribute (that’s Microsoft’s job). I do want to test that I have applied the attribute with the correct properties. Here’s my unit test code for checking that the attribute has been applied. [TestMethod()] public void Autorization_Attributes_Have_Been_Applied() { MethodInfo[] methodInfos = typeof (CustomersController).GetMethods(BindingFlags.Public | BindingFlags.Static); foreach (MethodInfo methodInfo in methodInfos) { ParameterInfo[] parmInfo = methodInfo.GetParameters(); if (methodInfo.Name == "Create" | methodInfo.Name == "Edit" ) { var attributes = methodInfo.GetCustomAttributes( typeof (AuthorizeAttribute), true ); Assert.IsNotNull(attributes); Assert.AreEqual(1, attributes.Length); var authorizeAttribute = (AuthorizeAttribute)attributes[0]; Assert.IsTr

UpdateModel Unit Testing Gotcha!

If you’re unit testing and make a call to UpdateModel, you get the case where your object doesn’t get updated. Say your controller has an Edit Post action similar to: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Customer customer) { Customer _customer = repository.GetByKey(customer.CustomerKey); UpdateModel(_customer); repository.Save(); return RedirectToAction( "Index" ); } Now you might think that the call to UpdateModel will use your the object you passed in. Wrong! It wants the form values that get passed as part of the post request. So if you’re unit testing and using MVC fakes, you need to pass in some form values. Customer customer = new Customer() { CustomerKey = 1234, CustomerName = "ABC Siding" , Address = "1 Main" , City = "Springfield" , State = "IL" , ZipCode = "62701" , FirstName = "Fred" , LastName = "Jones" , Phone

Fake HttpResponse for Asp.Net MVC

Here’s an HttpResponse fake to go with Stephen Walther’s MVC Fakes . It’s based on his HttpRequest. If you need something for testing the cache, look here . public class FakeHttpResponse : HttpResponseBase { private HttpCookieCollection _cookies; private NameValueCollection _headers; private bool isClientConnected; private bool isRequestBeingRedirected; private TextWriter output; private Stream outputStream; public FakeHttpResponse( NameValueCollection headers, HttpCookieCollection cookies ) { this ._headers = headers; this ._cookies = cookies; } public FakeHttpResponse( NameValueCollection headers, HttpCookieCollection cookies, bool isClientConnected, bool isRequestBeingRedirected, TextWriter output, Stream outputStream ) { this ._headers = headers; this ._cookies = cookies; this .isClientConnected =

Unit Testing Asp.net MVC and the Cache

If you haven’t worked with Stephen Walthers MVC Tip #12 , you’re missing out on a great way to test your MVC controllers. He provides fakes for the ControllerContext, HttpContext, HttpRequest, SessionState and also mechanisms for testing authorization. You can download his code at the end of the post. I created a new project called MvcFakesForTesting and copied all of the classes. I did this so I can extend and grow the project. Stephen wrote his library with pre-release code, so I needed to change a couple of IController references to ControllerBase. I also created added Headers so that I can fake the request headers. Just implement this the same as QueryString and FormParams. Now I have the DLL that I will use on all of our projects for testing. I made sure to include a reference to Stephen so that credit is given where credit is due. One thing that is not included is a fake for the Cache. Of course, I ran into this on my first test! First of all, the Cache object is sealed / not

KVM Switch gives USB not recognized

My TrendNet TK409K KVM popped up with a “USB not recognized or malfunctioned” today. The solution I found was to unplug all of the USB connections for a minute. This apparently “resets” the box. Plug everything back in and away you go.

Make Internal Methods Visible for Unit Testing

Need to make your internal classes and methods visible to unit testing? Try the post . Works like a champ!

T-SQL to create an instance of an object with the properties set

Here’s some T-SQL to create a SELECT statement that will create the properties with values. I use this for generating test data from existing DB’s. Right now I’ve got it setup to handle int, char, varchar, smalldatetime, datetime and bit. I’ll add others as needed. @TableName is the name of the table where the data is stored. Simply set the table name hit F5 then cut and paste the generated script into the T-SQL that gets the data your looking for. This can be all rows in the table or a single row. The code: declare @TableName varchar (100) declare @ColumnName varchar (100) declare @DataType varchar (100) declare @ Sql varchar ( max ) declare @Crlf char (2) set @TableName = 'Clients' set @ Sql = CHAR (39) declare cols_temp cursor for SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE Table_Name = @TableName and data_type in ( 'int' , 'char' , 'varchar' , 'smalldatetime' , 'datetime' ,

What’s in a name?

I’ve worked on database projects for over 20 years. I go back to FoxBASE and dBase . I’ve also been through a number of naming conventions in that time. I’ve developed a personal preference but can work with other preferences because I can usually figure them out fairly quickly. Here’s two rules I use as part of my database designs: Use a surrogate or artificial key as the primary key to avoid the need for cascading deletes or updates. Use the natural name for each element so that elements are easily identifiable when in discussions with the user. I can’t tell you how much time I have saved over the years with rule 2. Users have no idea of your database design (and they shouldn’t!) but they know exactly which piece of information they want. It’s a whole lot easier if they can write “client’s birth date” in a report request and in the Clients table there is a field called BirthDate. My problem is lately, I’ve noticed that a lot of people seem to be using a convention t

Asp.Net Forms Authentication with Groups and Roles

I found this great post from Rob Convery on creating a FilterAttribute that can be used to authorize specific controller actions against roles. I’d always wanted to implement a Group strategy and had made several attempts. They all seemed like kluges and I was never really happy. One small change to Rob’s code and I can do grouping in a simple manner. Note: If you have a large number of roles and groups, this will probably not work for you. Also, this uses Asp.Net MVC. ok, Rob’s code basically checked for a single role and you could use a constant to supply the role name. Something like [RequiresRoleAttribute(RoleToCheckFor = ApplicationRoles.AdminRole)] public ActionResult Edit( int id) My change just allows you to pass more than one role into RoleToCheckFor.  Basically, I split RoleToCheckFor using a comma. [RequiresRoleAttribute(RoleToCheckFor = ApplicationRoles.ChangeClientsGroup)] public ActionResult Edit( int id) The ApplicationRoles class looks like this

T-SQL To Identify All Characters in a Column

When doing conversions, I often need to write a RegEx pattern for a column. This little query gets all the characters in a string. declare @ColName varchar (200) = 'Vin' declare @TblName varchar (200) = 'Units' declare @ sql varchar ( max ) declare @maxlength int declare @iterator int = 1 select @maxlength = c.CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS c where COLUMN_NAME = @ColName create table #allchars ( colchar CHAR (1) ) while @iterator < @maxlength begin set @ sql = 'insert into #allchars select distinct SUBSTRING(' + @ColName + ', ' + CAST (@iterator as varchar ) + ', 1) from ' + @TblName exec (@ sql ) set @iterator = @iterator + 1 end select distinct colchar from #allchars order by colchar drop table #allchars It’s not optimzed cause it just does what I want. Enjoy!

An Asp.Net Validation Framework (Part 3)

Image
An Asp.Net Validation Framework (Part 1) An Asp.Net Validation Framework (Part 2) Unfortunately, if you’re using LINQ to SQL or the Entity Framework, you can’t add the custom attributes we need for validation. You could generate your entity model and then simply use those generated objects but you would lose the ability to use the designers. I prefer to leverage the code we’ve written. public class ValidatableOrmBase : ValidatableBase { private List<CustomPropertyAttributeListItem> customPropertyAttributes; public List<CustomPropertyAttributeListItem> CustomPropertyAttributes { get { if (customPropertyAttributes == null ) { customPropertyAttributes = new List<CustomPropertyAttributeListItem>(); } return customPropertyAttributes; } } public override bool Validate( bool clearBrokenRules) { base .Validate(clearBrokenRules);

Asp.Net MVC and Sys is undefined

If you’ve run into the Sys is undefined message, check to make sure that you’ve included the following: < script src ="<%= Url.Content(" ~/ Scripts / MicrosoftAjax . debug . js ") %>" type ="text/javascript" ></ script > and < script src ="<%= Url.Content(" ~/ Scripts / MicrosoftMvcAjax . debug . js ") %>" type ="text/javascript" ></ script > You can include them in your masterpage or each individual page.

Error 0x80090305 with VSS Internet

I received the above error recently when trying to connect to my VSS server using the internet service. What appears to be causing the error is that I had configured my machine  for FIPS level remote desktop access using this page . As soon as I turned it off, everything worked again.

An Asp.Net Validation Framework (Part 2)

Image
In the first part , we saw how to create custom attributes and rules. Now we'll look at how to implement those attributes. The IValidatable interface defines how consumers can interact with the framework. It indicates that we'll have a collection of BrokenRules and offers a method to perform validation. ValidatableBase implements IValidatable and does most of the work. Your classes simply inherit from ValidatableBase and they are completely functional. You decorate all of the properties you want. /// <summary> /// Interface for class that wish to implement /// validation. /// </summary> public interface IValidatable { /// <summary> /// Gets the collection of business rules that have /// been broken. /// </summary> BrokenRulesCollection BrokenRules { get; } /// <summary> /// Validates the objects. /// </summary> /// <param name="clearBrokenRules">Indicates if the Broken

An Asp.Net Validation Framework

I've been working on different ways to implement a validation framework that would really cut down on the code. It  had to be reusable and testable. I also didn't want to swap writing one bunch of repetitive code for another. I'd looked at CSLA from Rockford Lhotka . I liked the way he implemented broken rules but CSLA had a lot of stuff for multiple undo's that was not relevant to my apps. I then used some of ScottGu's stuff for LINQ to SQL and begin using validation methods that threw exceptions. Reusable and custom exceptions made this very testable but I was still writing a bunch of repetitive code. Microsoft's Enterprise Library has a Validation Block that was interesting but really seemed to be overkill.  I did like the declarative nature though and then found this from Imar Spaanjaars . That was more what I was looking for and I could see where I could make some changes. First change was in the naming. NotNullOrEmptyAttribute became RequiredAtt