Friday, May 23, 2008

Configuration System Failed to Initialize

Problem: Your application contains User Scope Settings and you receive the exception,

“Configuration system failed to initialize” when attempting to retrieve these settings.

 

Solution: The settings file has been corrupted and is unreadable. Close or stop your application and delete the user.config file. The file is located at:

 

C:\Documents and Settings\[UserName]\Local Settings\Application Data\[AppCompany]\[AppName] \[AppVersion]\

 

If you are in Visual Studio you can easily find the exact file that is causing the problem by viewing the details and drilling down to the inner exception to find the file name.

#     Comments [1]  
kick it on DotNetKicks.com
 Monday, March 31, 2008

DotNetNuke Upgrade - My Rant

I have been using DotNetNuke for a year or more now mostly for personal fun projects but I have setup a site for a family business using DNN, nothing explosive and shinny but it has served its purpose. I manage 2 different DotNetNuke installations and I have to say upgrading DNN application (not the modules) is scary. I have yet to do it successfully on my first try. Here are my steps to failure:

1. Backup my SQL Server as well as my site files. This is the most important step because the fallowing steps are sure to fail.

2. Download the latest install or upgrade package for your DotNetNuke application. I have tried upgrading using both the upgrade and install packages with equal success err failure... successful failure?

3. Create an app_offline.htm with some generic text stating that you are doing maintenance on the site blah blah blah.

4. Rename your current web.config to web.config.old

5. Copy contents of the install/upgrade package to your DNN application folder.

6. Rename release.config to web.config.

7. Merge your old web.config with the new web.config. The areas to merge are: Connection Strings, MachineKey, and the codeSubDirectories. I also like to set AutoUpgrade key too false so nobody but me will trigger the installation.

8. Now I navigate to [Domain Name]/install/install.aspx

9. After I watch the list of Successful, or sometimes on Friday and the moon is full I will get a failure, I navigate to my home page of my DNN application to view the wonderful yellow screen. The error displayed is usually different every time or a different flavor of the same variety "Object Null Reference" being my favorite for its descriptiveness [insert sarcasm].

The good news and one of the reasons that I like DNN is it has a great community and I have fixed every problem with the help of people on the forums. Also once it is updated and running it is a solid application and very easy to extend and write custom modules for. I just wish for a one click update and BAM you are getting your "real" work completed. Anyway my SQL Server and root files are done restoring, time for try number two.

Note: Currently DotNetNuke was on version 4.8.2 when I wrote this.

Here are a few tutorials on upgrading your installation: 1 2

#     Comments [1]  
kick it on DotNetKicks.com
 Saturday, September 15, 2007

Sweet Sweet NUnit on VS2005 Action

This is great! I dont know why I didnt do this earlier, but you can Debug your code and run NUnit at the same time. You just need to set the Debug>Start Action to start external aplication NUnit.exe. Then set your start project to be the same project as your test code and tada you now have debuging and break point goodness wile running nunit.

#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, September 13, 2007

Unable to find the report in the manifest resources. please build the project, and try again.

I was reorganizing a project and I moved a crystal report after that I received this error at runtime "Unable to find the report in the manifest resources. please build the project, and try again." No amount of building could fix this problem. I eventually had to open up the .csproj file in note pad and edit the items entries in the xml/MSBUILD.

Here is what a Crystal Report should look like in your MSBUILD script.

    <Compile Include="CrystalReport1.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>CrystalReport1.rpt</DependentUpon>
      <SubType>Component</SubType>
    </Compile>

    <EmbeddedResource Include="CrystalReport1.rpt">
      <Generator>CrystalDecisions.VSDesigner.CodeGen.ReportCodeGenerator</Generator>
      <LastGenOutput>CrystalReport1.cs</LastGenOutput>
    </EmbeddedResource>

 After you correct the entry Rename the file Build then rename it again to the old name and build again. It might work if you just delete the code behind and then rebuild, but I didnt't try this.

 

