Customizing Style of RadGrid Edit Items#

A developer wanted to customize his “edit” form with a telerik rad grid, and we found it less than simple to change the textboxes and other edit controls to make them more narrow, and/or other customizations.

 

I did some research and came across a few different technique for doing this that I am going to share with everyone.

 

Template Columns

The first option, which is the one he used because it is the easiest, is to convert your columns to “template columns.”  Converting columns changes:

 

<telerik:GridBoundColumn DataField="EmployeeEmail" DataType="System.Int32" HeaderText="EmployeeEmail"

SortExpression="EmployeeEmail" UniqueName="EmployeeEmail" />

 

To this:

 

<telerik:GridTemplateColumn DataField="EmployeeEmail"

    HeaderText="EmployeeEmail" SortExpression="EmployeeEmail"

    UniqueName="EmployeeEmail">

    <EditItemTemplate>

        <asp:TextBox ID="EmployeeEmailTextBox" runat="server"

            Text='<%# Bind("EmployeeEmail") %>'></asp:TextBox>

    </EditItemTemplate>

    <ItemTemplate>

        <asp:Label ID="EmployeeEmailLabel" runat="server"

            Text='<%# Eval("EmployeeEmail") %>'></asp:Label>

    </ItemTemplate>

</telerik:GridTemplateColumn>

 

 

As you can see, this gives you control over the actual textbox item that will be displayed when you are in edit mode.

 

But using template columns can also be a bit of a pain, because you losing some of the simplicity that you had before when you simply allowed the rad grid to deal with the details of the display/edit cell items.  This also complicates things when you try to do anything in the ItemDataBound or ItemCreated events on the rad grid.  You can’t just grab the column, you have to dig deeper, looking for the contained child controls to find your actual edit control.

 

ItemDataBound

 

    Protected Sub RadGrid1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound

        If TypeOf e.Item Is GridEditableItem And e.Item.IsInEditMode Then

            Dim editItem As GridEditableItem = e.Item

            If TypeOf editItem.Item("EmployeeId").Controls(0) Is TextBox Then

                CType(editItem.Item("EmployeeId").Controls(0), TextBox).Width = 30

            End If

        End If

    End Sub

 

 

In this example, I am setting the width of the EmployeeId textbox to only 30px.

 

 

CreateColumnEditor

 

    Protected Sub RadGrid1_CreateColumnEditor(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCreateColumnEditorEventArgs) Handles RadGrid1.CreateColumnEditor

        If TypeOf e.ColumnEditor Is GridTextBoxColumnEditor Then

            If e.Column.UniqueName = "FirstName" Then

                CType(e.ColumnEditor, GridTextBoxColumnEditor).TextBoxStyle.Width = 30

                CType(e.ColumnEditor, GridTextBoxColumnEditor).TextBoxControl.Style.Add("text-align", "right")

            End If

        End If

    End Sub

 

 

I believe this event is fired when the grid is creating the edit columns.  You hook into this event, and then modify the textboxstyle in order to change the look of the edit control.

 

 

Defined Column Editor

 

You can achieve the same results as in CreateColumnEditor without writing any code if you drop a GridTextBoxColumnEditor on your page (outside of the RadGrid) like so:

 

<telerik:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor1" runat="server">

    <TextBoxStyle Width="50px" />

</telerik:GridTextBoxColumnEditor>

 

And then in your column you specify the ID of the editor you want to use, like this:

 

<telerik:GridBoundColumn DataField="UserId" DataType="System.Int32" HeaderText="UserId" ColumnEditorID="GridTextBoxColumnEditor1"

    SortExpression="UserId" UniqueName="UserId">

</telerik:GridBoundColumn>

 

 

 

 

Categories: Programming | .Net | ASP.Net
Thursday, March 11, 2010 3:08:27 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

CSLA Validation AmbiguousMatchException#

Ran into this error today:

failed in property IsDeleted ---> System.Reflection.AmbiguousMatchException: Ambiguous match found. at System.RuntimeType.GetPropertyImpl

I knew that we happened to have a property on our class called IsDeleted that shadowed a property in the CSLA base class, but I didn't think it should be running into this problem.

After tracking down some reference info here http://msdn.microsoft.com/en-us/library/zy0d4103.aspx I found otu that the issue isn't that we are shadowing, it's that we are shadowing while at the same time changing the type. 

The documentation seems to indicate that both situations should fail, but in my tests, the only time I got the exception was when my shadowing property had a different type.  In this case, we were using a Nullable(of boolean) while the CSLA element was just a plain old Boolean.

I guess we are going to rename our property to make things easy on ourselves, but seeing as how this is codegenerated, it's a little more of a pain than you might think.  But, oh well.

Here is some code that produces the error.  If you change the 2nd property type to a string it works ok.

imports Microsoft.VisualBasic
imports System
Imports System.Collections.Generic

public module MyModule
    sub Main
        dim target as new baseclass
        
        dim p as system.Reflection.PropertyInfo  = target.GetType().GetProperty("Prop") 
        
        wl( p.GetValue(target, nothing))

        
        RL()
    end sub

    #region "Helper methods"

    sub WL(text as object)
        Console.WriteLine(text)
    end sub

    sub WL(text as object, paramarray args as object())
        Console.WriteLine(text.ToString(), args)
    end sub
        
    sub RL()
        Console.ReadLine()
    end sub
    
    sub Break() 
        System.Diagnostics.Debugger.Break()
    end sub

    #end region

end module

public class BaseBaseClass
    public readonly property Prop as string
    get
    return "BaseBaseClass"
    end get
    end property
end class

public class BaseClass 
inherits BaseBaseClass

    public readonly property Prop as integer
    get
    return 123
    end get
    end property

end class
Categories: Programming | .Net | .Net Framework
Monday, March 01, 2010 4:02:49 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Connecting dynamically to mygeneration MyMeta.dbRoot#

The amount of time that this cost me is astounding for such a stupid issue.  (And, I'm going to lay the blame fully on whoever wrote the dbRoot object in the MyGeneration project.  Total improper use of properties).

The situation was this: I was trying to dynamically wire up all the plumbing that the mygeneration windows app does for you manually from the ZeusCmd command line.

Doing this would allow me to switch from DB to DB within my code gen application.

Because ZeusCmd runs first (it references my app and passes in what is needed), if you had previously saved a connection in your MyGeneration app, then this connection is used when ZeusCmd runs.  I didn't want this to happen because as I move from location to location different DB servers are available or not available, so if the last DB server I connected to was at office A, I didn't want my code gen crashing onload when I am out of said office.

So I ran MyGeneration and changed my connection to be <None> and saved the settings.  Then in my code gen, I tried to manually create the dbRoot object (named meta here) that was previously created for me my ZeusCmd and my saved MyGeneration settings.

Code like this:

meta.Connect("SQL", "Provider=SQLNCLI;Server=cmayt61p;Database=DBName;Trusted_Connection=yes;")

Seemed to do the trick.

However, my codegen started blowing up on my later in the process.  After tracking down the error I find that the mygeneration result column object can't figure out the .net type that would be the same as a sql server "int".  Strange, never had these problems before.

A lot of debugging leads me to find that:

meta.DbTarget
meta.Language 

Are both returning "" when before they were returning "SqlClient" and "VB.NET" when I was not dynamically connecting.

So here is where things get bad... anytime I try setting these properties to their values:

meta.DbTarget = "SqlClient"
meta.Language = "VB.NET"

Nothing happens.  The values don't appear to stick.

Eventually I even start trying to set the LanguageMappingFileName and DbTargetMappingFileName properties as well:

meta.DbTarget = "SqlClient"
meta.Language = "VB.NET"
meta.LanguageMappingFileName = "C:\Program Files\MyGeneration13\Settings\Languages.xml"
meta.DbTargetMappingFileName = "C:\Program Files\MyGeneration13\Settings\DbTargets.xml"

I tried doing these property sets before connecting and after connecting.

I tried returning to having MyGeneration setup the meta object form me (and all these properties have their values) before dynamically connecting (and losing the DbTarget and Language property values).

I even tried creating a brand new dbRoot object, as well as trying to read some hidden values in the IZeusInput object.

But, in the end, it all came down to the this 1 little thing:

You have to set the mapping file properties before you can set the DbTarget and Language properties.

So this will work just fine:

meta.Connect("SQL", "Provider=SQLNCLI;Server=cmayt61p;Database=MSiUpgraded;Trusted_Connection=yes;")
meta.LanguageMappingFileName = "C:\Program Files\MyGeneration13\Settings\Languages.xml" meta.DbTargetMappingFileName = "C:\Program Files\MyGeneration13\Settings\DbTargets.xml" meta.DbTarget = "SqlClient" meta.Language = "VB.NET"

But this won't:

meta.Connect("SQL", "Provider=SQLNCLI;Server=cmayt61p;Database=MSiUpgraded;Trusted_Connection=yes;")
meta.DbTarget = "SqlClient" meta.Language = "VB.NET" meta.LanguageMappingFileName = "C:\Program Files\MyGeneration13\Settings\Languages.xml" meta.DbTargetMappingFileName = "C:\Program Files\MyGeneration13\Settings\DbTargets.xml"

It just so happened that everywhere that I was testing this stuff in my code, I always set the DbTarget and Language properties first, and they would never stick.

This is not a proper use of properties.  If a property set has conditional logic that will prevent it from setting, there is something wrong here.  At minimum something should happen, an exception being thrown maybe?  The proper thing to do in my mind would be to make DbTarget and Language readonly properties and have functions to set their value, which could return something indicating failure (or throw an exception).

Property gets and sets should do just that, get and set properties.  There shouldn't be logic in there deciding if and when to actually perform the set that you have coded.  That is the job of a function.

UPDATE: And I discovered as well that you have to connect first before you set any of these values, or none of them will stick.  So you have to 1) connect 2) set the file paths 3) set the language and dbtargets, in that order or nothing works.

Categories: Programming | .Net
Monday, January 18, 2010 12:42:39 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

CSLA 3.5 Child and Parent Patterns#
From this post:
http://forums.lhotka.net/forums/thread/25658.aspx


Child pattern:
[Serializable]
public class Child : BusinessBase<Child>
{
  internal static Child NewChild()
  {
    return DataPortal.CreateChild<Child>();
  }

  internal static Child GetChild()
  {
    return DataPortal.FetchChild<Child>();
  }

  private Child()
  { 
    MarkAsChild();
  }

  private void Child_Create()
  {
    // initialize new child here
  }

  private void Child_Fetch()
  {
    // load child data here
  }

  private void Child_Insert()
  {
    // insert child data here
  }

  private void Child_Update()
  {
    // update child data here
  }

  private void Child_DeleteSelf()
  {
    // delete child data here
  }
}

Editable root pattern:
[Serializable]
public class RootParent : BusinessBase<RootParent>
{
  // other class code here ...

  protected override void DataPortal_Insert()
  {
    using (SqlConnection cn = new SqlConnection(...))
    {
      // insert parent data here

      FieldManager.UpdateChildren();
    }
  }

  protected override void DataPortal_Update()
  {
    using (SqlConnection cn = new SqlConnection(...))
    {
      // update parent data here

      FieldManager.UpdateChildren();
    }
  }
}


Editable Root List:
[Serializable]
public class ChildList : BusinessListBase<ChildList, Child>
{
  // other class code here ...

  protected override void DataPortal_Update()
  {
    using (SqlConnection cn = new SqlConnection(...))
    {
      Child_Update();
    }
  }
}

Editable Child List:
[Serializable]
public class ChildList : BusinessListBase<ChildList, Child>
{
  internal ChildList()
  {
    MarkAsChild();
  }

  // other class code here ...
}
If you use the DataPortal methods for creating the child objects (i.e. FetchChild) then you don't have to bother with the MarkAsChild() stuff.

Categories: Programming | .Net | C#
Friday, November 27, 2009 6:12:18 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Turn an Enum into a list in VB.Net with optional CSLA#
From time to time you might have an enum that you want to databind to something as if it were a list, so I wrote some classes that turn an Enum into a list that you can databind. 

I created ways to do this in CSLA and also w/o CSLA.  I made the non-CSLA versions 1 work so that you can either use a sub class, or just use generics when defining the type of your list.  You can do the same with the CSLA versions if you want by changing some of the generics, but I didn't bother.

'*** csla
Dim cslaList As MyTestTypeList = MyTestTypeList.GetList

'*** non-csla with inherited subclass and without
Dim list As New MyTestTypeList2
Dim list2 As New EnumList2(Of MyTestType)


'*** enum we are using
Public Enum MyTestType
something = 1
here = 2
ok = 3
End Enum

'*** csla
<Serializable()> _
Public Class MyTestTypeList
Inherits EnumList(Of mytesttype, MyTestTypeList)

End Class
<Serializable()> _
Public Class EnumList(Of T As Structure, R As EnumList(Of T, R))
Inherits Csla.NameValueListBase(Of String, Integer)

Public Shared Function GetList() As R
Return Csla.DataPortal.Fetch(Of R)()
End Function

Protected Sub New()
' require use of factory method
End Sub

<Csla.RunLocal()> _
Public Overloads Sub DataPortal_Fetch() 'ByVal criteria As Object)
Me.IsReadOnly = False
For Each item As T In [Enum].GetValues(GetType(T))
Dim name As String = [Enum].GetName(GetType(T), item)
Add(New Csla.NameValueListBase(Of String, Integer).NameValuePair(name, [Enum].Parse(GetType(T), name)))
Next
Me.IsReadOnly = True
End Sub
End Class

'*** non-csla
Public Class MyTestTypeList2
Inherits EnumList2(Of MyTestType)

End Class

Public Class EnumList2(Of T As Structure)
Inherits List(Of EnumListItem)

Public Structure EnumListItem
Dim Name As String
Dim Value As Integer
Public Sub New(ByVal name As String, ByVal value As Integer)
Me.Name = name
Me.Value = value
End Sub
End Structure

Public Sub New()
For Each item As T In [Enum].GetValues(GetType(T))
Dim name As String = [Enum].GetName(GetType(T), item)
Add(New EnumListItem(name, [Enum].Parse(GetType(T), name)))
Next
End Sub

End Class


Categories: Programming | .Net | VB.Net
Friday, November 27, 2009 3:16:10 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

SSRS report fails with vertical text#

We ran into an interesting problem today.

A matrix report in SSRS (sqlserver reporting services) 2008 would work just fine when previewing it in VS, and would work fine when viewed directly on the reporting server.  But, if you view it through a asp.net reportviewer control, it would just show the header, a big blank space, and then the footer.

This only happens if you have Vertical text for the row headers.  Remove that and everything is OK.

I began editing the generated CSS/HTML and found that the cells had a number of styles applied, but specifically the one that seemed to break everything was:

WIDTH:100%;

Remove that and the page rendered as expected.

We tried changing a number of parameters to get it to remove the width style but no luck.

We have something that generates images with GDI to do it now, but it's not ideal.

Categories: Programming | .Net | ASP.Net | Reporting
Friday, September 25, 2009 1:49:54 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Getting error reports when a SQL Reporting Subscription Fails#

UPDATE 2:

Either this never worked in the first place as I wanted, or MS has changed how they are doing things in SSRS 2008.

I now don't see any of the errors in the tables I had been looking in, and in fact, the errors don't show up in any of their logs either.  This is crap.

If you are like me, you don't like the fact that the first time you realize that a data driven subscriptions in SQL Server Reporting Services has been failing is when someone comes up to you and says "Hey, I did XYZ and I never saw the server kick off an email." 

Really?  Let me check.... oh, looks like it has been broken for god knows how long.  What the heck?

Well, I wrote a script to notify you when there are errors on the report server.

First, you need to setup Database Mail.  Expand Management, and pick Database Mail.  For my script I used the name "Email Profile" for the "Email Profile" get it?

Then create a trigger on the ExecutionLogStorage table like this:

USE [ReportServer]
GO
/****** Object:  Trigger [dbo].[ExecutionLogStorage_Insert]    Script Date: 05/13/2009 10:20:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[ExecutionLogStorage_Insert]
ON [dbo].[ExecutionLogStorage]
AFTER INSERT
AS 
BEGIN
    DECLARE @sStatus AS NVARCHAR(32)
    SET @sStatus = (SELECT Status FROM inserted)
    
    IF(@sStatus <> 'rsSuccess')
    BEGIN
        DECLARE @sReportName AS NVARCHAR(425)
        DECLARE @sPath AS NVARCHAR(425)
        DECLARE @ReportId AS UNIQUEIDENTIFIER 
        DECLARE @sUserName AS NVARCHAR(260)
        DECLARE @sParameters AS NVARCHAR(4000)
        DECLARE @dTimeEnd AS DATETIME 
        DECLARE @iTimeProcessing as int
        
        
        SELECT 
          @sReportName = Name,
          @sPath =PATH,
          @ReportId = ReportId,
          @sUserName = username,
          @sParameters = (select CAST(ISNULL(ELS.Parameters,'') AS NVARCHAR(4000)) from ExecutionLogStorage ELS Where LogEntryId = Inserted.LogEntryId),
          @dTimeEnd = TimeEnd,
          @iTimeProcessing = ISNULL(TimeProcessing,0)
        FROM inserted INNER JOIN [Catalog] 
        ON inserted.ReportId = CATALOG.[ItemID] 
        
        DECLARE @sBody VARCHAR(8000)
        SET @sBody = 'Error with SQL Report ' 
                    + CAST(@sReportName AS VARCHAR(100))
                    + ' at path ' 
                    + CAST (@sPath AS VARCHAR(250))
                    + ' with ReportId ' 
                    + CAST(@ReportId AS VARCHAR(100)) 
                    + ' and username ' 
                    + CAST(@sUserName AS VARCHAR(100))
                    + ' Parameters ' 
                    + CAST(@sParameters  AS VARCHAR(5000))
                    + ' End time ' 
                    + CAST(@dTimeEnd AS VARCHAR(50))
                    + ' Status ' 
                    + CAST(@sStatus AS VARCHAR(50))
                    + ' Time Processing '
                    + CAST(@iTimeProcessing AS VARCHAR(50));
        
        DECLARE @sSubject VARCHAR(500)
        SET @sSubject = 'Error With Report ' + @sReportName
        
        EXEC msdb.dbo.sp_send_dbmail 
         @profile_name = 'Email Profile', 
         @recipients = 'email@address.com', 
         @body =  @sBody  ,
         @subject = @sSubject;

    END
    
END

Presto!

 

UPDATE: Added logic to get the status and parameters.

 

Categories: Programming | .Net | Database | SQL Server | T-Sql | Reporting
Wednesday, May 06, 2009 4:55:06 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

ASP.NET Apps Recycling Because of FCN Issues#

I have written before about some of the problems that a frequently recycling asp.net application can cause, espically if you are using session for anything.

ASP.NET Process Recycling Too Often

But I ran into a situation where the recycle was caused by the application itself for a client of mine.  I had bought and customized a asp.net application that allows my client to give THEIR clients access to a section of their site where they can upload/download/manage files very nicely.  But after moving to a new hosting environment, users kept losing their login sessions very quickly.

After some research, I found out that session was being used to track if the user was logged in, and session was being lost very quickly because the application was recycling.

I used the following code to help diagnose the cause for the application restarting:

(this goes in Application_End)

Dim runtime As HttpRuntime = GetType(System.Web.HttpRuntime).InvokeMember("_theRuntime", _
    BindingFlags.NonPublic Or _
     BindingFlags.Static Or _
    BindingFlags.GetField, _
    Nothing, Nothing, Nothing)

If runtime Is Nothing Then
    logger.Error("The application is closing at " & Now.ToShortDateString & " " & Now.ToLongTimeString)
    Return
End If

Dim shutDownMessage As String = runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
'If shutDownMessage = "HostingEnvironment caused shutdown" Then
'    '*** this is normal, you can include this commented out section or not
'    Return
'End If
Dim shutDownStack As String = runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
'*** email this error
logger.Error(String.Format("The application is closing at " & Now.ToShortDateString & " " & Now.ToLongTimeString & " " & vbCrLf & vbCrLf & "_shutDownMessage={0}" & vbCrLf & vbCrLf & "_shutDownStack={1}", shutDownMessage, shutDownStack))


Dim log As New EventLog
log.Source = ".NET Runtime"
log.WriteEntry(String.Format(vbCrLf & vbCrLf & "_shutDownMessage={0}" & vbCrLf & vbCrLf & "_shutDownStack={1}", shutDownMessage, shutDownStack), EventLogEntryType.Error)

The cause was:

Directory rename change notification for 'APP PATH HERE.
Clients dir change or directory rename
HostingEnvironment caused shutdown

Because this app was now hosted with a 3rd party, I didn't have control over the environment to go see if there was an AV scanner or backup manager running that was touching the files.

However, I because I was able to reproduce the error in my dev environment, I was confident I could rule out those causes.

I eventually found that the problem was 2 fold:

1) The application allows the user to upload files/create folders that reside in subfolders of the application.  The app could think these changes require a recycle.

2) The application creates a temp folder for the user for each session under the root as well.  Changing folder structure can cause a recycle.

So what can be done?

Well, I adapted some code from a few places to turn off the FCN (File change notifications) for sub directories of the website.  This isn't easy to do if you don't have something to go off of, becaues you basically have to hijack your way into private methods on classes in the .net framework, using reflection to call methods that you shouldn't be accessing, in order to turn off specific behavior.

Here are the methods I created to help me do this.  I also have some log4net code in here, so you'll have to pull that out if you want to use this.

Private Sub TurnOffDirectoryMonitoring()
    Try
        Dim p As System.Reflection.PropertyInfo = GetType(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
        Dim o As Object = p.GetValue(Nothing, Nothing)

        Dim f As FieldInfo = o.GetType.GetField("_dirMonSubdirs", BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.IgnoreCase)

        Dim monitor As Object = f.GetValue(o)

        Dim asdf As System.Reflection.MethodInfo() = monitor.GetType.GetMethods()

        Dim propIsMonitoring As System.Reflection.MethodInfo = monitor.GetType.GetMethod("IsMonitoring", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
        Dim bIsMonitoring As Boolean = propIsMonitoring.Invoke(monitor, Nothing)
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Info("Directory monitoring IsMonitoring was " & bIsMonitoring)


        Dim m As System.Reflection.MethodInfo = monitor.GetType.GetMethod("StopMonitoring", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)

        Dim objArray() As Object = {}
        m.Invoke(monitor, objArray)

        logger.Info("Directory monitoring IsMonitoring after change is " & bIsMonitoring)

    Catch ex As Exception
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Error(ex) 
    End Try
End Sub

Private Sub CheckDirectoryMonitoring()
    Try
        Dim p As System.Reflection.PropertyInfo = GetType(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
        Dim o As Object = p.GetValue(Nothing, Nothing)

        Dim f As FieldInfo = o.GetType.GetField("_dirMonSubdirs", BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.IgnoreCase)

        Dim monitor As Object = f.GetValue(o)

        Dim asdf As System.Reflection.MethodInfo() = monitor.GetType.GetMethods()

        Dim propIsMonitoring As System.Reflection.MethodInfo = monitor.GetType.GetMethod("IsMonitoring", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
        Dim bIsMonitoring As Boolean = propIsMonitoring.Invoke(monitor, Nothing)
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Info("In CheckDirectoryMonitoring, Directory monitoring IsMonitoring is " & bIsMonitoring)
    Catch ex As Exception
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Error(ex)
    End Try
End Sub

Private Sub CheckFCNMode()
    Try
        Dim p As System.Reflection.PropertyInfo = GetType(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
        Dim o As Object = p.GetValue(Nothing, Nothing)

        Dim f As FieldInfo = o.GetType.GetField("_FCNMode", BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.IgnoreCase)

        Dim iFCNMode As Integer = f.GetValue(o) 
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Info("In CheckFCNMode, FCNMode is " & iFCNMode)
    Catch ex As Exception
        Dim logger As log4net.ILog = log4net.LogManager.GetLogger("File")
        logger.Error(ex)
    End Try
End Sub

These methods are not refactored or "best practice" at all, there is a lot of copy/paste code in here, but you'll get the idea of what I'm doing.

You can call these methods from the beginning on Application_Start. 

1 thing to note.  I found that my code that checks to make sure that logging was turned off, doesn't seem to report the right value the first time I check it.  But by the time the first session starts, it has indeed stopped monitoring.

Just try calling these methods from a few places after application_start and you can see what happens.

 

Categories: Programming | .Net | ASP.Net
Thursday, April 02, 2009 12:27:04 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Golden Rule of Winform Databinding#

Rocky Lhotka had this over on his site:

The Golden Rule of Windows Forms data binding

Never directly interact with a business object while it is data bound - only interact with the bindingsource

http://forums.lhotka.net/forums/thread/22990.aspx

I have to say, I am guilty of doing this, and I didn't even know it was considered a bad practice, but I do recall running into problems with the behavior in getting the UI to refresh as I would want it to.

I also found a nice article talking about how to speed up binding to the datagrid:
 
Categories: Programming | .Net | WinForms
Monday, March 23, 2009 3:08:22 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Problems Upgrading VS Solutions to 2008 With CruiseControl.Net#

Problem:

We have a server that gets all files from TFS and uses Nant w/ Visual studio to compile our projects.  Basically nant issues a command line statement to get VS to build a given solution.

Everything was working great, until I upgraded our clients to 2008.

I went through and upgraded all our solutions.

I installed vs 2008 on the server.  But when I try to build from the command line, it tells me that the solution file "is from a previous version of this application and must be converted in order to build in this version of the application."

I tried directly copying my solution file (skipping the source control step) directly to the server but I get the same message.

If I try to build it from the command line with VS 2005 it tells me that the solution is too new!! 

So 2005 says the solution is too new, 2008 says it is too old!

The solution on the server has the "version 9" icon, just like on my laptop.

The solution file starts with:
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008

Resolution:

Even thought I compared the solution files and found them to be exactly the same using a diff compare tool, I allowed the server to run the "upgrade" process on the solutions.  I didn't save any of the changes it made, but from then on it recognized those files as having been already upgraded.

I even replaced the "server upgraded" solution files with the old solution files that it didn't like and it continued to work just fine.

There must be some other files stored somewhere that made it think that it hadn't been upgraded yet.

This isn't a great solution, but it works at least.

 

Categories: Programming | .Net | VS.Net | TFS | VSS
Monday, March 16, 2009 9:43:30 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Using Asyncronous Tasks In ASP.NET#

ASP.NET has a limited number of threads that it uses to service incoming requests.  Thes threads from the its thread pool, and when its collection of threads are busy, requests have to queue up waiting for an open thread.

But, what happens when you have threads that are blocking waiting for another process to complete?  This could we a database call, or a webservice call, or an IO operation etc.

Well, what happens is that the thread, while doing no real work, is unavailable to service requests.

So, if your database is crunching on some long queries, other simple web requests may be sitting in the queue unable to be handled, even though the webserver CPU is idle.

One solution to this is to use Async pages/methods in ASP.NET 2 or greater.

Async operations allow the thread to be returned back to the thread pool instead of blocking, while some process is executed.

 

There is more than 1 way to do async operations like this from asp.net pages. 

One is to use RegisterAsyncTask and the other to user AddOnPreRenderCompleteAsync as well as declare the page as Async="true".

I won't go into all the details, but AddOnPreRenderCompleteAsync is probably simpler, but you can't define a timeout, you can't call it multiple times in parallel, and in the EndAsyncOperation event handler you can't access things like the httpcontext object.

Here are 2 examples of pages that are asynchronously serving up a PDF document (which is itself served from a page DownloadPDF.aspx, which has a 5 second thread sleep in it to simulate the processing of the report on another server.

Using AddOnPreRenderCompleteAsync:

Imports System.Net
Imports System.IO

Partial Class AsyncServer
    Inherits System.Web.UI.Page

    Dim _request As WebRequest

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddOnPreRenderCompleteAsync(New BeginEventHandler(AddressOf BeginAsyncOperation), _
                                    New EndEventHandler(AddressOf EndAsyncOperation))
    End Sub

    Function BeginAsyncOperation(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object) As IAsyncResult
        _request = WebRequest.Create(HttpContext.Current.Request.Url.Scheme & _
                                     "://" & HttpContext.Current.Request.Url.Authority & _
                                     Page.ResolveUrl("DownloadPDF.aspx"))
        Return _request.BeginGetResponse(cb, state)
    End Function

    Sub EndAsyncOperation(ByVal ar As IAsyncResult)
        Dim reportResponse As WebResponse = _request.EndGetResponse(ar)
        Dim reader As New BinaryReader(reportResponse.GetResponseStream())

        Dim buffer(reportResponse.ContentLength) As Byte
        buffer = reader.ReadBytes(buffer.Length)
        
        Response.Clear()
        Response.ClearHeaders()
        Response.ClearContent()
        Response.ContentType = "Application/pdf"
        Response.BinaryWrite(buffer)
    End Sub

End Class

 

But I prefer to use RegisterAsyncTask.  Now, keep in mind that many operations will already support async versions (webrequests, webservice calls, databases calls, file IO etc), but if there isn't already built in support for an async call, you can make your own method work in this framework with an async delegate.  Check out the commented code below for how you could do this, but because webrequests already support making the call in an asynchronous fashion, I don't need to.

Imports System.Net
Imports System.IO

Partial Class RegisterAsyncTaskServer
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Page.AsyncTimeout = New System.TimeSpan(0, 0, 8)
        Dim task As New PageAsyncTask(New BeginEventHandler(AddressOf BeginGetAsyncData), _
                                      New EndEventHandler(AddressOf EndGetAsyncData), _
                                      New EndEventHandler(AddressOf TimeoutGetAsyncData), "task1", True)

        RegisterAsyncTask(task)
    End Sub

    '*************** This is one way to do this if not using an async download method by creating an async delegate
    'Dim taskDelegate As AsyncTaskDelegate
    '' Create delegate.
    'Delegate Sub AsyncTaskDelegate()
    'Private Function BeginGetAsyncData(ByVal src As Object, ByVal args As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object) As IAsyncResult
    '    Dim extraData As New Object
    '    taskDelegate = New AsyncTaskDelegate(AddressOf DownloadReport)
    '    Dim result As IAsyncResult = taskDelegate.BeginInvoke(cb, extraData)
    '    Return result
    'End Function
    'Private Sub DownloadReport()
    'End Sub

    Private reportRequest As WebRequest

    Private Function BeginGetAsyncData(ByVal src As Object, ByVal args As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object) As IAsyncResult
        reportRequest = WebRequest.Create(HttpContext.Current.Request.Url.Scheme & "://" & _
                                          HttpContext.Current.Request.Url.Authority & _
                                          Page.ResolveUrl("DownloadPDF.aspx"))
        Return reportRequest.BeginGetResponse(cb, state)
    End Function


    Private Sub TimeoutGetAsyncData(ByVal ar As IAsyncResult)
        Response.Write("TIMEOUT")
    End Sub

    Private Sub EndGetAsyncData(ByVal ar As IAsyncResult)
        Dim reportResponse As WebResponse = reportRequest.EndGetResponse(ar)
        Dim reader As New BinaryReader(reportResponse.GetResponseStream())

        Dim buffer(reportResponse.ContentLength - 1) As Byte
        buffer = reader.ReadBytes(buffer.Length)

        Response.Clear()
        Response.ClearHeaders()
        Response.ClearContent()
        Response.ContentType = "Application/pdf"
        Response.BinaryWrite(buffer)
        Response.Flush()
    End Sub

End Class

Nice!

Categories: Programming | .Net | .Net Framework | ASP.Net
Friday, March 13, 2009 10:46:43 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Regenerating the designer.vb and designer.cs files#

Chances are you have had this happen to you.

You start getting compile errors on your asp.net controls in your code behind pages.  But the controls exist on the page??  Whats the deal?

Well, in VS2003 the designer would create the class level controls in your code behind.  It would created a special region where it would put all it's autogenerated code.

2005 brought the new "Web Site Project" which used a "CodeFile" instead of "CodeBehind" attribute on the page tag.  In addition, the codefile/codebehind became a Partial Class.  VS would then put all the generated code in a seperate file so it didn't cramp up your code behind.

In Web Application projects, the autogen code is stored in .designer.vb files:

But everynow and then, things get out of sync, or the designer files get totally lost.

Here is how you can regenerate them:

First, make sure your class names, and page attributes are right.  The Page tag should have a Codebeind attribute pointing to the aspx.vb file and an Inherits attribute that contains the fully qualified class name in the codebehind.  (This instructions are for Web App Projects, not Web Site Projects, which use Codefile instead of Codebehind).

Second, create a designer file if one doesn't exist.  Click the "Show all files" icon in the Solution Explorer to see if you have designer files.  If not, add a class file with the right name page_name.aspx.designer.vb.  VS will automatically put it "under" the aspx page.

Make sure all namespaces are right.  Check your code beind, your designer file, and your page codebehind attribute.

Open your page in a designer and rename one of your controls.  Save everything and close the code and designer windows.  Open the designer back up and rename the control back.  Now look at your designer file, it should have a punch of controls in it, and now VS shouldn't complain about compile errors in your code behind.

 

Categories: Programming | .Net | ASP.Net | VS.Net
Monday, February 23, 2009 4:07:35 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Showing Deleted Folders In TFS#

Sometimes you might try to rename a folder in TFS Team Explorer and it tells you that you can't rename the folder b/c an existing item exists (but it doesn't).

The reason is that if there is a delete folder with the same name, it won't allow you to name a current folder with the same name.

To see your deleted folders (so you can undelete, rename, and delete again) you can use the following option under Tools->Options.



Categories: Programming | .Net | TFS
Tuesday, February 03, 2009 4:50:31 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Extending Microsoft Data Access Blocks (early version)#

Microsoft has released several versions of their Data Access Blocks, but they started mixing all their blocks together at some point, so if you wanted to use the DAB, you had to also use the Configuration blocks, and you had to use the Encryption blocks, and those needed the logging blocks etc.

So in many of my projects I have kept with one of the earlier versions.

But, there was a problem.  Basically in order to pass parameters, the easiest way to do it was in an ordinal position way, such as:

Public Shared Sub Whatever(SomeParamsHere)
    Dim storedParams() As SqlParameter
    storedParams = SqlHelperParameterCache.GetSpParameterSet(ConnectionString, "Whatever")

    storedParams(0).Value = 1
    storedParams(1).Value = 2
    storedParams(2).Value = 3
    storedParams(3).Value = "abc"

   SqlHelper.ExecuteNonQuery(ConnectionString, _
        CommandType.StoredProcedure, _
        "ItProjectInfo_General_Update", _
        storedParams)

End Sub

Obviously, this code is hard to read because we don't know which parameters are getting which values w/o opening up the stored procedure and looking ourselves.

So I wrote some extra code to allow of working with SqlParameters in the form of Dictionary(Of String, SqlParameter).  Calling the same function would look like this:

Public Shared Sub Whatever(ByVal SomeParamsHere)
    Dim storedParams() As New Dictionary(Of String, SqlParameter)
    storedParams = SqlHelperParameterCache.GetSpParameterCollection(ConnectionString, "Whatever")

    storedParams.Item("@id").Value = 1
    storedParams.Item("@num").Value = 2
    storedParams.Item("@cat").Value = 3
    storedParams.Item("@name").Value = "abc"

    SqlHelper.ExecuteNonQuery(ConnectionString, _
         CommandType.StoredProcedure, _
         "ItProjectInfo_General_Update", _
         storedParams)

End Sub

This works for output parameters as well.

In order to make this work you need to edit the SqlHelper.vb code.

Inside the SqlHelperParameterCache class you need to add:

Public Overloads Shared Function GetSpParameterCollection(ByVal connectionString As String, ByVal spName As String) As System.Collections.Generic.Dictionary(Of String, SqlParameter)
    Dim parameters() As SqlParameter = GetSpParameterSet(connectionString, spName, False)
    Dim paramsCol As System.Collections.Generic.Dictionary(Of String, SqlParameter)
    paramsCol = SqlHelper.ParamArrayToDict(parameters)
    Return paramsCol
End Function

And inside SqlHelper class you need to add the following methods:

#Region " Dictionary Support Helpers "
Friend Shared Function ParamArrayToDict(ByVal params() As SqlParameter) As Dictionary(Of String, SqlParameter)
    Dim dict As New System.Collections.Generic.Dictionary(Of String, SqlParameter)(StringComparer.CurrentCultureIgnoreCase)
    For i As Integer = 0 To params.Length - 1
        dict.Add(params(i).ParameterName, params(i))
    Next
    Return dict
End Function

Friend Shared Function ParamDictToArray(ByVal dict As Dictionary(Of String, SqlParameter)) As SqlParameter()
    Dim params(dict.Count - 1) As SqlParameter
    Dim i As Integer
    For Each p As SqlParameter In dict.Values
        params(i) = p
        i += 1
    Next
    Return params
End Function
#End Region

Public Overloads Shared Function ExecuteDataset(ByVal connectionString As String, _
                                           ByVal commandType As CommandType, _
                                           ByVal commandText As String, _
                                           ByVal commandParameters As Dictionary(Of String, SqlParameter)) As DataSet ' Execute Dataset with generic dictionary support

    Dim parametersArray() As SqlParameter
    parametersArray = ParamDictToArray(commandParameters)
    Return ExecuteDataset(connectionString, commandType, commandText, parametersArray)
End Function


Public Overloads Shared Function ExecuteNonQuery(ByVal connectionString As String, _
                                              ByVal commandType As CommandType, _
                                              ByVal commandText As String, _
                                              ByVal commandParameters As Dictionary(Of String, SqlParameter)) As Integer
    Dim parametersArray() As SqlParameter
    parametersArray = ParamDictToArray(commandParameters)
    Return ExecuteNonQuery(connectionString, commandType, commandText, parametersArray)
End Function  ' ExecuteNonQuery with generic dictionary support


Public Overloads Shared Function ExecuteScalar(ByVal connectionString As String, _
                                              ByVal commandType As CommandType, _
                                              ByVal commandText As String, _
                                              ByVal commandParameters As Dictionary(Of String, SqlParameter)) As Object

    Dim parametersArray() As SqlParameter
    parametersArray = ParamDictToArray(commandParameters)
    Return ExecuteScalar(connectionString, commandType, commandText, parametersArray)

End Function ' ExecuteScalar with generic dictionary support

 

 

Categories: Programming | .Net | .Net Framework
Thursday, December 04, 2008 1:36:06 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Using nant to build projects from the command line#

NAnt is a tool that can help you build your .net applications. 

You can get really detailed with it, but what if you just want to set it up to quickly build projects/solutions or run automated builds.  This is especially useful if you are rebuilding 1 project that you are in the process of testing so you don't have to wait for VS to figure out if any of the referenced projects need to be rebuilt.

Well, with a few quick steps you can have this.

After downloading NAnt you need to create a little batch file somewhere in your PATH (for example, c:\windows).  Name the file nant.bat and put this in it:

@echo off
"C:\apps\nant\nant-0.86-beta1\bin\NAnt.exe" %*

You will obviously want to replace my path with your own path to your nant exe that you downloaded.

Then add an entry to your PATH system variable to the directory that contains devenv.com.  For me this path is:
C:\Program Files\Microsoft Visual Studio 8\Common7\ide\

Then you just need to add a .build file to your project.  I name it the same as my project name but you can do whatever you want.

This build file should contain the following XML:

<?xml version="1.0"?>
<project name="ProjName" default="build" basedir=".">
  <target name="build">
    <exec failonerror="true" program="devenv.com" commandline="ProjName.vbproj /build Debug" />
  </target>
</project>

Rename ProjName as needed in this file as well.

Then all you need to do is navigate to the folder that contains the .build file from a command line and run:

nant

It will scan for the build file, and use devenv.com to build it.

You can also use this to build solutions, just change the .vbproj file to a .sln file.

Categories: Programming | .Net | Testing | Tools
Monday, December 01, 2008 4:35:19 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Webservices: The request failed with HTTP status 400: Bad Request#

We have a webservice that is called from an application under heavy use.

From time to time we are getting errors coming back from the webservice:

The request failed with HTTP status 400: Bad Request

The stack trace is not very helpful:

at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)

So basically the webservice is just throwing back a 400 error to the webservice request.

I haven't seen anyone online who has this type of issue.  I have seen several where they ALWAYS get this error, but none where it works most of the time and fails sometimes.

I am considering that it could be something in the network, like a proxy server or AV sniffer, but not sure.

 

Categories: Programming | .Net | .Net Framework | ASP.Net | WebServices
Tuesday, November 18, 2008 5:21:48 PM (Central Standard Time, UTC-06:00) #    Comments [1]  | 

 

Compressing Web Service Calls#

Most webservers will compress data if the clients support it.

Unfortunately for .net developers the auto generated proxy classes that access webservices don't include this functionality.

I'll show you how to achieve this while avoiding changing any code in the auto generated proxy classes.

(These classes utilize ICSharpCode.SharpZipLib.dll so you'll have to download this)

This following class will deal with decompressing a response.

Imports System.Net
Imports ICSharpCode.SharpZipLib

Public Class UncompressedGzipResponse
    Inherits System.Net.WebResponse

    Private cCompressedGzipResponse As HttpWebResponse

    Public Sub New(ByVal compressedGzipResponse As HttpWebResponse)
        MyBase.New()
        cCompressedGzipResponse = compressedGzipResponse
    End Sub


    Public Overrides Function GetResponseStream() As System.IO.Stream

        Dim compressedStream As System.IO.Stream = New GZip.GZipInputStream(cCompressedGzipResponse.GetResponseStream)
        Dim decompressedStream As New System.IO.MemoryStream
        Dim size As Integer = 2048
        Dim writeData(2048) As Byte
        While True
            size = compressedStream.Read(writeData, 0, size)
            If size > 0 Then
                decompressedStream.Write(writeData, 0, size)
                Dim s As String = System.Text.Encoding.ASCII.GetString(writeData)
                s = s & ""
            Else
                Exit While
            End If
        End While
        decompressedStream.Seek(0, IO.SeekOrigin.Begin)

        Return CType(decompressedStream, IO.Stream)

    End Function

    Public Overrides Property ContentType() As String
        Get
            Return cCompressedGzipResponse.ContentType
        End Get
        Set(ByVal value As String)
            cCompressedGzipResponse.ContentType = value
        End Set
    End Property

    Public Overrides Property ContentLength() As Long
        Get
            Return cCompressedGzipResponse.ContentLength
        End Get
        Set(ByVal value As Long)
            cCompressedGzipResponse.ContentLength = value
        End Set
    End Property

    Public Overrides ReadOnly Property Headers() As System.Net.WebHeaderCollection
        Get
            Return cCompressedGzipResponse.Headers
        End Get
    End Property

End Class

This next class will handle most of the logic so that your proxy class can be as small as possible:

Public Class WebServiceCompressionHelper
    Public Shared Function GetWebRequest(ByVal uri As System.Uri, ByVal output As WebRequest, ByVal compress As Boolean) As WebRequest

        '*** add gzip
        If compress Then
            output.Headers.Item(Net.HttpRequestHeader.AcceptEncoding) = "gzip"
        End If

        Return output
    End Function

    Public Shared Function GetWebResponse(ByVal output As WebResponse, ByVal request As System.Net.WebRequest) As WebResponse

        Dim compressedResponse As HttpWebResponse = Nothing
        If TypeOf output Is HttpWebResponse Then
            compressedResponse = CType(output, HttpWebResponse)
        End If

        If compressedResponse IsNot Nothing AndAlso compressedResponse.ContentEncoding = "gzip" Then
            output = New UncompressedGzipResponse(compressedResponse)
        End If
        Return output
    End Function
End Class

In order to make use of this we need to tap into a few methods in the auto generated proxy.  The easiest way to do this is to extend the proxy class into your own subclass, like so:

Public Class MyService
    Inherits generated.proxy.class.here
    Protected Overrides Function GetWebRequest(ByVal uri As System.Uri) As System.Net.WebRequest
        Return Walshgroup.Webservices.Common.WebServiceCompressionHelper.GetWebRequest(uri, MyBase.GetWebRequest(uri), True)
    End Function
    Protected Overrides Function GetWebResponse(ByVal request As System.Net.WebRequest) As System.Net.WebResponse
        Dim output As System.Net.WebResponse = MyBase.GetWebResponse(request)
        Return Walshgroup.Webservices.Common.WebServiceCompressionHelper.GetWebResponse(output, request)
    End Function
End Class

Now, instead of instantiating your generated proxy class, you will simply instantiate your subclass.

That's it!

 

Categories: Programming | .Net | WebServices
Monday, November 17, 2008 5:30:44 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Putting code in server controls attributes#

You can't do something like this:

<asp:Label id="lbl1" runat="server" Text=<%= CurrentUserName %> />

That is because it won't let you assign a server tag result to the attribute of a server control.

Thankfully, there is a solution:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

 

Categories: Programming | .Net | ASP.Net
Wednesday, October 08, 2008 3:25:31 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Problems Extending Winforms Combobox#

On a recent project, one of my developers was trying to extend the combobox in a winforms project.  We wanted to reuse the same combobox in several places. 

The combobox would always have the same objects bound to it, and we wanted a few functions extra functions on the combobox that would centralize some functionality.

So we inherited from combobox, and in the constructor of our class we created the 5 objects that we need in the dropdown and we added them to the combobox items collection.

So far so good.

But we found that when we made a change in the designer for a form that uses this combobox, the designer put stuff in the designer.vb file.  Lines that were trying to add items to our combobox.

It used the .items.AddRange(...) function and tried to add 1 item for every item that we add in the contructor.

Basically it was looking like the designer instantiated the control, and then was trying to serialize the items in the combobox when we would change anything on the form.

This would eventually cause the designer to blow up, as well as a similar error when we tried to run the compiled code.

The solution was elusive and quite a pain.

Some credit needs to go to Andre for his post.

Basically we needed a way to tell in our code if the control was being hosted in the VS designer.  If it was, then we skipped the part where we populated this dropdown.

So first thing we did was create 2 functions to figure out where the control is hosted:

Private Function IsDesignerHosted() As Boolean
    Return Me.IsControlDesignerHosted(Me)
End Function
Private Function IsControlDesignerHosted(ByVal ctrl As Control) As Boolean
    If ctrl IsNot Nothing Then
        If ctrl.Site IsNot Nothing Then
            If ctrl.Site.DesignMode Then
                Return True
            Else
                Return IsControlDesignerHosted(ctrl.Parent)
            End If
        Else
            Return IsControlDesignerHosted(ctrl.Parent)
        End If
    Else
        Return False
    End If
End Function

Then, because it turns out that testing the DesignMode is useless when you are doing the testing from the constructor, so I had to move the databinding into it's own function along with a instance variable to make sure we only do this one time.

Private cbInit As Boolean = False
Private Sub MyControl_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.VisibleChanged
    If Not cbInit Then
        cbInit = True
        If Not Me.IsDesignerHosted Then
            '*** add items here
        End If
    End If
End Sub

There it is!

 

Categories: Programming | .Net | WinForms
Wednesday, October 08, 2008 1:53:28 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

NHibernate Tutorials#

I have been poking around with NHibernate for a while now, but I am actually writing a small app with it at the moment.

During my time getting it up and running, I came across a few well written tutorials that I want to catalog here in case I want to return to them at some point for more in depth reading.

Great NHibernate Faq:
http://www.tobinharris.com/2007/2/3/nhibernate-faq

Fluent Interface for NHibernate:
http://blogs.hibernatingrhinos.com/...nhibernate.aspx

Alan Northam's Tutorials:
http://devlicio.us/blogs/alan_northam/...part-i.aspx
http://devlicio.us/blogs/alan_northam/...part-ii.aspx
http://devlicio.us/blogs/alan_northam/...part-iii.aspx
http://devlicio.us/blogs/alan_northam/...part-iv.aspx

 

Categories: Programming | .Net | Database
Tuesday, September 16, 2008 2:17:08 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Careful With Those Cookies#

When doing testing, you might find yourself wanting to delete cookies for some URLs on your development machine.

Now, you need to be careful about how you delete these cookies, because Microsoft decided to pull a little trick on you.  They created a folder:

C:\Documents and Settings\[user]\Cookies

This folder seems to contain all your cookies!  But, actually it doesn't.  Deleting these cookies really doesn't clear out the cookies you think you are deleting because the REAL cookies are stored in:

C:\Documents and Settings\[user]\Local Settings\Temporary Internet Files

This folder contains cookies and other temporary internet files, but of the most importance here is that THIS is where you need to clear your cookies from.

I came across another thing on a recent project is that you can't test for the existance of an outbound cookie.

If Response.Cookies.Item("ASDFA") Is Nothing Then
     Response.Write("This Will Never Execute")
End If

Why is this?  It is because with the Response.Cookies collection (but not on the Request's cookies collection) when you request an item from the collection that doesn't exist it CREATES it, with a value of an empty string.

 

Categories: Programming | .Net | ASP.Net
Thursday, July 31, 2008 5:42:33 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

DOs and DONTs of getting a development job#

I have been accepting resumes for a while now trying to find developers for a client of mine.

I will be updating this article from time to time with new stuff.

DO have someone proofread your resume, cover letter, and email body.  Espically if you are not a native english speaker.  If you want your resume to go directly into the trash, then please, write your email with lots of grammer and spelling problems.

DON'T write in your cover letter that, while you don't have the skills/experience they are looking for, you DO have the skills/experience that really matters.  You have just managed to tell the person reading your resume that a) you don't have the skills they need, b) you think you are smarter than the person who came up with the needed skills/experience, and c) you are probably not easy to get along with.  All in the first sentence of your cover letter: BRAVO!

DON'T send a 9 page resume including every project you have ever worked on and details about said project.  I remember when I was told that resumes should be 1 page long (2 at the most) and I thought how wrong that was.  "My resme will be so awesome, 2 pages can't contain it!"  I realized very quickly how wrong I was.  I don't need to know the specifics of some project you worked on for 3 months back in 2002, and I don't need to know a list of every programming langauge, technique, or technology that you have ever touched. 

DO supply a cover letter, or at least turn your email into your cover letter.  It will get you bonus points.

DON'T include a stupid signature on your emails.  I actually received a resume that was signed like this:

--
If fishes could talk they'd ask for legs

Ok I guess that is somewhat funny in a Jack Handy kinda way, but it really doesn't belong on an job application email.

DON'T list "Internet Connection Technologies" that you have experience with.  I swear I got a resume with this as the 2nd heading (after education).  It listed "AOL Dial Up, AOL High Speed DSL, SBC DSL".  Before you start thinking, ok well maybe these were projects they worked on, you know, like working on the team to create AOL's dial up service... no this was not what they meant, it was clear from the rest of the resume.

DON'T just make up stuff if you don't know the answer to a question.  This isn't the ACT: there are penalities for guessing (it makes you look really stupid).  Now clearly there is a difference between making an educated guess (or talking in generalities instead of specifics) and trying to totally pull something out of thin air.  I recently interviewed a candidate who said he didn't have any project experience using AJAX but was aware of AJAX technologies.  So I asked him, can you explain how AJAX works?  I wasn't expecting much, just something about using client side script to make calls to the server w/o reloading the entire page.  Instead the answer we got back was "It's like JAVA running on top of Microsoft."  Up until that point I hadn't decided if this guy was qualified, and had he simply said "No, I am sorry I am not that familiar with AJAX" I probably would have still been considering him, but his terrible attempt at an answer removed all doubt that he was not qualified.

Categories: Interesting | Misc | Programming | .Net | Thoughts
Sunday, July 27, 2008 11:26:33 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Validating Enum Values#

You were a good developer and created an enum to represent the integer values that are being passed into your method.

It makes life easy for everyone.  Good job.

But now you realize that ANY integer can be passed into your function, even though your type only defines a handful of values.

Well, you need to validate the enum values that are coming into your method.

This can be done quickly with the following code snippet:

If Not [Enum].IsDefined(localId.GetType, localId) Then
    Throw New System.ComponentModel.InvalidEnumArgumentException("Invalid local value.")
End If

In this example localId is the variable name of type LocalType.

Categories: Programming | .Net | VB.Net
Thursday, July 24, 2008 1:55:29 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Generating Resx Files For Globalization and Localization#

Using resource files (resx files) for globalization is a standard technicque.  ASP.NET allows you to create 1 resx file per page to help you manage your content.

But when it is time to convert those files into the correctly named localized version to send to the translator, you might find yourself doing a lot of copying and renaming.

So I wrote a little script that does this for you:

Imports System.IO
Module Module1

    Sub Main()
        Dim languages() As String = {"es", "pl", "de", "fr"}
        For Each filepath As String In Directory.GetFiles("C:\translationTest")
            If filepath.Contains("x.resx") Then
                For i As Integer = 0 To languages.Length - 1
                    File.Copy(filepath, filepath.Replace(".resx", "." & languages(i) & ".resx"))
                Next
            End If
        Next
    End Sub

End Module

This will generate all the files for you, and then all you need to do is send the off and wait for the translator to do the REAL work :).

Categories: Programming | .Net | .Net Framework | ASP.Net
Tuesday, July 22, 2008 3:13:50 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Model View Presenter Guidance From MS Patterns and Practices#

Microsoft's Patterns and Practices group has released some guidance for creating MVP web applications.

http://www.pnpguidance.net/Tag/MVPBundle.aspx

I haven't checked this out, so I can't verify if they are worth looking into you, but I will be reading them in the near future.

Categories: Programming | .Net | ASP.Net
Tuesday, June 24, 2008 5:55:57 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

FancyUpload Component#

I recently wrote about how the Flickr Uploadr tool sucks, but the other part of that article was how the web upload tools for Flickr is very nice!

FancyUpload is a set of code using Flash/Javascript to perform out of band file uploads.

This is basically how Flickr allows you to queue files for upload in their web client, and it is very useful in this sense because it would be extremely painful to be forced to post every single image individually.

For me, I am more interested in the ability to post very large files without leaving the brower in a fashion that seems to make it look like it is "stuck" when really it is just uploading a giant file.

 

Categories: Misc | Programming | .Net | ASP.Net | Flash
Tuesday, June 24, 2008 10:26:51 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Globalization and Localization in ASP.NET#

This is a good article from Microsoft on globalization and localization of asp.net applications.

The article describes how to automate the process of moving static content from pages (inside labels) into resource files and setup the proper binding between the content controls and the resource files.

This article has some interesting and useful information as well about some other topics such as global vs local, implicit globalization settings, dealing with scripts etc.

Categories: Programming | .Net | ASP.Net
Monday, June 23, 2008 5:52:24 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

e.Item.Dataitem is nothing?#

So you have some code running in your itemdatabound event handler and you are trying to do someting with e.item.dataitem but it keeps bombing out with errors because e.item.dataitem is nothing.

So, why is e.item.dataitem is nothing??

Answer: Because you are probably using a header or footer in your binding object.  The header/footer will cause the itemdatabound event to fire, but there is no dataitem for them.

Check if the current row is the header or footer, and then you will have no issues with using e.item.dataitem.

Categories: Programming | .Net | ASP.Net
Thursday, June 19, 2008 4:22:37 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

VS.NET Extensions for Sharepoint#

My experience with developing for Sharepoint was very painful.  The jist of it was, unless you are truly going to hook into a lot of the core functionality of sharepoint (document collaboration and workflow) it will be MUCH harder to build an app to run in sharepoint than it would be to build a standalone application.

But MS has released some new extensions that will hopefully ease the pain a little bit:

Announcing: Visual Studio extensions for SharePoint – Developer User Guide

I don't know if I will ever have enough time to implement anything in sharepoint, but these will be nice to have.

Categories: Programming | .Net | ASP.Net
Thursday, June 12, 2008 12:50:21 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Highslide#

We have been working with a pretty cool little javascript toolkit called Highslide.

http://vikjavev.no/highslide/

It gives you some nice lightbox type effects but I like it more because of some of the options to load in iframes and stuff.

Someone wrote some asp.net wrappers as well to make it easier to add to your pages:

http://encosia.com/

 

Categories: Programming | .Net | ASP.Net | HTML | Javascript
Thursday, June 05, 2008 4:21:01 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Visual Studio .Net 2008 - Making sense of all the versions#

Microsoft really does a terrible job explaining all the variations of Visual Studio .Net 2008 (and there are many):

  • Visual Web Developer 2008 Express Edition
  • Visual Basic 2008 Express Edition
  • Visual C# 2008 Express Edition
  • Visual C++ 2008 Express Edition
  • Visual Studio 2008 Standard Edition
  • Visual Studio 2008 Professional Edition
  • Visual Studio Team System 2008 Architecture Edition
  • Visual Studio Team System 2008 Database Edition
  • Visual Studio Team System 2008 Development Edition
  • Visual Studio Team System 2008 Test Edition
  • Visual Studio Team System 2008 Team Suite

After a lot of searching, I finally found this data sheet that explains most of it.

Why this was so hard to find is anyones guess.

Categories: Misc | Programming | .Net | VS.Net
Thursday, March 20, 2008 12:43:45 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Where did my columns go?#

I just noticed this while working on a windows forms .net application.

I made some changes to the underlying business objects that I had bound to a datagridview.  Things looked like they should at runtime, but when I opened up the designer, several of my columns were missing!

After some testing around, I realized that any column that was bound to a property on the object, where I had changed the name of the property, was no longer showing.

I figured it would fail the databind or something, but at least let me change the column details to get things working right!

So I added in fake empty property definitions to the business objects and presto: back come the columns.

After that, I was able to update the databinding field and remove my bogus properties.

 

Categories: Programming | .Net | .Net Framework | WinForms
Wednesday, February 13, 2008 6:15:40 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

BoundFields, DataFormatString, and HtmlEncode#

Ran into this again today.

<asp:BoundField
  DataField="FollowUpDate"   
  DataFormatString="{0:MMM-dd-yy}"   
  HtmlEncode="false"  
  HeaderText="Follow Up Date" />

If you are doing a boundfield in an asp.net gridview, and you play on using the DataFormatString, you have to set HtmlEncode to false.

Kinda stupid, but that's life.

Categories: Programming | .Net | ASP.Net
Wednesday, January 30, 2008 10:33:13 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Using a STYLE block on a page with a Master Page#

I have been asked this a few times, so I decided to write up a little article on it.

The problem is that when you are using master pages in asp.net, the <HEAD> is usually inside the master page template.  So if you are on a page that needs a 1 off change or addition to the style of the rest of the site, you are unable to create a <STYLE> element in your content page.

Well, you CAN create one, but then VS.Net won't show you the designer for your page b/c it keeps asking you to clean up the HTML problems on your page.

The solution I have used is to create a 2nd content place holder in the master page head.  But, I might as well not duplicate effort here, as Rick Strahl has already written the article I am about to write (and apparently, even someone else beat him to the punch).

http://www.west-wind.com/WebLog/posts/5706.aspx

This works very well for this type of situation. 

 

Categories: Programming | .Net | ASP.Net | HTML
Monday, January 14, 2008 7:21:52 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

What could cause this casting error?#

Error:

Unable to cast object of type 'System.Collections.Generic.List`1[EditQuoteController+UnsavedQuoteItemInfo]' to type 'System.Collections.Generic.List`1[EditQuoteController+UnsavedQuoteItemInfo]'.

Yes, you read that right.  Unable to cast object of type X to type X.

I have seen this type of error once before and it was when there were multiple assemblies referencing different version of a common assembly, so even though their names were the same, their versions were different.

But in this instance there is nothing like this that could be having an impact.  All of the classes of consequence are in the same assembly.

Also, I don't get exception very often, only every now and then.

UPDATE:

I think maybe this is happening between builds on my development machine b/c I am storing some data in the session.  So the version in session was from the last build?  Doesn't sound like a great explanation, but it's the best I have at this point.

UPDATE 2:

I am pretty sure that what I wrote in the last update is what is actually happening. 

I used this code:

Try
    list = CType(view.Session.Item(Me.UnsavedKey), List(Of UnsavedQuoteItemInfo))
Catch ex As System.InvalidCastException
    Dim sError As String = "Unable to cast from type " & _
        view.Session.Item(Me.UnsavedKey).GetType.AssemblyQualifiedName & _
        " to type " & GetType(List(Of UnsavedQuoteItemInfo)).AssemblyQualifiedName & _
        ".  The session has been cleared."
    view.Session.Item(Me.UnsavedKey) = Nothing
    Throw New System.ApplicationException(sError)
End Try

Which producted the following 2 types:

System.Collections.Generic.List`1[[EditQuoteController+UnsavedQuoteItemInfo, App_Web_bp-bbqew, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral PublicKeyToken=b77a5c561934e089

System.Collections.Generic.List`1[[EditQuoteController+UnsavedQuoteItemInfo, App_Web_ve7ziow-, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. 

I am guessing this is a by product of using the web site project, instead of web application project.  There are some other reasons why we wanted to use web site instead of web app on this project, so you don't have to scold me: we made the right choice.

But it seems that every time I make a change to the project, it creates a new dynamically named assembly.  So even though the classes are really the same, they are globally different as far as asp.net is concerned.

 

Categories: Programming | .Net | .Net Framework | ASP.Net
Monday, January 14, 2008 3:14:02 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Using Redirects The Right Way For SEO#

Rob Howard has a nice article on how to use the 301 redirect (permanent redirect) in order to get search engines to spider the new page, as opposed to just using Response.Redirect, which will send a 302 (temporary redirect) to the client.

Categories: Programming | .Net | ASP.Net
Thursday, January 10, 2008 2:49:33 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

WebAii Website Automated Testing Framework#

I am always on the lookout for better and easier ways to automate testing of my applications.  Mostly, this stems from my teams not being too keen on implementing testing, so the easier I can make it, the easier it will be to convince others to write tests.

So Phil Haack has suggested a free framework called WebAii, and after taking a quick look, it looks promising.

It supports some nice features like mouse/keyboard actions for Ajax testing, and dom actions (find an element and click it, or whatever).  It also supports unit testing your javascript functions by having your test call the functions.  It also integrates with Nunit.  Nice!

Hopefully I can find some free time (HAHAHHAAH) when I can test this out more in a project.

 

Categories: Programming | .Net | ASP.Net | HTML | Testing
Thursday, January 10, 2008 1:55:44 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Free Flyout and Alternating Panel Controls#

These are some nice looking, cross browser compliant, ASP.NET based, free controls from Obout.com

Flyout can perform stuff like this:

But almost more interesting is how it can be used in conjunction with traditional controls.  For example, you can wire up a nice looking "Alt Text" effect for images and labels, and you can provide some nice explanation in the flyout for how to properly fill in a control.  The example they give on their site shows a textbox for "Routing Number" and when you click on the textbox it shows this in the flyout:

 

 

The alternating content control which is called "Show" (Show examples) can rotate through some content like so:

These are both free controls.  Very nice!

 

Categories: Programming | .Net | ASP.Net
Friday, November 30, 2007 2:18:56 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

VS.Net Macro Editor Errors#

When I try to edit some of my Macros I get this nice little message:

Microsoft Visual Studio Macros: An Add-In has caused an access violation while sinking on 'ProjectAdded'.

Google turns up nothing on this guy.

Does anyone out there have any idea how to fix this?

Categories: Programming | .Net | VS.Net
Monday, November 19, 2007 3:21:26 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

ASP.NET Application Not Reading The Web.Config File#

I recently ran into an interesting problem... my webservice application seemed unable to read info from the web.config file.

I tried adding some invalid < marks to the config file and the app still ran w/o any error (but still wouldn't read the web.config appSettings or connectionString sections).

So I created another IIS application and it worked as expected.

So I deleted the troubled IIS App and recreated it.  Still broken!

The solution was to clear out the ASP.NET Temporarly Files folder in c:\windows\...\...

Once that was gone, and I restarted IIS, everything went back to normal.

 

Categories: Programming | .Net | ASP.Net
Friday, November 16, 2007 10:20:04 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Solution for "Thread was being aborted" exception when you call Response.End (or .Redirect)#

You've probably seen this one.

Whenever you do one of the following:

Response.End()
Response.Redirect("page.aspx")
Server.Transfer("page.aspx")

You end up with a ThreadAbortException, "Thread was being aborted".

I had previously dealt with this by swallowing the ThreadAbortException, which of course isn't a great method, but it worked.

Well today I came across a better way for all of these.

Replace This With This
Response.End HttpContext.Current.ApplicationInstance.CompleteRequest
Response.Redirect("page.aspx") Response.Redirect("page.aspx",false)
Server.Transfer("page.aspx") Server.Execute("page.aspx")
Categories: Programming | .Net | ASP.Net
Tuesday, November 13, 2007 1:06:39 PM (Central Standard Time, UTC-06:00) #    Comments [1]  | 

 

My Dark Theme for Visual Studio.Net#

I have been wanting to try a dark theme for vs.net, but I couldn't quit find one I liked.

So I took bits from here and from Scott Hanselman and created my own.

Take a look at some screen shots, and you can download the settings file at the bottom.

 

 

 

Here is my settings file:
Dark-Theme.vssettings (32.85 KB)

If you like this, please leave a comment!  Thanks.

 

Categories: Programming | .Net | VS.Net
Friday, November 09, 2007 11:42:25 AM (Central Standard Time, UTC-06:00) #    Comments [1]  | 

 

ScottGu Demos Upcoming MVC Framework for ASP.NET#

In a recent gathering of the ALT.NET group, ScottGu gave a demo of the upcoming MVC framework for asp.net.

The article (and video) can be found here.

Lots of people in the ALT community have been working with asp.net and MVC by using one of the OS frameworks out there like Monorail, but I am glad to see that MS is not sitting around waiting on this issue.

Hopefully this will make testing even easier. 

Categories: Programming | .Net | ASP.Net
Tuesday, October 30, 2007 9:44:25 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Date Format Strings#

This article from MSDN shows just about every type of format string you can use on a date:

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

 

Categories: Programming | .Net
Monday, October 29, 2007 1:53:41 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

404s on ASP.NET AJAX script files in the System.Web.Extensions folder#

Recently I ran into a problem where browsing to a newly installed web app produced a bunch of javascript errors.  Stuff like: "'Type' is not defined" and "'Sys' is not defined".

After debugging it for a while, I found the problem to be that URLScan had been installed on the server (Windows 2000 Server), which was preventing any requests with dots in the folder name.

URL Scan is a tool that MS suggested everyone install a while back that acts to filter out many malicious attacks.

So, with the default settings any request for a file inside the scripts\System.Web.Extensions folder would be denied as a 404 b/c of URL Scan.

To fix this, you need to edit the UrlScan.ini file, located in %WINDIR%\System32\Inetsrv\URLscan.  Near the top of the file, change AllowDotInPath from 0 to 1.

The run iisreset to restart IIS and you should be ok!

More info on URLScan is available here:

http://support.microsoft.com/kb/326444

 

Categories: Programming | .Net | ASP.Net | AJAX | IIS
Tuesday, September 11, 2007 2:17:20 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

.NET IL Decompilers Part 3#

Reflector is the one I have been using lately.

It runs well, and has a nice interface. 

Categories: Programming | .Net
Wednesday, September 05, 2007 11:13:38 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Using My.Settings on a referenced project#

I recently ran into some seemingly strange behavior as I was testing a couple windows services I had written.

In my case, I had a test harness program that was referencing the service (an exe) but this could also apply to references to dlls if you are using the projects application settings (My.Settings.Whatever in VB.Net).

After figuring it out, it all makes sense.

When you create an application setting by providing a value in the project's "Settings" tab, the value is written out into a special <applicationSettings> block in your config file.

But, in order to make those values accessible via a strongly typed/intellisense method, a class is created to wrap those values.  The class is in the Settings.vb file that is generated when you first add an application setting to your project.

But there is one more interesting thing to note:  If the settings class doesn't find the item it expects in the config file, it will return the last supplied value by default. 

So what this means is that if create an application setting for XYZ for the value "123" and then change the app.config file directly to change the "123" to "abc", then "abc" will be returned when you run the program.  However, if you were to then alter the config file to remove or rename the XYZ item, then your application would return "123" again when it ran.

Also, if you directly modify the config file, and then try to edit the projects applications settings, it will alert you to the fact that some values have changed, and ask if you want to use the updated values from the config file.  If you say yes, it will overwrite the Settings.vb file to use the new values that you had supplied in the config file.

So, I was referencing a project that used these settings, but when I would update the config file, those updated settings were not seen.  All I had to do was go into the project settings tab, allow it to refresh the Settings.vb file, and rebuild the project.

 

Categories: Programming | .Net | .Net Framework | VB.Net
Wednesday, August 22, 2007 8:07:09 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

TFS Source Control "No Commands Available"#

I just opened VS to do something in TFS Source Control Explorer only to find that all my controls were disabled and right clicking on anything only showed "No Commands Available."

Turns out that this was because I had to change my default source control plugin to VSS for a project I was working on.  If you go to Tools->Options->Source Control and select TFS as the default SCC plugin, it will fix the problem.

Categories: Programming | .Net | VS.Net | TFS
Monday, August 13, 2007 10:48:25 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Right aligning text when printing from a .net program#

In a program I am writing, I need to print directly to a couple of label printers.

My God these things are a pain in the ass to work with, but I will leave that rant to another post.

One thing I ran into was how to right align text when using the DrawString method of the System.Drawing.Graphics class off of the PrintPageEventArgs.

The solutions I was coming across seemed about as bad as I was expecting.

They involved measuring the width of the line of string using some System.Drawing.Graphics.MeasureString to figure out the length, and then dynamically position the text to make it appear right aligned.  So what that means is that for short text, X would be greater and for long text X would be less.

Fortunately, I came across the most simple solution:

Dim s As New StringFormat()
s.Alignment = StringAlignment.Far

e.Graphics.DrawString("por que?", New Font("Tahoma", 8), Brushes.Black, 50, 50, s)

Very simple.  But you have to wonder, why did MS pick "Far" as the alignment name instead of "Right", as you would expect.  Maybe "Far" is more of a graphics term for alignment?  Who knows.

 

Categories: Programming | .Net | .Net Framework | WinForms
Monday, August 06, 2007 2:44:24 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Subsonic MVC Templates. Not what I was expecting.#

When I saw a new item in my RSS feed from Rob Conery about MV* I was immediately interested to read it, because I have been working on trying to create my web app pages using MVP, but am unable to find any examples beyond the most basic.

I would love to see how other people manage the interactions between the Controller and the View, to see how it compares to how I am doing it. 

My view interfaces tend to be kinda large.  For example, if I have a button that I hide and show depending on business rules, I will create a MyButtonVisibility property on the interface can set the properties from the controller.

I would be interested to see how others deal with things like the hiding / showing of items.  I could see wrapping more of that kind of functionality in the view, and giving the view some more logic but I think you would then start to lose some of the testability.

Anyway, the articl on Rob's blog was really to talk about creating an MVC style architecture for subsonic itself, not the pages that use it.  However, Rob seemed to suggest that the new changes would aid you in using MV* in your pages by forcing you into good habits.

But I really don't understand how that would work.  If you have code that does:

MyGridView.DataSource=Product.FetchAll();
MyGridView.DataBind();

And you change it so that you use a Controller (or Manager as I have called it when loading Business Objects or DTOs) to look like this:

Product product = ProductController.Get(newID);
product.ReorderLevel = 100;
ProductController.Save(product,"unit test");

I don't see how this helps you create an MV* architecture in your pages.

Maybe I am just not understanding.

 

Categories: Programming | .Net | ASP.Net | Architecture
Thursday, July 19, 2007 10:06:07 AM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

 

Getting Enterprise Services Working#

I have been trying to get Enterprise Services working in one of my clients environment. 

The latest hurdle was cleared thank to this article, which pointed out the need to modify the settings for windows firewall to allow the msdtc executable to talk OUT.

To enable network transactions through the firewall, you will need to add the msdtc.exe to the exception list of the firewall on all the machines involved in the transactions. You can do this using the UI in Control Panel\Windows Firewall or you can use this command: “netsh firewall set allowedprogram %windir%\system32\msdtc.exe MSDTC enable”.

Categories: Programming | .Net
Thursday, July 12, 2007 4:08:03 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

.NET "How Do I" Videos#
Categories: Programming | .Net
Friday, June 29, 2007 9:26:33 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

ASP.NET "How Do I" Videos#

The asp.net site has a section where they are putting up short videos showing how to do things in asp.net as well as VSTS and asp.net AJAX.

You can find the site here, and the RSS feed here.

There are some similar videos started to get produced for TFS here, with an RSS feed here.

 

Categories: Programming | .Net | ASP.Net
Tuesday, June 26, 2007 5:50:51 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Managing the number of assemblies#

Scott Hanselman has an article on trying to pick the right number of assemblies when creating an application.

Much of my work is on a large intranet application, which brings lots of considerations into the fold.  We have started segmenting different web applications into their own projects, meaning they are seperate applications in IIS.

Of course this means that common functionality now needs to be broken out into assemblies.

Also, we had the practice of creating 1 data access assembly for each database we touched.  This was pretty simple at first as we only had a handful of databases, but now have 16 of these assemblies, am I am starting to think we should just merge them all into 1.

I downloaded a trial of NDepend which produced a pretty neat diagram connecting assemblies together.  I am going to try to see if I can refactor out a few (maybe only 2 are options at this point).

Categories: Programming | .Net
Wednesday, June 20, 2007 10:04:43 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Speeding Up Visual Studio#

I would love to speed up VS, and maybe get it to stop crashing, but in the short term, maybe some of these items can help speed it up.

Categories: Programming | .Net
Thursday, June 07, 2007 7:55:41 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Microsoft P&P Software Factories#

I didn't notice that the Microsoft P&P team has released something they call "Software Factories" which are supposed to guide the developer in building different apps using best practices (at least that is what I think they do from the descriptions).

Specifically I am interested in the Web Client Software Factory:

... provides an integrated set of guidance that assists architects and developers in creating composite Web applications and page flow client applications.

These applications have one or more of the following characteristics:

  • They have complex page flows and workflows.
  • They are developed by multiple collaborating development teams.
  • They are composite applications that present information from multiple sources through an integrated user interface.
  • They support XCopy deployment of independently developed modules.
  • They support online business transaction processing Web sites.

 

and the Web Service Software Factory, which as they put it is:

... an integrated collection of tools, patterns, source code and prescriptive guidance. It is designed to help you quickly and consistently construct Web services that adhere to well known architecture and design patterns.

The package covers:

  • Designing ASMX and WCF messages and service interfaces.
  • Applying exception shielding and exception handling.
  • Designing business entities in the domain model.
  • Translating messages to and from business entities.
  • Designing, building, and invoking the data access layer.
  • Validating the conformance of service implementation, configuration, and security using code analysis.
  • Planning for the migration to WCF.
  • Applying security to WCF services.
  • Applying message validation.
  • Categories: Programming | .Net | ASP.Net | WebServices
    Tuesday, June 05, 2007 11:59:00 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    TechEd WebCasts / Virtual Labs#

    TechEd is going on right now.

    They have some webcasts, both on demand and live, as well as some virtual labs.

    Categories: Programming | .Net
    Monday, June 04, 2007 3:08:32 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Nice NUnitASP writeup.#

    Over at TheServerSide they had a nice writeup of an example of how to use NUnitASP to test the UI of some pages.

    I am not sure how valuable this would be to invest my time in, espically as it seems that there is now way to test repeaters or gridviews (there is a datagridtester however).

    I will have to look some more and see if ther eis a way to do this.

    Categories: Programming | .Net | ASP.Net | Testing
    Sunday, June 03, 2007 3:48:28 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Refactor! for ASP.NET#

    This looks really cool. 

    You can download it here for free.

    Included Refactorings

    Add Validator
    Create Overload
    Encapsulate Field
    Extract ContentPlaceHolder
    Extract ContentPlaceHolder (create master page)
    Extract Method
    Extract Property
    Extract Style (Class)
    Extract Style (id)
    Extract to User Control
    Flatten Conditional
    Inline Temp
    Introduce Constant
    Introduce Local
    Introduce Local (replace all)
    Move Declaration Near Reference
    Move Initialization to Declaration
    Move Style Attributes to CSS
    Move to Code-behind
    Rename
    Reorder Parameters
    Replace Temp with Query
    Reverse Conditional
    Safe Rename
    Simplify Expression
    Split Initialization from Declaration
    Split Temporary Variable
    Surround with Update Panel
     

    UPDATE:  It seems that installing this may have removed some of the features of the old Refactor! that I was frequently using (?).  I used to use the "Surround With-->Region" all the time.  Now that is gone.  I will have to investigate.

    Categories: Programming | .Net | ASP.Net | Tools
    Friday, June 01, 2007 9:57:43 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    The "Microsoft Crossroads"?#

    Sam Gentile thinks that MS is at a crossroads in terms of web development.

    He thinks with all the cool, free, cutting edgs stuff out there, like Ruby on Rails, MS may soon lose out on all the "alpha geeks", who move on to newer and better things while MS stays locked in the past.

    I'm not ready to crown RoR the winner of anything yet.  True, MS is usually not on the cutting edge, but they usually do a pretty good job adopting good ideas.  There are only a handful of serious RoR sites out there.  If that number grows a ton, then it will mean something. 

    Martin Fowler has some similar concerns though, so maybe this will come to fruition.

    Categories: Programming | .Net | .Net Framework
    Thursday, May 31, 2007 9:15:46 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Unit testing data access #

    Roy Osherove blogs that he was mistaken when he suggesting using mocks for data access code.  With the improved Rollback attributes that he helped create, along with people like Justin Burtch who created a similar attribute for VSTS, they are now thinking that this is the way to go: rolling back database changes.

    Roy is no fan of VSTS testing, finding a few bugs and some questionable design decisions.  Those don't seem like deal breakers for me, but we will see.

    Categories: Programming | .Net | .Net Framework | Testing | TFS
    Tuesday, May 29, 2007 9:48:11 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    BindingListView#

    The BindingList is very nice, but doens't support some things like sort and filter that a lot of people would like to have (see here for a short discussion on BindingList vs Datatable).

    This project, in sourceforge, called BindingListView is supposed to allow you to get a sorted or filtered "view" of a bindinglist.

    Might be worth checking out.

    Categories: Programming | .Net | .Net Framework
    Tuesday, May 29, 2007 9:19:00 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Asp.net Label vs Literal#

    It looks like I have fallen victim to an asp.net no-no.

    I have always used a label in my forms when I want to have some text that is updated by the code behind.  Turns out that I should probably be using literals.

    Even more, I didn't even realize that the label object allows you to specify a text element that will gain focus when the label is clicked.  Nice.

    Categories: Programming | .Net | ASP.Net
    Monday, May 28, 2007 2:49:53 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Polymorphic podcast#

    This site looks really interesting.  They seem to have loads of video content, interviews and examples.

    The one that got me looking at the site was their video on MVC/MVP pattern.

    http://polymorphicpodcast.com/shows/mv-patterns/

    I will be checking this out.

    Categories: Programming | .Net
    Monday, May 28, 2007 2:41:58 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Rhino Mocks#

    Rhino Mocks seems to be one of the most preferred mock frameworks out there.

    Phil Haack, CodeBetter and Markitup have article showing how to test events on interfaces (x2) and objects in Rhino Mocks respectively.

    They even have some videos up showing some Rhino Mocks stuff.

    Haack also has a nice example of using MVP and Rhino Mocks to test some asp.net pages.

    Categories: Programming | .Net | ASP.Net | Testing
    Monday, May 28, 2007 2:33:20 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    LINQ to SQL#

    ScottGu has an article on using LINQ to SQL which is basically going to work like an ORM product shipping in the next version of .net / visual studio called Orca.

    http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

    Categories: Programming | .Net
    Tuesday, May 22, 2007 3:20:45 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Drill Through Reports using Report Viewer and ASP.NET 2.0#

    Here is an interesting article on codeproject about creating "drill through" reports.

    Categories: Programming | .Net | ASP.Net | Reporting
    Friday, May 11, 2007 1:22:26 PM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

     

    Webservices Compression#
    Categories: Programming | .Net | .Net Framework | VB.Net | WebServices
    Wednesday, May 02, 2007 3:34:54 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    WCF One-Way Calls, Callbacks, And Events#

    Here an article I was reading about some of the new (and from the looks of it... very useful) features of WCF.

    One-Way calls, callbacks, and events.

    Categories: Programming | .Net | .Net Framework
    Monday, April 30, 2007 2:03:06 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    ASP.NET AJAX Errors#

    I have been getting a few errors when trying to use the asp.net ajax framework.

    The one error message is:

    Error: Sys.ArgumentTypeException: Object of type 'Sys_Application' cannot be converted to type 'Sys._Application'/

    Parameter name: instance

    This is caused by having SmartNavigation turned on for the page. 

    The other error I was getting was this Sys.ArgumentOutOfRangeException.  Value must be an integer.  Parameter name: X.  Actual value was NaN.

    This error is caused by using a "yes" or "no" for "frameborder" for a frame.

    Yes and No are valid entries but the framework is expecting a "1" or a "0".

     

    Categories: Programming | .Net | AJAX | ASP.Net
    Thursday, April 26, 2007 3:16:06 PM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

     

    ASP.NET Upload Component#

    I think I saw this ABCUpload .Net tool being used by microsoft on one of their internal support sites for uploading large files.

    I don't think it actually gets around the httprequest length and executiontimeout problems, but it does provide you a window showing your progress, which is nice.

    Categories: Programming | .Net | ASP.Net
    Monday, April 23, 2007 4:05:47 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Escaping Characters in MailTo#

    I have recently needed to create some more complex mailto links than people normally use.  I need to populate the subject and body with text that is pulled from a DB, so there are lots of random characters in there like @, #, &, -, _, etc...

    Most of these won't work, and need to be escaped.

    The most effective way I found was to use the ascii HEX code in this format:

    %2D = "-"

    %45 = "E"

    Categories: .Net | HTML
    Monday, April 23, 2007 1:38:51 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    ASP.NET Process Recycling Too Often#

    I'm not going to write too much about this, but we have been seeing a LOT of recycles of our web application, which makes us lose session for everyone logged it.

    I am just going to archive a few links I have been using to track down this problem.

    ScottGu has some reflection code to get the reason the process is shutting down that I converted to vb.net

    Scott Gu's Article

    And here are some places discussing the issue:

    asp.net thread

    Todd Carter's Blog Article

    Scott Forsyth's Blog Article

    Categories: Programming | .Net | ASP.Net
    Wednesday, April 11, 2007 10:34:58 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    ASP.NET Design Patterns#
    Categories: Programming | .Net | .Net Framework | ASP.Net
    Wednesday, April 11, 2007 10:17:54 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Neural Network#

    This article shows a open source neural network component that the author uses for verification of written characters.
    Categories: Programming | .Net
    Tuesday, April 10, 2007 3:37:46 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Controlling Programs Remotely#

    It looks like from this article that the author is showing how to use remoting to interact with a windows form running on a server.

    http://www.codeproject.com/csharp/RemoteWinControls.asp

    Pretty interesting.

    Categories: Programming | .Net | .Net Framework
    Tuesday, April 10, 2007 3:32:23 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Working with Active Directory and .Net#

    I have written a few programs in .Net that utilize Active Directory (AD), and what a pain it was.

    Here is an article where the author created classes to encapsulate some of the objects in AD, which is pretty similar to what I did.

    Keywords: LDAP, AD, Active Directory

    Categories: Networking | ActiveDirectory | Programming | .Net
    Tuesday, April 10, 2007 3:29:54 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    TypeOf VB.NET vs C##

    If you are Microsoft, why do you create a function "TypeOf" that has totally differnet applications in VB and C#?

    Typeof in C# is like GetType in VB, where VB uses TypeOf to see if 2 types are the same or check for interface implementation.

    Kinda dumb.

    Categories: Programming | .Net | C# | VB.Net
    Friday, April 06, 2007 8:59:58 AM (Central Daylight Time, UTC-05:00) #    Comments [3]  | 

     

    ASP.NET RegularExpressionValidator with Phone Extension Numbers#

    The built in options for validating an email address didn't include any way to validate phone numbers that include extension numbers.

    Here is a regular expression that does this:

    ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}( x\d{0,})?

     

    Categories: Programming | .Net | ASP.Net
    Thursday, March 22, 2007 5:42:21 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    How to get the TOP X rows from a DataTable or DataView#

    Here is a function I found that can trim down a datatable/dataview to a limited number of rows.  Basically, it's like doing a "TOP X".

    ''' <summary>
    ''' Will return a dataview with only the top "number" of rows.
    ''' </summary>
    ''' <param name="myDataView">dataview to "trim"</param>
    ''' <param name="number">the number of rows to return</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetTopDataViewRows(ByVal myDataView As DataView, ByVal number As Integer) As DataView
        Dim tableToClone As DataTable = myDataView.Table.Clone
        Dim i As Integer
        For i = 0 To number - 1
            If i >= myDataView.Count Then Exit For
            tableToClone.ImportRow(myDataView(i).Row)
        Next
        Return New DataView(tableToClone, myDataView.RowFilter, myDataView.Sort, myDataView.RowStateFilter)
    End Function

    I didn't write this, credit goes to this post.

    Categories: .Net | .Net Framework
    Friday, February 23, 2007 3:06:17 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Gridview, DateFormatString, and HtmlEncoding#

    Here is the original source of this tip.

    "for some bizarre reason, you have to set HtmlEncode=false on a bound column in a gridview, to get the DataFormatString to work. "

    Categories: Programming | .Net | .Net Framework | ASP.Net
    Tuesday, February 20, 2007 11:59:55 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    VB Keyboard Shortcut Poster#

    Shows all the vs.net ide shortcuts for vb.net.

    Categories: Programming | .Net | VB.Net
    Sunday, February 04, 2007 11:15:33 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Understanding Object Pooling#

    Here is an article discussing object pooling.  How to use them, and some code examples.

    Categories: Programming | .Net
    Sunday, February 04, 2007 11:13:31 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    VS.Net SP1... kinda crashy#

    I installed Vs.Net a few days ago... and so far I think I have had 4 complete crashes of VS.Net.

    I am not sure that this is being caused by SP1, but it is crashing in ways it never did before.

    I will give it another few days and then rollback if this keeps happening.

    Categories: Programming | .Net | VS.Net
    Thursday, January 11, 2007 2:49:35 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    .Net Search Engine#

    Lucene.Net is another document index search engine.

    You can point it at some files, office, pdf, rtf, html, and it will index them and provide a nice google-like results page.

    http://dotlucene.net/

    Categories: Programming | .Net | ASP.Net
    Thursday, November 23, 2006 9:21:13 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Dealing with WinForms Combobox and name/value items.#

    I just read this article on aspalliance.com by Sandeep Archarya.

    I think the article had 2 main points.  One was that databinding a combobox is not "bug free" because the act of manually databinding to a combobox causes the SelectedIndexChanged event to fire.  The second point was to show how to create a simple namevalue class to be added to the combobox items collection to get around the "problem" of combobox's taking an object as the item in it's list (as opposed to a name value pair).

    I would point out the following:

    First, I am not sure that I would call the SelectedIndexChanged event firing a bug.  When you manually databind a list, the first item become selected by default, and thus the selectedindex HAS changed, from -1 to 0.

    Second, if you consider this a problem you can get around it a couple different ways.

    1) Don't use manual databinding.

    In the designer, select a datasource or create a new one.  I created a simple employee object and created an object datasource for this employee.  This creates a EmployeeBindingSource object that I bind my employee list to.  Using this method, I didn't experience the SelectedIndexChanged event firing on the databind.

    Private list As New System.Collections.Generic.List(Of employee)
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '*** create some fake employee objects
       For i As Integer = 70 To 80
          list.Add(New employee(i, Chr(i)))
       Next

        '*** this will populate our control (Combobox1)
       Me.EmployeeBindingSource.DataSource = list

    End Sub

    2) You can use manual databinding, and manually detach and attach the event handler for this event.

    Private list As New System.Collections.Generic.List(Of employee)

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        
        '*** create some fake employee objects
       For i As Integer = 70 To 80
          list.Add(New employee(i, Chr(i)))
       Next

        '*** remove the handler
        RemoveHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
        '*** databind
        Me.ComboBox1.ValueMember = "id"
        Me.ComboBox1.DisplayMember = "name"
        Me.ComboBox1.DataSource = list
        '*** add the handler back
        AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
    End Sub

     

    Categories: .Net | .Net Framework | DataBinding | WinForms
    Friday, November 10, 2006 4:32:43 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    .Net 3.0 Free Online Labs From Microsoft#

    Microsoft is offering some free online lab training on .Net 3.0 for a limited time.

    Use this link: http://msdn.microsoft.com/virtuallabs/netframe/default.aspx

    Categories: Programming | .Net
    Monday, November 06, 2006 4:37:39 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    VS.Net for Database Launch Event#

    Microsoft is releasing "Visual Studio Team Edition 2005 for Database Professionals" (who on Earth comes up with these names????).

    MS is holding some launch events all over where you can come (for free) and learn a little about this product, which from what I saw looks pretty slick.

    http://www.teams-deliver.com

    Categories: .Net | VS.Net | SQL Server
    Monday, November 06, 2006 4:36:25 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Convert RTF to HTML#

    More than once I have looked into a way to convert RTF into HTML.  Mostly because there are RTF textboxes available for winforms, but you might want to save the page as HTML, and not RTF.

    This article shows a way to do this that:

    http://www.codeproject.com/vb/net/RTFToHTML.asp

    Categories: Programming | .Net | .Net Framework
    Monday, November 06, 2006 4:33:56 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Missing Step in, Step Out and Macros in VS.Net#

    A while back I had some problems with a coworkers VS.net settings.

    They were missing the step in and step out as well as the Macros option in the tools menu.

    We were able to get these back by changing the VS.Net settings by going to Tools->Import and Export settings.

    Then select to Import settings and pick where you want to backup your current settings.

    Then I think we picked "Visual Basic Development Settings" or maybe "General Development Settings."  This seemed to get things back to normal for the most part.

    I still have a few problems, like if I am working on some file, that file will not be highlighted in the solution explorer (what a pain) and I can't right click on a webform and select "View Code" (what a pain).

    It looks like MS was trying to make it really customizable, but I think they ended up making it a pain to get things working the way you expect them to.

     

    UPDATE:
    I was able to quickly find a setting to make sure that the current page I was working on became tracked in Solution Explorer:

     

    Categories: Programming | .Net | VS.Net
    Wednesday, November 01, 2006 4:38:40 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    AJAX Toolkit Library Growing#

    A while back I was looking at the AJAX toolkit page (http://ajax.asp.net/ajaxtookit) and I was really not impressed with anything I saw.

    Things like the "Confirm" button, which is basically a button with 10 seconds of javascript coding built into it isn't a big deal, IMO.

    But their list of controls has really grown and there are some really interesting things in that toolkit.

    It still boggles my mind that they don't have an autocomplete dropdown list where your selections are LIMITED to the choices from the list.

     

    Categories: Programming | .Net | AJAX | Javascript
    Tuesday, October 24, 2006 3:29:30 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Printing Vb.Net Forms with PrintForm Component#

    Microsoft has released their first 3 Power Packs for Visual Basic 2005, which are "free Add-Ins, Controls, Components, and Tools for you to use with Visual Basic 2005 to make developing great applications even easier."

    1 of the first 3 is the Microsoft PrintForm Component 1.0 , which gives you the ability to easily print a form.

    I could have really used this on my last project, where I manually wrote the code to do just that.

    Categories: Programming | .Net | VB.Net | VS.Net
    Monday, October 09, 2006 2:58:15 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Make Use Of Culture in SQL Reporting Services Local Reports#

    When using SQL Reporting services, you can format things such as dates and currency.

    However, depending on the situation you might want to:

    1. Show a report with culture X on a computer running culture Y.
    2. Show a report using the same culture settings as the local computer.

    To do (1), all you have to do is set the "Language" parameter of the local report in design time.

    To get (2) to work, you need to set the Language parameter of the report as the expression "=User.Language".  This will set the report culture as the culture that the hosting program is running under.

    If you have a program that you need to switch between different cultures, you can do so with the following line of code (which changes the culture to "English-Ireland")

    System.Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("en-IE", False)

    More information can be found at: http://msdn2.microsoft.com/en-us/library/ms156493.aspx

    Categories: Programming | .Net | .Net Framework | Reporting
    Monday, October 09, 2006 1:43:24 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Convert a String to a Byte Array in VB.Net#

    I had a snippet on my site for converting a byte array to a string, but I didn't have anything for going the other way.

    This function should do the trick.

    Public Shared Function StringByByteArray(ByVal s As String) As Byte()
        Return System.Text.Encoding.UTF8.GetBytes(s)
    End Function


    Categories: Programming | .Net | VB.Net
    Wednesday, October 04, 2006 3:44:23 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Regular Expressions Tutorial#

    This is really a great tutorial on using regular expressions.

    http://www.regular-expressions.info/tutorial.html

    The information is broken down into sections, which appear on the left hand side.

     

    Categories: Programming | .Net
    Tuesday, October 03, 2006 3:50:20 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Default Buttons in ASP.NET 2.0#

    ASP.NET has this thing where pressing Enter on a page will cause it to be submitted, but no submit action is taken, mostly because you can have multiple buttons on a page, and it isn't sure which button it should consider clicked when you press enter.

    The solution to this was the "__EVENTTYPE" field.  Click here for more info on __EVENTTYPE.

    Thankfully ASP.NET 2.0 has introduced some new features to help remove this complexity.

    Scott Gu blogs about the new form defaultButton property, as well as the new SetFocusOnError property of the validators here:

    http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx

     

    Categories: Programming | .Net | ASP.Net
    Saturday, September 30, 2006 3:55:52 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    VS.Net Macro to Narrow VB.Net Method Signatures and Function Calls#

    Lately I have been doing some refactoring of code as I go through it.

    Trying to name variables correctly, breaking up long methods, trying to adhere to some coding standards.

    One way that I have been employing to clean up code is to convert very long method signatures, or calls to methods with many parameters from LONG single line entities to shorter multi-line blocks.

    This is simple, but tedious.  So I wrote a VS.Net macro to do it for me.

    Simply copy and paste the macro code (paste into wordpad first to get rid of the missing newline problem) at the bottom of this article into a macro.  Then all you have to do is highlight the entire row you want to "narrow", and run the macro.  You can always Cntl+z out of it if you want to undo the changes.

    The results are good!  The following are examples of a long method signature, and a call to a method with a lot of arguments, and then the refactored results.

    '*** Long method signature
    Public Function ActivitySave(ByVal Activity As MyNamespace.Business.Equipment.Activity, ByVal StartTime As DateTime, ByVal EndTime As DateTime, ByVal StatusOverride As System.Nullable(Of MyNamespace.Business.Data.Criteria.Equipment.ActivityStatusEnum), ByVal Clerk As Integer) As Integer

    '*** long method call
    ActivityID = MainActivity.ActivitySave(Activity.ActivityID, Activity.Status, Activity.PurposeNotes, Activity.JobIndex, Activity.CategoryID, Activity.RequestedStartDate, Activity.RequestedEndDate, Activity.EquipmentID, Activity.PlanStartDate, Activity.PlanEndDate, Activity.ActualStartDate, Activity.ActualEndDate, Activity.DiscountScheduleID, Activity.DiscountOffset, Activity.CodeID, Activity.RentalRate, Activity.RowVersion, Clerk)

    Here is the result of the refactoring:

    '*** Refactored long method signature
    Public Function ActivitySave(ByVal Activity As MyNamespace.Business.Equipment.Activity, _
    ByVal StartTime As DateTime, _
    ByVal EndTime As DateTime, _
    ByVal StatusOverride As System.Nullable(Of MyNamespace.Business.Data.Criteria.Equipment.ActivityStatusEnum), _
    ByVal Clerk As Integer) As Integer

    '*** Refactored long call
    ActivityID = MainActivity.ActivitySave(Activity.ActivityID, _
    Activity.Status, _
    Activity.PurposeNotes, _
    Activity.JobIndex, _
    Activity.CategoryID, _
    Activity.RequestedStartDate, _
    Activity.RequestedEndDate, _
    Activity.EquipmentID, _
    Activity.PlanStartDate, _
    Activity.PlanEndDate, _
    Activity.ActualStartDate, _
    Activity.ActualEndDate, _
    Activity.DiscountScheduleID, _
    Activity.DiscountOffset, _
    Activity.CodeID, _
    Activity.RentalRate, _
    Activity.RowVersion, _
    Clerk)

     

    Here is the macro.

     Public Sub NarrowMethodsAndCalls()
    'Create an Undo context object so all the changes can be
    'undone by CTRL+Z
    Dim oUnDo As UndoContext = DTE.UndoContext

    'Supress the User Interface. This will make it run faster
    'and make all the changes appear once
    DTE.SuppressUI = True
    Try


    Dim oTextSelection As TextSelection = DTE.ActiveWindow.Selection
    Dim sOrigText As String = oTextSelection.Text

    Dim RegExp As New System.Text.RegularExpressions.Regex("([ .=_a-zA-Z0-9]*)\(")
    Dim Match As System.Text.RegularExpressions.Match = RegExp.Match(sOrigText)
    If Match.Success Then
    Dim sMethod As String = Match.ToString
    Dim sParametersAndReturn() As String = sOrigText.Replace(sMethod, "").Split(",")
    Dim sFirstLineWhiteSpace As String
    Dim sb As New System.Text.StringBuilder
    sb.Append(" ", Trim(sMethod).Length)
    sFirstLineWhiteSpace = sb.ToString

    '*** redo the first line
    oTextSelection.Text = sMethod & sParametersAndReturn(0) & ", _"
    oTextSelection.NewLine()
    oTextSelection.Text = sFirstLineWhiteSpace

    For i As Integer = 1 To sParametersAndReturn.Length - 2
    oTextSelection.Text = Trim(sParametersAndReturn(i)) & ", _"
    oTextSelection.NewLine()
    Next
    oTextSelection.Text = Trim(sParametersAndReturn(sParametersAndReturn.Length - 1))
    oTextSelection.NewLine()



    Else
    MsgBox("failed to find function regexp match")
    End If
    Catch ex As Exception
    MsgBox("Error: " & ex.ToString)
    Finally

    'If an error occured, then need to make sure that the undo context is cleaned up.
    'Otherwise, the editor can be left in a perpetual undo context
    If oUnDo.IsOpen Then
    oUnDo.Close()
    End If

    DTE.SuppressUI = False
    End Try

    End Sub
    Categories: .Net | VB.Net | VS.Net | Macros
    Wednesday, September 27, 2006 10:52:05 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    SmartNavigation with Metabuilders Combobox#

    I ran into a little problem trying to integrate Metabuilders combobox into an asp.net web app I am creating.

    The problem was that the onload event handler was not properly firing when smartNav was turned on.

    The "InitScript" was as follows:

    if ( typeof( window.addEventListener ) != "undefined" ) {
        window.addEventListener("load", ComboBox_Init, false);
        alert('case 1');
    } else if ( typeof( window.attachEvent ) != "undefined" ) {
        window.attachEvent("onload", ComboBox_Init);
    } else {
        ComboBox_Init();

    }

    Well when you are using smartNav, the window.onload event is only fired the first time you reach the page.  So I used this bit of C# in the control to get it to work.

    String initScript = resources.GetString("InitScript");
    if (this.Page.SmartNavigation)
    {
    this.Page.RegisterStartupScript("MetaBuilders.WebControls.ComboBox Init with Smartnav", "<script>ComboBox_Init();</script>");
    }
    else
    {
    this.Page.RegisterStartupScript("MetaBuilders.WebControls.ComboBox Init", initScript);
    }

     

    Categories: Programming | .Net | ASP.Net | C# | Javascript
    Monday, September 25, 2006 8:06:55 PM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

     

    Extending the Atlast AutoComplete Extender#

    I have been looking at the new "Atlas" controls, which MS has brilliantly (sarcasm) decided to rename "ASP.NET AJAX".

    The one control I have been most interested in is the autocomplete extender.

    I want to use something like this, not to help populate a textox, but instead to allow the user to type a few characters in to narrow down the list of options, rather than showing them a dropdown of 10,000 items.

    In otherwords, when they are done with the control, I don't want the text in the textbox, I want the database ID value behind it, and i also don't want to let them type in just anything they want, but rather limit their options to what is in the autocomplete options.

    I found another blog post where someone is extending the autocomplete behavior:

    http://aspadvice.com/blogs/garbin/archive/2006/01/02/14518.aspx

     

    Categories: Programming | .Net | ASP.Net
    Monday, September 18, 2006 1:39:31 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Debug = true in web.config files#
    Categories: Programming | .Net | ASP.Net
    Thursday, September 14, 2006 2:22:27 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Performance of Web Services / Remoting / Enterprise Services#

    I had previously read and heard in presentations by Rocky Lhotka that performance comparisons between Web Services and Remoting showed that they were basically the same, and that when talking about RPC protocols ES killed them both so badly (order of magnitude) that it wasn't worth fretting over the small diff between WS and remoting.

    Rocky kinda explains this position in this post:
    http://www.lhotka.net/weblog/RemotingVsWebServicesVsESCOMDCOM.aspx

    However, I actually tracked down the white paper on Microsofts website:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwebsrv/html/asmxremotesperf.asp

    Much to my suprise the giant performance improvement when using ES was only seen when calling empty functions.  In otherwords, it was basically a test of the transport.  Some "real world" tests showed ES performing faster than most other methods, but sometimes something like Remoting TCP Binary would outperform it as well.

    In the tests that actually did something, the performance across the board was usually fairly comperable.  I guess this makes sense.  If you liken the round trip of an RPC call to a person going on a business trip, the speed of the airplane is less important that the time it takes the person to do the job at the end of the trip.  So even if your plane takes 3 hours instead of 2 hours, if your going to be staying for a week then that 1 hour isn't a big deal.

    The major conclusion is to not pass datasets.  Datasets are serialized as XML even if you are using the binary serializer.  I have posted some stuff on this topic as well on my blog so you can search for it if you want. 

    Categories: Programming | .Net | .Net Framework | Architecture | WebServices
    Thursday, September 14, 2006 9:12:30 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Data Driven Checkbox (Horizontal) Lists#

    This control is pretty cool.  It makes it pretty easy to databind data into a list of checkboxes.

    http://developer.coreweb.com/articles/Default6.aspx

    Categories: Programming | .Net | ASP.Net | DataBinding
    Wednesday, September 06, 2006 5:54:56 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Rocky Lhotka and Csla.Net/Asp.Net on DnrTV#

    Rochy Lhotka appeared again on DNR-TV for 2 more segments focusing on CSLA in ASP.Net and WebServices:

    http://www.dnrtv.com/default.aspx?showID=32

    http://www.dnrtv.com/default.aspx?showID=33

    Having successfully completed a CSLA.Net project for Wilson Sporting Goods I am interested to see what is different in the web side vs the winform side.

    Categories: Programming | .Net | ASP.Net | DataBinding
    Wednesday, September 06, 2006 4:39:48 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Checking an objects type or implemented interfaces#

    A common thing people might want to do is check if a object is a certain type, or inherits a type, or implements a type.

    This can be done in VB.Net with the following code:

    TypeOf someObject Is ClassName

    This works for inheritance heirarchy as well as checking for interface implementation.

    Here is a sample app showing it in practice.

    imports Microsoft.VisualBasic
    imports System
    Imports System.Collections.Generic

    public module MyModule
        sub Main
    dim o as new subclass
            WL(typeof o is subclass)
            WL(typeof o is baseclass)
            WL(typeof o is IWhatever)
            RL()
        end sub

        #region "Helper methods"

        sub WL(text as object)
            Console.WriteLine(text)
        end sub

        sub WL(text as object, paramarray args as object())
            Console.WriteLine(text.ToString(), args)
        end sub
            
        sub RL()
            Console.ReadLine()
        end sub
        
        sub Break()
            System.Diagnostics.Debugger.Break()
        end sub

    #end region

    end module


    public interface IWhatever
    end interface
    public class BaseClass

    end class

    public class SubClass
    inherits BaseClass
    implements IWhatever

    end class
    Categories: Programming | .Net | VB.Net
    Wednesday, September 06, 2006 4:35:02 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    PostBackUrl And SmartNavigation Bug?#
    I have a page with SmartNav, that contains a linkbutton with a
    PostBackUrl.

    I have found that the page that is the target of the PostBackUrl will
    have it's postback property fired 2 times, and unfortunately, the 2nd
    time it is fired the "PreviousPage" is set to Nothing.

    I have posted a few places to see if someone from MS can confirm this is a bug, but  I am betting they are going to tell me to not use smartnav.

    Categories: Programming | .Net | ASP.Net
    Thursday, August 31, 2006 10:30:38 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Using XSD.exe#

    .Net has a tool called the XML Schema Definition Tool (XSD.EXE) which can turn XSD schemas into classes.  Also, it will try to make it so those classes will conform to the schema when serialized as XML.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpconxmlschemadefinitiontoolxsdexe.asp

    xsd.exe pathToXSD.xsd /classes /language:VB /outputdir:C:\output

    You can then serialize and deserialize the object into/from XML.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlSerializationXmlSerializerClassTopic.asp

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlSerializationXmlSerializerClassDeserializeTopic.asp

     

     

    Categories: Programming | .Net | XML
    Friday, August 25, 2006 3:10:35 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Is The Date On The Weekend#

    This function will figure out if the given date lands on a weekend.

        Public Shared Function IsWeekend(ByVal dateOfInterest As DateTime) As Boolean
    Dim d, m, y, w As Integer
    d = dateOfInterest.Day
    m = dateOfInterest.Month
    y = dateOfInterest.Year


    If m = 1 Or m = 2 Then
    m += 12
    y -= 1
    End If


    w = CInt((d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) Mod 7)
    If w <> 6 And w <> 7 Then
    Return False
    Else
    Return True
    End If
    End Function

    Another function to do the weekend check could be this:

        Private Const ERR_INVALID_DATE = 20000
    Private Const ERR_INVALID_DATE_MSG = "Date Required"

    Public Function IsWeekend(ByVal DateValue As Object) As Boolean

    Dim dDateValue As Date

    If Not IsDate(DateValue) Then
    Err.Raise(ERR_INVALID_DATE, ERR_INVALID_DATE_MSG)
    Exit Function
    End If

    dDateValue = CDate(DateValue)
    IsWeekend = (Weekday(dDateValue) Mod 6 = 1)

    End Function
    Categories: Programming | .Net
    Friday, August 25, 2006 12:33:23 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Using Postbacks in ASP.NET From showModalDialog pages.#

    If you have an ASP.NET page (.aspx) opened with the JavaScript showModalDialog() function and inside that page there is a form doing PostBack, when the PostBack is being done the page loads in another (popup) window. The easiest way to prevent this is to add the following tag inside the <HEAD></HEAD> tags of the ASP.NET page:

    <base target="_self">

    From: http://www.geekpedia.com/Question23_Using-showModalDialog()-with-an-ASP.NET-page-that-does-PostBack-opens-another-window.html

    Categories: Programming | .Net | ASP.Net
    Thursday, August 24, 2006 2:52:59 PM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

     

    Databinding "Bind()" in ASP.NET#

    If you used the developemt tools to create a datagrid in ASP.NET 2.0, it will show something like:

    NavigateUrl='<%# Bind("EmployeeId") %>'

    But what if you wanted to do something more complicated that just ge the EmployeeId into the field, like for example if you wanted to run a JS function.  Then you have to do away with Bind and use the more verbose DataBinder method like this: 

    NavigateUrl='<%# "javascript:UseThisJobIndex(" & DataBinder.Eval(Container.DataItem,"JobIndex") & ")" %>'

    That's all there is to it.

     

    Categories: Programming | .Net | ASP.Net | DataBinding
    Thursday, August 24, 2006 1:16:56 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Throwing the Right Exception#

    Brad Abrams has a good article out there showing a list of all the .net exceptions you can throw from your code.

    There are some exceptions that are not shown here, for example ConfigurationException, but this is a good starting point.

    From Brad's article:

    +--System.Object  

       |

       |

       +--System.Exception  

           |

           |

           +--System.SystemException  

               |

               |

               +--System.ArgumentException  

               |   |

               |   |

               |   +--System.ArgumentNullException  

               |   |

               |   |

               |   +--System.ArgumentOutOfRangeException  

               |   |

               |   |

               |   +--System.DuplicateWaitObjectException  

               |

               |

               +--System.ArithmeticException  

               |   |

               |   |

               |   +--System.DivideByZeroException  

               |   |

               |   |

               |   +--System.OverflowException  

               |   |

               |   |

               |   +--System.NotFiniteNumberException

               |

               |

               +--System.ArrayTypeMismatchException  

               |

               |

               +--System.ExecutionEngineException  

               |

               |

               +--System.FormatException  

               |

               |

               +--System.IndexOutOfRangeException  

               |

               |

               +--System.InvalidCastException  

               |

               |

               +--System.InvalidOperationException  

               |   |

               |   |

               |   +--System.ObjectDisposedException  

               |

               |

               +--System.InvalidProgramException  

               |

               |

               +--System.IO.IOException  

               |   |

               |   |

               |   +--System.IO.DirectoryNotFoundException  

               |   |

               |   |

               |   +--System.IO.EndOfStreamException  

               |   |

               |   |

               |   +--System.IO.FileLoadException  

               |   |

               |   |

               |   +--System.IO.FileNotFoundException  

               |   |

               |   |

               |   +--System.IO.PathTooLongException  

               |

               |

               +--System.NotImplementedException  

               |

               |

               +--System.NotSupportedException  

               |

               |

               +--System.NullReferenceException  

               |

               |

               +--System.OutOfMemoryException  

               |

               |

               +--System.RankException  

               |

               |

               +--System.Security.SecurityException  

               |

               |

               +--System.Security.VerificationException  

               |

               |

               +--System.StackOverflowException  

               |

               |

               +--System.Threading.SynchronizationLockException  

               |

               |

               +--System.Threading.ThreadAbortException  

               |

               |

               +--System.Threading.ThreadStateException  

               |

               |

               +--System.TypeInitializationException  

               |

               |

               +--System.UnauthorizedAccessException 


    Jeff Atwood put up another article where he uses a little console app to find all classes named "*Exception". 


    Here is his list:


    System.AppDomainUnloadedException
    System.ApplicationException
    System.ArgumentException
    System.ArgumentNullException
    System.ArgumentOutOfRangeException
    System.ArithmeticException
    System.ArrayTypeMismatchException
    System.BadImageFormatException
    System.CannotUnloadAppDomainException
    System.ComponentModel.Design.CheckoutException
    System.ComponentModel.Design.Serialization.CodeDomSerializerException
    System.ComponentModel.InvalidEnumArgumentException
    System.ComponentModel.LicenseException
    System.ComponentModel.WarningException
    System.ComponentModel.Win32Exception
    System.Configuration.ConfigurationException
    System.ContextMarshalException
    System.Data.ConstraintException
    System.Data.DataException
    System.Data.DBConcurrencyException
    System.Data.DeletedRowInaccessibleException
    System.Data.DuplicateNameException
    System.Data.EvaluateException
    System.Data.ExprException
    System.Data.InRowChangingEventException
    System.Data.InvalidConstraintException
    System.Data.InvalidExpressionException
    System.Data.MissingPrimaryKeyException
    System.Data.NoNullAllowedException
    System.Data.Odbc.OdbcException
    System.Data.OleDb.OleDbException
    System.Data.ReadOnlyException
    System.Data.RowNotInTableException
    System.Data.SqlClient._ValueException
    System.Data.SqlClient.SqlException
    System.Data.SqlTypes.SqlNullValueException
    System.Data.SqlTypes.SqlTruncateException
    System.Data.SqlTypes.SqlTypeException
    System.Data.StrongTypingException
    System.Data.SyntaxErrorException
    System.Data.TypedDataSetGeneratorException
    System.Data.VersionNotFoundException
    System.DivideByZeroException
    System.DllNotFoundException
    System.Drawing.Printing.InvalidPrinterException
    System.DuplicateWaitObjectException
    System.EntryPointNotFoundException
    System.Exception
    System.ExecutionEngineException
    System.FieldAccessException
    System.FormatException
    System.IndexOutOfRangeException
    System.InvalidCastException
    System.InvalidOperationException
    System.InvalidProgramException
    System.IO.DirectoryNotFoundException
    System.IO.EndOfStreamException
    System.IO.FileLoadException
    System.IO.FileNotFoundException
    System.IO.InternalBufferOverflowException
    System.IO.IOException
    System.IO.IsolatedStorage.IsolatedStorageException
    System.IO.PathTooLongException
    System.Management.ManagementException
    System.MemberAccessException
    System.Messaging.MessageQueueException
    System.MethodAccessException
    System.MissingFieldException
    System.MissingMemberException
    System.MissingMethodException
    System.MulticastNotSupportedException
    System.Net.CookieException
    System.Net.ProtocolViolationException
    System.Net.Sockets.SocketException
    System.Net.WebException
    System.NotFiniteNumberException
    System.NotImplementedException
    System.NotSupportedException
    System.NullReferenceException
    System.ObjectDisposedException
    System.OutOfMemoryException
    System.OverflowException
    System.PlatformNotSupportedException
    System.RankException
    System.Reflection.AmbiguousMatchException
    System.Reflection.CustomAttributeFormatException
    System.Reflection.InvalidFilterCriteriaException
    System.Reflection.ReflectionTypeLoadException
    System.Reflection.TargetException
    System.Reflection.TargetInvocationException
    System.Reflection.TargetParameterCountException
    System.Resources.MissingManifestResourceException
    System.Runtime.InteropServices.COMException
    System.Runtime.InteropServices.ExternalException
    System.Runtime.InteropServices.InvalidComObjectException
    System.Runtime.InteropServices.InvalidOleVariantTypeException
    System.Runtime.InteropServices.MarshalDirectiveException
    System.Runtime.InteropServices.SafeArrayRankMismatchException
    System.Runtime.InteropServices.SafeArrayTypeMismatchException
    System.Runtime.InteropServices.SEHException
    System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
    System.Runtime.Remoting.MetadataServices.SUDSParserException
    System.Runtime.Remoting.RemotingException
    System.Runtime.Remoting.RemotingTimeoutException
    System.Runtime.Remoting.ServerException
    System.Runtime.Serialization.SerializationException
    System.Security.Cryptography.CryptographicException
    System.Security.Cryptography.CryptographicUnexpectedOperationException
    System.Security.Policy.PolicyException
    System.Security.SecurityException
    System.Security.VerificationException
    System.Security.XmlSyntaxException
    System.ServiceProcess.TimeoutException
    System.StackOverflowException
    System.SystemException
    System.Threading.SynchronizationLockException
    System.Threading.ThreadAbortException
    System.Threading.ThreadInterruptedException
    System.Threading.ThreadStateException
    System.Threading.ThreadStopException
    System.TypeInitializationException
    System.TypeLoadException
    System.TypeUnloadedException
    System.UnauthorizedAccessException
    System.UriFormatException
    System.Web.HttpApplication+CancelModuleException
    System.Web.HttpCompileException
    System.Web.HttpException
    System.Web.HttpParseException
    System.Web.HttpRequestValidationException
    System.Web.HttpUnhandledException
    System.Web.Services.Discovery.InvalidContentTypeException
    System.Web.Services.Discovery.InvalidDocumentContentsException
    System.Web.Services.Protocols.SoapException
    System.Web.Services.Protocols.SoapHeaderException
    System.Windows.Forms.AxHost+InvalidActiveXStateException
    System.Xml.Schema.XmlSchemaException
    System.Xml.XmlException
    System.Xml.XPath.XPathException
    System.Xml.Xsl.XsltCompileException


    The code used to create this list (.net 1.1) is:


    Sub Main()
    ReflectionSearch(".*exception$")
    Console.ReadLine()
    End Sub

    Sub ReflectionSearch(ByVal strPattern As String)
    Dim a As Reflection.Assembly
    Dim m As Reflection.Module
    Dim t As Type
    Dim al As New ArrayList
    Dim sl As New SortedList
    Dim strAssemblyName As String

    For Each strAssemblyName In DefaultAssemblyList()
    a = Reflection.Assembly.Load(strAssemblyName)
    For Each m In a.GetModules
    For Each t In m.GetTypes
    al.Add(t)
    Dim strFullName As String = t.FullName
    If Regex.IsMatch(strFullName, strPattern, RegexOptions.IgnoreCase) Then
    sl.Add(strFullName, Nothing)
    End If
    Next
    Next
    Next

    Dim de As DictionaryEntry
    For Each de In sl
    Console.WriteLine(de.Key)
    Next
    Console.WriteLine(sl.Count.ToString & " matches for " & strPattern)
    End Sub

    Function DefaultAssemblyList() as ArrayList
    Dim al As New ArrayList
    With al
    .Add("mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System.Xml, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    .Add("System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.DirectoryServices, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Drawing.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Messaging, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Runtime.Serialization.Formatters.Soap, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Security, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.ServiceProcess, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    .Add("System.Management, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    End With
    Return al
    End Function

    System.Xml.Xsl.XsltException


    Categories: Programming | .Net | .Net Framework | Architecture
    Thursday, August 10, 2006 11:07:53 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Accessing DLLs stored in the GAC#

    You can access the dlls by going to this undocumented folder:

    C:\WINDOWS\ASSEMBLY\GAC_MSIL

    If you go to C:\WINDOWS\ASSEMBLY\ it will not show you the GAC_MSIL folder, but rather a view of all DLLs that you can't copy.

     

    Categories: Programming | .Net | .Net Framework
    Wednesday, August 09, 2006 11:35:34 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    VS.Net Macro for Generating Simple and CSLA Property Accessors#

    Here are a few macros I wrote to generate property accessors from your class level variables.

    These Macros are absolutely not an example of great coding.  They are really pretty crappy, but they do the job, so as I kept tweaking them I never went back to clean up the code or look into more elegant ways to accomplish this stuff.

    Some notes about these macros:

    1) dasBlog's code display tools somehow screws up the LFs, so if you cut and paste this code you might want to first paste it into Word, or WordPad.

    2) These macros need some space between your last bit of code and the end of your class.  In other words, the line directly above "End Class" can't have code in it.  Fixing this bug wouldn't be a big deal but I haven't done it yet.

    3) These macros will allow formatting of your variables/accessors in any of the following ways:

    private csClassLevelString as String '*** property name "ClassLevelString"
    private mModuleLevelInt as Integer '*** property name "ModuleLevelInt"
    private _SomeObject as Object '*** property name "SomeObject"
    private camelCaseBoolean as Boolean '*** WON'T work: property will be named "CaseBoolean"

    4) To use these macros, simply declare your class level (instance) variables.  Then with your mouse, highlight the ones you want to create property accessors for.  You need to highlight the entire definition from "private" to data type, and of course you can highlight a bunch at 1 time.  i.e. I could highlight the entire code block above and it would produce 4 property accessors.

    5) Again... this code... well it kinda sucks.  So if you are looking for a lesson on producing good code, avert your eyes, but the output is good.

     

    Imports System
    Imports EnvDTE
    Imports EnvDTE80
    Imports System.Diagnostics

    Public Module Module1

        Public Sub AddClassProperties()
            Call AddClassProperties(False)
        End Sub
        Public Sub AddCslaProperties()
            Call AddClassProperties(True)
        End Sub

        ' highlight the private properties
        Private Sub AddClassProperties(ByVal useCsla As Boolean)

            Dim oTextSelection As TextSelection = DTE.ActiveWindow.Selection
            Dim iLinesSelected = oTextSelection.TextRanges.Count
            Dim colPropertyList As New Collection()
            Dim iIndex As Integer
            Dim oStart As EditPoint = oTextSelection.TopPoint.CreateEditPoint()
            Dim oEnd As TextPoint = oTextSelection.BottomPoint

            'Create an Undo context object so all the changes can be
            'undone by CTRL+Z
            Dim oUnDo As UndoContext = DTE.UndoContext

            'Supress the User Interface. This will make it run faster
            'and make all the changes appear once
            DTE.SuppressUI = True

            Try

                oUnDo.Open("Comment Line")

                Dim sProperty As String
                Dim sLineOfText As String

                Do While (oStart.LessThan(oEnd))

                    sLineOfText = oStart.GetText(oStart.LineLength).Trim
                    '*** do some kind of simple check to make sure that this line
                    '*** isn't blank and isn't some other kind of code or comment
                    If (sLineOfText.IndexOf(" As ") >= 0 And ( _
                        (sLineOfText.IndexOf("Public ") >= 0) Or _
                        (sLineOfText.IndexOf("Private ") >= 0) Or _
                        (sLineOfText.IndexOf("Dim ") >= 0) Or _
                        (sLineOfText.IndexOf("Protected ") >= 0) Or _
                        (sLineOfText.IndexOf("Friend ") >= 0) Or _
                        (sLineOfText.IndexOf("ReDim ") >= 0) Or _
                        (sLineOfText.IndexOf("Shared ") >= 0) Or _
                        (sLineOfText.IndexOf("Static ") >= 0) _
                        )) Then

                        sProperty = oStart.GetText(oStart.LineLength).Trim.Replace(" New ", " ").Replace("()", "")

                        colPropertyList.Add(sProperty)
                    End If

                    oStart.LineDown()
                    oStart.StartOfLine()

                Loop

                If colPropertyList.Count > 0 Then

                    For Each sProperty In colPropertyList
                        Call InsertProperty(sProperty, useCsla)
                    Next

                Else
                    MsgBox("You must select the class properties")
                End If

            Catch ex As System.Exception

                Debug.WriteLine(ex)
                If MsgBoxResult.Yes = MsgBox("Error: " & ex.ToString & vbCrLf & "Undo Changes?", MsgBoxStyle.YesNo) Then
                    oUnDo.SetAborted()
                End If

                Return
            Finally

                'If an error occured, then need to make sure that the undo context is cleaned up.
                'Otherwise, the editor can be left in a perpetual undo context
                If oUnDo.IsOpen Then
                    oUnDo.Close()
                End If

                DTE.SuppressUI = False
            End Try


        End Sub

        Private Sub InsertProperty(ByVal sProp As String, Optional ByVal UseCsla As Boolean = False)
            Dim oTextSelection As TextSelection = DTE.ActiveWindow.Selection
            Dim sMember As String = sProp.Substring(sProp.IndexOf(" ")).Trim
            Dim sDataType As String
            Dim sName As String
            Dim i As Integer
            Dim iAscVal As Integer

            i = sMember.IndexOf("(")
            If Not i = -1 Then
                sMember = sMember.Substring(0, i)
            End If

            i = sMember.IndexOf("=")
            If Not i = -1 Then
                sMember = sMember.Substring(0, i)
            End If

            sDataType = sMember.Substring(sMember.IndexOf(" As ") + 1)

            For i = 0 To sMember.Length - 1
                'iAscVal = Asc(Mid(sName, i, 1))
                iAscVal = Asc(sMember.Chars(i))
                If iAscVal > 64 And iAscVal < 91 Then
                    sName = sMember.Substring(i)
                    Exit For
                End If
            Next i

            sName = sName.Substring(0, sName.IndexOf(" As ") + 1).Trim

            If sName.Length = 0 Then
                MsgBox("Unable to process the class property: " & sMember & ".  This is usually caused by an incorrect naming convention (e.g. not cxName)")
                Return
            End If

            sMember = sMember.Substring(0, sMember.Length - sDataType.Length).Trim

            With oTextSelection
                Dim pt As TextPoint = .ActivePoint.CodeElement(vsCMElement.vsCMElementClass).GetEndPoint(vsCMPart.vsCMPartWhole)
                If pt Is Nothing Then
                    pt = .ActivePoint.CodeElement(vsCMElement.vsCMElementStruct).GetEndPoint(vsCMPart.vsCMPartWhole)
                End If
                .MoveToPoint(pt)
                .LineUp()
                .EndOfLine()

                .Text = "Public Property " & sName & "() " & sDataType
                .NewLine()
                If UseCsla Then
                    .Text = "CanReadProperty(True)"
                    .NewLine()
                End If
                .Text = "Return " & sMember
                .StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText)
                .StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, True)
                .Copy()
                .LineDown(False, 3)
                DTE.ExecuteCommand("Edit.Paste")
                If UseCsla Then
                    .Text = "CanWriteProperty(True)"
                    .NewLine()
                    .Text = "If Me." & sMember & " <> Value then"
                    .NewLine()
                End If
                .Text = "Me." & sMember & " = Value"
                If UseCsla Then
                    .NewLine()
                    .Text = "PropertyHasChanged()"
                End If
                .LineDown(False, 2)
                If UseCsla Then
                    .LineDown(False, 1)

                End If
                .NewLine(2)

            End With

        End Sub


    End Module

     

     

    Categories: Code | Programming | .Net | VB.Net
    Thursday, August 03, 2006 7:51:08 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Select DataSource and Visual Studio Errors#

    I recently ran into a nebulous problem when creating a windows app with vs.net 2005.

    I would select the DataBindings or DataSource properties from the proeprties window (click the dropdown) and VS would give me an "Object reference not set to an instance of an object" error.

    Fantastic!

    I finally figured out the problem was caused by a recent rename of a misspelled class.

    This class was being used by one of the datasources.  As soon as I changed the name of that class, the datasource became invalid, and I guess when VS tries to get a list of the these datasources for the dropdown it just blows up.

    Once I deleted the problematic datasource everything went back to normal.

    Categories: Programming | .Net | VS.Net | WinForms
    Tuesday, August 01, 2006 9:25:40 PM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

     

    Expresso Regular Expression Tool#

    Expresso is a free tool that you can download and run to aid you in building and testing regular expressions.

    It's pretty handy!

    Categories: Programming | .Net | .Net Framework | Utilities
    Monday, July 31, 2006 10:19:54 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Validating XML document against an XML Schema with VB.Net#

    It seems like validating an XML document against a schema would be a pretty simple thing to do in the .Net framework, seeing as how they have such deep support for dealing with XML.

    But as of yet, I haven't found a simple way to do it.

    Here is the code I have been using to validate XML against an XML Schema.

    Imports System.IO
    Imports System.Xml
    Imports System.Xml.Schema


    Private schemaValidation As New ValidationEventHandler(AddressOf ValidationHandler)

    Private Function ValidateXml(ByVal xmlFileName As String, ByVal xmlSchemaName As String) As Boolean
    Using myFile As New FileStream(xmlFileName, FileMode.Open, FileAccess.Read, FileShare.None)
    Dim xDoc As New Xml.XmlDocument()
    xDoc.Load(myFile)
    xDoc.Schemas.Add(GetSchema(xmlSchemaName))
    Try
    xDoc.Validate(schemaValidation)
    Return True
    Catch ex As XmlSchemaValidationException
    Console.Write(ex.ToString)
    Return False
    Catch ex As XmlSchemaException
    Console.Write(ex.ToString)
    Return False
    Catch ex As Exception
    Console.Write(ex.ToString)
    Return False
    End Try
    End Using
    End Function

    Private Function GetSchema(ByVal filePath As String) As XmlSchema
    Dim schema As XmlSchema
    Using s As New System.IO.FileStream(filePath, FileMode.Open)
    Using reader As New StreamReader(s)
    schema = XmlSchema.Read(reader, Nothing)
    End Using
    End Using
    Return schema
    End Function

    Private Sub ValidationHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    Throw e.Exception
    End Sub
     
    Categories: Programming | .Net | .Net Framework | VB.Net | XML
    Saturday, July 29, 2006 4:35:25 PM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

     

    CSLA Contrib #

    CSLA Contrib is supposed to be a community for sharing CSLA tools, templates, and ideas.

    http://www.codeplex.com/Wiki/View.aspx?ProjectName=CSLAcontrib

    Worth checking out.

    Categories: Programming | .Net
    Sunday, July 23, 2006 12:48:39 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Here Is A Article Talking About The Ability To Put Some Of Your Config Info In Another Config File When Using Aspnet#

    Here is a article talking about the ability to put some of your .config info in another config file when using asp.net

    http://www.beansoftware.com/ASP.NET-Tutorials/Multiple-Config.aspx

    What I found most interesting is that it says that changing the otherFile.config will not reset your app.

    I am guessing that it also means that it won't find your new values until the app is reloaded, but if it DID find the new values w/o a reload that would be great.

    <?xml version="1.0"?>
    <configuration>
        <appSettings/>
        <connectionStrings/>
        <system.web>
            <compilation debug="false" strict="false" explicit="true" />
        </system.web>
        <appSettings file="externalSettings.config"/>
    </configuration>

    I also wonder if you could have more than 1 appSettings external file.

    Categories: Programming | .Net | ASP.Net
    Thursday, July 20, 2006 3:52:58 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Sorting a generic List(Of T) using IComparable(Of T) #

    List(Of T) supports sorting through it's Sort method.  When you call Sort it will use the default comparer for the items it contans.  So if you have a custom class in there, you need to implement IComparable or IComparable(Of T). 

    Here is some code that shows how to do this.  This code sorts lowest to highest.

        Public Function CompareTo(ByVal other As CustomClass) As Integer Implements System.IComparable(Of CustomClass).CompareTo
    Dim myscore As Integer = Me.SomeValue
    Dim otherscore As Integer = other.SomeValue
    If myscore > otherscore Then
    Return 1
    ElseIf myscore = otherscore Then
    Return 0
    Else
    Return -1
    End If
    End Function
    Categories: Programming | .Net | VB.Net
    Sunday, July 16, 2006 3:15:15 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    IBiz Quickbooks Integrator#

    nSoftware just released a product called IBiz Integrator for Quickbooks, which is supposed to enable one to integrate their applicaiton with Quickbooks via QBXML.

    A comprehensive suite of Internet-enabled components for QuickBooks (QBXML) Integration. Includes easy-to-use components for accessing QuickBooks constructs and automating accounting tasks.

    Should be work looking into for QB applications.

    Categories: Programming | .Net | Tools
    Friday, July 07, 2006 11:44:48 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    XSL Transformations in .NET 2.0#

    I found this article that talks about some of the classes used in the .net framework v2.0 when doing XSLT.

    http://www.15seconds.com/issue/060608.htm

    I am taking a course on XML / XSLT at UofC that I am planning on doing in .Net.  I have written xml schamas xml stylesheets and xml transforms before, but not using .net 2.0, so it should be interesting.

    Categories: Programming | .Net | .Net Framework | University of Chicago
    Monday, June 26, 2006 1:12:49 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Exceptions in .Net#

    I found this snippet on another site, and it looks like it comes from the book I just bought about building frameworks from the guys that worked on the .net framework.

  • DO report execution failures by throwing exceptions.
  • CONSIDER terminating the process by calling System.Environment.FailFast (.NET 2.0) instead of throwing an exception, if your code reaches a situation where you consider it unsafe for further execution.
  • DO NOT use exceptions for the normal flow of control, if possible.
  • CONSIDER the performance implications of throwing exceptions.
  • DO document all exceptions thrown by publicly callable members because of a violation of the member contract and treat them as part of your contract.
  • DO NOT have public members that can either throw or not based on some option such as a bool parameter (.e.g., bool throwOnError)
  • DO NOT have public members that return exceptions as the return value or as an out parameter.
  • CONSIDER using exception builder methods.
  • DO NOT throw exceptions from exception filter blocks
  • AVOID explicitly throwing exceptions from finally blocks.
  • DO throw the most specific (the most derived) exception that makes sense.
  • DO NOT swallow errors by catching nonspecifc exceptions ( e.g., catch (Exception e) { } // swallowed whole!)
  • CONSIDER catching a specific exception when you understand why it was thrown in a given context and you can respond to the failure programmatically.
  • DO Clean up any side effects when throwing an exception. For example, if a Hashtable.Insert method throws an exception, the caller can assume that the specified item was not added to the Hashtable.
  • DO NOT derive all new exceptions directly from the base class SystemException. Inherit from SystemException only when creating new exceptions in System namespaces. Inherit from ApplicationException when creating new exceptions in other namespaces.
  • DO use the predefined exceptions types. Define new exception types only for programmatic scenarios.
  • DO NOT overcatch. Exceptions should often simply be allowed to propagate up the call stack.
  • DO prefer using an empty throw when catching and rethrowing an exception. This is the best way to preserve the exception call stack.
  • AVOID creating custom exception classes when there is already an exception type that's "good enough".
  • DO Design classes so that in the normal course of use an exception will never be thrown.
  • DO NOT return Error Codes!
  • Categories: Programming | .Net | .Net Framework
    Wednesday, June 21, 2006 1:52:51 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Printing a VB.Net Form#

    I found this useful code at VB-Helper.com

     

    #Region "Print"
        Private Declare Auto Function BitBlt Lib "gdi32.dll" (ByVal _
        hdcDest As IntPtr, ByVal nXDest As Integer, ByVal _
        nYDest As Integer, ByVal nWidth As Integer, ByVal _
        nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc _
        As Integer, ByVal nYSrc As Integer, ByVal dwRop As _
        System.Int32) As Boolean
        Private Const SRCCOPY As Integer = &HCC0020
    
        ' Variables used to print.
        Private m_PrintBitmap As Bitmap
        Private WithEvents m_PrintDocument As Printing.PrintDocument
    
        Private Sub PrintForm()
            ' Copy the form's image into a bitmap.
            m_PrintBitmap = GetFormImage()
    
            ' Make a PrintDocument and print.
            MsgBox(m_PrintDocument.PrinterSettings.PrinterName)
            m_PrintDocument = New PrintDocument
            m_PrintDocument.Print()
        End Sub
    
        Private Function GetFormImage() As Bitmap
            ' Get this form's Graphics object.
            Dim me_gr As Graphics = Me.CreateGraphics
    
            ' Make a Bitmap to hold the image.
            Dim bm As New Bitmap(Me.ClientSize.Width, _
                Me.ClientSize.Height, me_gr)
            Dim bm_gr As Graphics = Graphics.FromImage(bm)
            Dim bm_hdc As IntPtr = bm_gr.GetHdc
    
            ' Get the form's hDC. We must do this after 
            ' creating the new Bitmap, which uses me_gr.
            Dim me_hdc As IntPtr = me_gr.GetHdc
    
            ' BitBlt the form's image onto the Bitmap.
            BitBlt(bm_hdc, 0, 0, Me.ClientSize.Width, _
                Me.ClientSize.Height, _
                me_hdc, 0, 0, SRCCOPY)
            me_gr.ReleaseHdc(me_hdc)
            bm_gr.ReleaseHdc(bm_hdc)
    
            ' Return the result.
            Return bm
        End Function
    
        ' Print the form image.
        Private Sub m_PrintDocument_PrintPage(ByVal sender As _
            Object, ByVal e As _
            System.Drawing.Printing.PrintPageEventArgs) Handles _
            m_PrintDocument.PrintPage
            ' Draw the image centered.
            Dim x As Integer = e.MarginBounds.X + _
                (e.MarginBounds.Width - m_PrintBitmap.Width) \ 2
            Dim y As Integer = e.MarginBounds.Y + _
                (e.MarginBounds.Height - m_PrintBitmap.Height) \ 2
            e.Graphics.DrawImage(m_PrintBitmap, x, y)
    
            ' There's only one page.
            e.HasMorePages = False
        End Sub
    
    #End Region
    Categories: Programming | .Net | VB.Net
    Wednesday, June 14, 2006 11:49:10 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    MSDN Wiki#
    This is pretty cool:
     
     
    People can now add their own comments, suggestions, etc to the MSDN documentation.

    Categories: Programming | .Net | References
    Friday, June 09, 2006 10:16:09 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Problems moving from System.Web.Mail to System.Net.Mail#

    I recently went through the painful process of updating all our codebase to remove all warning messages after our "successful" convesion from .net 1.1 to 2.0.

    After I made all the adjustments to remove all warnings, all seemd to be well.  In fact, it was going to well, as this morning I relized that I hadn't seen an exception report come through my email in a week.

    Sure enough, I went into the database where I log everything and found exceptions that were not being emailed to our development team.

    The exceptions that were being thrown when we tried to email were stuff like this:

    Email address problemsError sending Error Report: Message: The specified string is not in the form required for an e-mail address.
    Stack:   at System.Net.Mime.MailBnfHelper.ReadMailAddress(String data, Int32& offset, String& displayName)
       at System.Net.Mime.MailBnfHelper.ReadMailAddress(String data, Int32& offset)
       at System.Net.Mail.MailAddressCollection.ParseValue(String addresses)
       at System.Net.Mail.MailAddressCollection.Add(String addresses)
       at System.Net.Mail.Message..ctor(String from, String to)
       at System.Net.Mail.MailMessage..ctor(String from, String to)
       at System.Net.Mail.MailMessage..ctor(String from, String to, String subject, String body)
       at Walshgroup.Logging.ApplicationAudit.EmailErrorToDevelopmentTeam(String sErrorMessage, Int32 iLoginID) in x.vb:line 586 on machine y

    Subject problemsError sending Error Report: Message: The specified string is not in the form required for a subject.
    Stack:   at System.Net.Mail.Message.set_Subject(String value)
       at System.Net.Mail.MailMessage..ctor(String from, String to, String subject, String body)
       at Walshgroup.Logging.ApplicationAudit.EmailErrorToDevelopmentTeam(String sErrorMessage, Int32 iLoginID) in C:\x.vb:line 586 on machine y

    It turns out that we were doing 2 things that System.Web.Mail seemed to accept, but System.Net.Mail did not.

    Email Address: We were using the MS Outlook way of email concatenation (using a semicolon) to send an email to multiple people (e.g. bill@asdf.com;jack@asdf.com;pete@asdf.com).  Once I changed it to use commas, everything worked, but we still had errors related to the subject line.

    What we were doing for the subject line was simply to take the first 50 characters of the email error message.  In this case, this included some CRLF.  Once those were removed the email sent w/o a problem.

    For more info on these classes check out http://www.systemwebmail.com/ and http://www.systemnetmail.com/.

    Categories: Networking | Email | Programming | .Net | .Net Framework
    Thursday, June 01, 2006 4:33:55 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Activate Flash, Movies, and other ActiveX controls#

    Recently Microsoft lost a patent judgement, which resulted in them pushing down an "update" to IE that forces you to click on any embedded object to "activate" it.

    Embedded objects can be flash movies, video clips, audio, etc.

    This is really bad for sites that use flash.  Things like navigation and rollovers don't work until you first click on them.

    This article talks about the work around, and how you can incorporate this into your ASP.NET projects.

    http://www.codeproject.com/aspnet/IEActiveXActivation.asp