#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, April 05, 2007

Switching to C# from VB.Net

    My current job requires me to jump on the band wagon and start coding in the C# syntax for .Net. For the last year I have been coding in VB.Net and doing all my blog examples in VB.Net and I really started to enjoy that language. The My namespace allowed for quick access to a number of common functions, key words such as AndAlso and OrElse eliminated the need for extra if statements, the background compiler was great finding errors instantly, the VB.Net code is formatted automatically for you (in C# I find my self having to hit ctr+K+D a lot and some times still have to format braces my self), and the lack of {}.[], <>, and () makes the language easy to read.
    My switch to C# was relatively easy I can't quite code as fast as I am able to in VB.Net and I still try to write Dim, forget semicolons, and other little syntax issues like that. I like that C# seems to hide less from you than VB.Net one example is just having the namespace automatically at the top of the page. C# is also less wordy than VB.Net and I can see more of the code that is important to me at one time. Maybe its just because I am new to the language but C# seems to have less ambiguous ways of doing things as well, witch seems to make code from programmer to programmer more consistent. Example of this is casting int from a string in VB you can use Cint(str), Ctype(str,int), Integer.Parse(str), and Val(str). There are a lot of other instances of this in VB.Net I think it has a lot to do with helping the VB 6.0 coders with there transition to .Net.
    All and all it is a refreshing change and I like going back to C++ derived syntax I believe to progress as a programmer you really need to experience in multiple languages.

#     Comments [0]  
kick it on DotNetKicks.com
 Wednesday, February 07, 2007

The Observer Pattern

The observer pattern is very useful and very easy to implement. It only requires two interfaces. One interface is the subject interface the other is the Observer.

    The subject contains three methods: AddObserver, RemoveObserver, and Notify. This interface is implemented by any class that needs to notify other objects that its state has changed.

Public Interface ISubject
    Sub AddObserver(ByRef ob As IObserver)
    Sub RemoveObserver(ByRef ob As IObserver)
    Sub Notify()
End Interface

The other interface is the observer it only contains one method Update, this interface is implemented by any class that needs to be notified by the subject object.

Public Interface IObserver
    Sub Update(ByVal subj As Object)
End Interface

In some examples of this pattern I have seen the subject is setup as an abstract class that you must inherit from, but I believe it limits the usefulness of the pattern. From what I read in the Head First Design Patterns book it says it is best to program to an interface instead of using inheritance. To illustrate this pattern I have created a simple program that monitors My Documents  folder on your computer and notifies a form when ever this folder's contents have changed. This is only an example, the way I implemented the subject object is a little weak but it will serve well enough.

I used the FileSystemWatcher as my base class and implemented the ISubject interface to serve as the subject. The class that implements the subject interface must contain a collection of observers the observers are added and removed using the AddObserver and RemoveObserver methods. The observers are notified by the Notify method witch iterates through the observer collection calling the Update method in the IObserver interface.

Imports System.IO

Public Class MyFileWatcher
    Inherits FileSystemWatcher
    Implements ISubject

Dim _observers As New ArrayList

Public Sub AddObserver(ByRef ob As IObserver) _
  Implements ISubject.AddObserver
    _observers.Add(ob)
End Sub

Public Sub Notify() _
  Implements ISubject.Notify
    Dim ob As IObserver
    For Each ob In _observers
        ob.Update(Me)
    Next
End Sub

Public Sub RemoveObserver(ByRef ob As IObserver) _
  Implements ISubject.RemoveObserver
    _observers.Remove(ob)
End Sub


Private Sub File_Changed _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Changed
    Me.Notify()
End Sub
Private Sub File_Created _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Created
    Me.Notify()
End Sub
Private Sub File_Deleted _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Deleted
    Me.Notify()
End Sub
Private Sub file_Renamed _
    (ByVal sender As Object, ByVal e As System.IO.RenamedEventArgs)Handles Me.Renamed
    Me.Notify()
End Sub
End Class

The observer is implemented as a form that contains List box this list box is Notified by the Subject and the Update method is ran witch updates the list with a valid list of files.

Imports fileWatcher
Imports System.IO
Public Class Form1
Implements IObserver
Private _path As String
Private _allfiles As Collections.ObjectModel.ReadOnlyCollection(Of String)
Public Property Path() As String
Get
Return _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
_allfiles = My.Computer.FileSystem.GetFiles(_path)
For Each singleFile As String In _allfiles
Me.ListBox1.Items.Add(singleFile)
Next
End Sub
Public Sub Update1(ByVal subj As Object) Implements fileWatcher.IObserver.Update
Me.ListBox1.Items.Clear()
_allfiles = My.Computer.FileSystem.GetFiles(_path)
For Each singleFile As String In _allfiles
Me.ListBox1.Items.Add(singleFile)
Next
End Sub
End Class

Lastly I created an MDI form that contains an instance of the FileWatcher class and creates a new Instance of the subject form every time a tool strip button is clicked. When ever a file in my documents is update all the child forms of the mdi are updated.

Imports System.Windows.Forms
Imports fileWatcher
Public Class MDIParent1
Private Sub ShowNewForm(ByVal sender As Object, ByVal e As EventArgs) Handles NewToolStripButton.Click
Dim FormObserver As New Form1
FormObserver.MdiParent = Me
FormObserver.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
_fileWatcherSubject.AddObserver(FormObserver)
FormObserver.Show()
End Sub
Private Sub MDIParent1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
_fileWatcherSubject.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
End Sub
End Class

For complete Observer pattern code download at the following link.

fileWatcher.zip (116.6 KB)
#     Comments [3]  
kick it on DotNetKicks.com
 Saturday, January 27, 2007

I' m Learning Design Patterns

I received a great book from my girl friend this Christmas called Head First Design Patterns. I have been reading this book and it is really getting me excited (about coding patterns in case you needed clarification). To better understand these patterns I am going to try and code examples of each one and post my experience as well as the code on my blog. I will list the patterns so I can keep track of them as well as giving my one or two readers a heads up on what to expect.

All of these patterns and definitions are described in Head First Design Patterns by Eric Freeman & Elisabeth Freeman with Kathy Sierra & Bert Bates from O'Reilly

Design patterns

  • The Strategy Pattern (p24) - Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  • The Observer Pattern (p51) - Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • The Decorator Pattern (p91) - Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • The factory Method Pattern (p134) - Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • The Abstract Factory Pattern(p156) - Provides an interface for creating families of related of dependent objects without specifying their concrete classes.
  • The Singleton Pattern (p177) - Ensures a class has only one instance, and provides a global point of access to it.
  • The Command Pattern (p206) - Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
  • The Adapter Pattern (p243) - Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • The Template Method Pattern(p289) - Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Methods lets subclasses redefined certain steps of an algorithm without changing the algorithm's structure.
  • The Interator Pattern (p336) - Provides a way to access the elements of an aggregate object sequentially without exposing the underlying representation.
  • The Composite Pattern(p356) - Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • The State Pattern(p410) - Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • The proxy pattern(p460) -  Provides a surrogate or placeholder for another object to control access to it.

#     Comments [0]  
kick it on DotNetKicks.com
 Wednesday, January 17, 2007

Throw vs Throw ex - The Why

I was talking to a friend of mine and he found my example of throw vs. throw ex interesting but he asked me a question that I didn’t expect, he asked me, "why?" I simply replied, "I don’t know, just don’t do it." But his insightful question made me curious. The answer to the question is in the real .Net language, the IL. When you compile your C# or VB.Net code just plain Throw becomes ReThrow but if you write Throw ex it becomes throw. In the IL snipit below Look at line 13 for JustThrowIT and line 14 in ThrowEX.


.method private instance void JustThrowIT() cil managed
{
.maxstack 2
.locals init (
[mscorlib]System.Exception exception1)
L_0000: nop
L_0001: nop
L_0002: ldarg.0
L_0003: callvirt instance void throwDemo.Form1::ThrowsExceptions()
L_0008: nop
L_0009: leave.s L_001c
L_000b: dup
L_000c: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError([mscorlib]System.Exception)
L_0011: stloc.0
L_0012: nop
L_0013: rethrow
L_0015: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()
L_001a: leave.s L_001c
L_001c: nop
L_001d: nop
L_001e: ret
.try L_0002 to L_000b catch [mscorlib]System.Exception handler L_000b to L_001c
}

.method private instance void ThrowEX() cil managed
{
.maxstack 2
.locals init (
[mscorlib]System.Exception exception1)
L_0000: nop
L_0001: nop
L_0002: ldarg.0
L_0003: callvirt instance void throwDemo.Form1::ThrowsExceptions()
L_0008: nop
L_0009: leave.s L_001c
L_000b: dup
L_000c: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError([mscorlib]System.Exception)
L_0011: stloc.0
L_0012: nop
L_0013: ldloc.0
L_0014: throw
L_0015: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()
L_001a: leave.s L_001c
L_001c: nop
L_001d: nop
L_001e: ret
.try L_0002 to L_000b catch [mscorlib]System.Exception handler L_000b to L_001c
}



#     Comments [2]  
kick it on DotNetKicks.com
 Wednesday, December 27, 2006

Throw vs Throw ex

A common mistake a lot of new .Net developers do is using Throw ex instead of just Throw. The difference between Throw ex and Throw is very simple but can cause major headaches when it comes to maintenance. If you use Throw ex it overwrites the stack trace this makes it very hard to find the original line of the thrown exception as you can see in the example I have provided.
Public Class Form1
Private Sub ThrowsExceptions()
Throw New System.Exception("Exception Thrown") 'Line 3
End Sub
Private Sub JustThrowIT()
Try
ThrowsExceptions()
Catch ex As Exception
Throw 'Line 9
End Try
End Sub
Private Sub ThrowEX()
Try
ThrowsExceptions()
Catch ex As Exception
Throw ex 'Line 16
End Try
End Sub
Private Sub ThrowEX_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
ThrowEX() 'Line 21
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Private Sub JustThrowIt_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Try
JustThrowIT() 'Line 29
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class

When you click the Throw ex button you get only get references to two lines 16 and 21 the orginal line the exception is thrown is missing(line 3).



When you click the Throw button you get the full stack trace including the line of the orginal exception that was thrown.



Download Source.
throwDemo.zip (47.73 KB)
#     Comments [4]  
kick it on DotNetKicks.com
 Tuesday, December 19, 2006

Using an Enum as the DataSource for a ComboBox

While working on my spell check app Dyslexic Helper I had to use an Enum (System.Windows.Forms.keys) as a data source for a Combo box I found this to be very easy and very useful. Here is an example of how to do this.

Public Class frmExample
'Enum to fill the combo box with
Public Enum Names
Jim
Bob
Dave
Sam
Tim
Jon
Suse
Ann
Sassy
Silvia
End Enum

Private Sub FormExample_Load(ByVal sender As Object, _
ByVal
e As System.EventArgs) Handles Me.Load
'fills the combo box with the names from the Enum Names
Me.ComboBoxExample.DataSource = System.Enum.GetValues(GetType(Names))
'selects the last selected name in the combobox
'My.Settings.Name is defined in the project/properties/settings as a string
Me.ComboBoxExample.SelectedIndex = Me.ComboBoxExample.FindStringExact(My.Settings.Name)
End Sub

Private Sub frmExample_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'saves the selected name in settings as form is closeing
My.Settings.Name = Me.ComboBoxExample.Text
My.Settings.Save()
End Sub
End Class

You can download the source here.

CboExample.zip (50.48 KB)
#     Comments [0]  
kick it on DotNetKicks.com