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]  | 

 

jQuery Easing Demos#

This page has a quick demo of all the easing methods in the jQuery Easing plugin:  http://www.commadot.com/jquery/easing.php

Pretty cool.  Just click on any of the boxes to see the easing action.

Categories: Programming | Javascript
Tuesday, January 05, 2010 9:49:01 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Where is the jQuery Effects Core effects.core.js #

I was trying to use some jQuery effects on this page:

http://docs.jquery.com/UI/Effects

And none of them were working.  After a while, I realized it was because I didn't have the "jQuery Effects Core" or as they list it on that page: effects.core.js

Turns out you need to download it as part of the UI package here: http://jqueryui.com/download

Categories: Programming | Javascript
Tuesday, January 05, 2010 9:31:22 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Removing all extended properties from SQL Server#

About a year ago, we tried using a tool to get our SQL schema into a souce control system.  It was supposed to work like this: every night the process would run and checkin each object as a file into TFS. 

Well, aside from not working, it also added Extended Properties to all our objects in SQL Server. 

Not really a big deal, except when we would run our database comparison tools between production and development these would cause it so that almost everything would appear out of sync.

I ended up writing my own service to check in all our SQL objects into TFS, but we were left with all these Extended Properties all over the place. 

So I finally got around to cleaning them up using the script below:

select 'EXEC sp_dropextendedproperty 
@name = ''' + sys.extended_properties.name + ''' 
,@level0type = ''schema'' 
,@level0name = ' + object_schema_name(extended_properties.major_id) + '
,@level1type = ''' + 
    CASE WHEN  
        xtype = 'U' THEN 'table'
        WHEN 
        xtype = 'FN' THEN 'function'
        WHEN 
        xtype = 'V' THEN 'view'
        WHEN 
        xtype = 'P' THEN 'procedure' end
    + '''
,@level1name = ''' + object_name(extended_properties.major_id) + ''''
from sys.extended_properties
INNER JOIN sysobjects ON sys.extended_properties.major_id  = sysobjects.id
where extended_properties.class_desc = 'OBJECT_OR_COLUMN'
and extended_properties.minor_id = 0
and extended_properties.name like 'VSS%'

This script will produce a record set that you can copy and paste into another query window to run to clean out all the extended properties. 

Note: all the generated extended properties that this tool created on our DB started with "VSS" so that is why I have that extra item in my where clause.  You'll probably want to remove that.

Categories: Programming | Database | SQL Server
Friday, December 11, 2009 11:27:26 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]  | 

 

Visual Studio type fly out windows in HTML#

I've been working on a project where I wanted to have a flyout window on the left just like how Visual Studio does their menus.

Maybe "slide out" is more accurate.

I used jQuery, which I am trying to use more in my projects, for the effects.

Anyway, I ended up making it a bit harder than it needed to be by having the tab itself slide out, as well as allow for multiple tabs.

At this point I'm happy enough to move on with a successful proof of concept, but I think if I were doing this from scratch again I wouldn't bother having the tab slide out as well.  I'd just show the sliding out window.

But, this should be a good starting point.

visualstudioflyoutmenus.htm (17.7 KB)

Update: And of course it completely fails in FF.

I made some changes, removed some things, tweaked others... looks ok in FF now.

visualstudioflyoutmenus2.htm (17.7 KB)

Categories: Programming | HTML | Javascript
Thursday, October 29, 2009 12:16:37 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Performing a recursive wildcard delete in TFS#

Because I didn't like the options for integrating SQL Server code into TFS, I wrote an application that scripts all our database objects to text files and then checks those files into TFS every night.  If there is a change in any of the files, those changes are versioned in TFS so we can go back and see when things were changed or recover old code without restoring the entire database.

But recently there was a problem with the server that my app runs on, and during the restore process, the backup process was run twice on a set of folders (at least that is my best guess) leaving thousands of duplciate files in a myriad of folders.

So for example, if there was a file called:

$\DatabaseFiles\sqlserver1\SomeDBName\SPs\dbo.SomeSP.sql

then the restore process created another file called

$\DatabaseFiles\sqlserver1\SomeDBName\SPs\Copy of dbo.SomeSP.sql

The problem is that my application does bulk checkins each night of all files under the \DatabaseFiles folder.  I didn't realize that the backup process had been messed up until it was too late, and those thousands of files were already checked into TFS.

So using this page to help with some of the syntax of using the TF.EXE command line too, I was able to perform a recursive wildcard delete.

In the end something like this worked just great:

tf.exe delete /recursive /noprompt "C:\TFSroot\DatabaseFiles\Copy of*"

Notice that the wildcard is applied to all recursive folders under C:\TFSroot\DatabaseFiles\.

Nice.

 

Categories: Programming | TFS
Monday, September 28, 2009 10:13:47 AM (Central Daylight Time, UTC-05: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]  | 

 

SQL NOT IN and NULL still will not work#

Last night I had another instance where doing a:

SELECT * FROM
TBL WHERE ID NOT IN (SELECT ID FROM TBL2)

would fail every time to return any rows.

After longer than it should have been, I realized that it was this stupid issue that I blogged about already (SQL "NOT IN" Will Fail If The List Contains A Null).

 

Categories: Misc | Programming | Database | SQL Server | T-Sql
Thursday, August 13, 2009 1:07:10 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Debugging SQL Server Deadlock Issues#
Categories: Programming | Database | SQL Server
Friday, July 10, 2009 3:09:10 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

SSIS FTP Error#

Connection can not be established.  Server name, port number, or credentials may be invalid.

I just got that message when trying to enter a perfectly valid set of connection/credential info into an SSIS package.  But testing the connection failed.

Turns out my issue, and maybe your issue too, is that SSIS doesn't remove white space from the server name textbox.  So if you pasted in the name of the FTP server, as I did, you might have fallen victim to the "trailing space" that is frequently copied with your text, and instead of trying to connect to "ftp.com" it tried to connect to "ftp.com " notice the extra space.

Categories: Programming
Friday, May 22, 2009 4:41:28 PM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

 

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]  | 

 

Finding if SP Parameters are Nullable#

I'm working on something where I wanted to know if some parameters to a SQL Server Stored Procedure were nullable (or, in otherwords, if they had a default value).

The API I was working with provided a way to find info about the SP, but the isNullable value was never accurate.

I tried working with with the MS DAABs which have a way to fetch SP parameter info, but this method also produced faulty information.

Looking into the code of the DAAB, it was internally calling:

Dim command As SqlCommand

SqlCommandBuilder.DeriveParameters(command)

Somewhere I came across some code for the DeriveParameters method (I think from the Mono project maybe?) which showed it calling this system SP:

sp_procedure_params_rowset

Which returns output fields,:

PARAMETER_HASDEFAULT

IS_NULLABLE

But, again, neither of these appear correctly.

However, I finally came across this thread where a MSFT poster indicates that this data is simply not available:

http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/900756fd-3980-48e3-ae59-a15d7fc15b4c/

Instead, you need to parse the SP definition to see what the default parameter value is, which is a pain, but at least I know why these other methods kept not working.

 

Categories: Programming | Database | SQL Server | T-Sql
Saturday, April 25, 2009 10:55:55 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Avoid Overwriting Modified SPs With Code Generation#

One of the challenges of using code generation is to avoid overwriting your custom changes when you re-generate the code later.

This is a trick I am using to avoid overwriting my stored procedures if I update them manually.  The trick is to include a comment indicating that the SP has been code generated, and then to remove that comment if you update the SP.  So lets say that you generate:

CREATE PROCEDURE OrderDetails_Get
@OrderId as int
AS
-- CODE GENERATED
SELECT * FROM
OrderDetails
WHERE
OrderId = @OrderId

and you made some customizations to the SP so it now looks like this:

CREATE PROCEDURE OrderDetails_Get
@OrderId as int
AS
SELECT * FROM
OrderDetails
INNER JOIN
Orders ON
Orders.OrderId = OrderDetails.OrderId
WHERE
OrderId = @OrderId

The following code will help you when generating your SPs to avoid overwriting this change:

IF EXISTS(
  SELECT [definition] AS objectText 
  FROM sys.sql_modules 
  WHERE [object_id] = OBJECT_ID(N'OrderDetails_Get', 'P') 
  AND definition LIKE '%CODE GENERATED%')
BEGIN
   -- overwrite is ok
END

 

Categories: Programming | Database | SQL Server | T-Sql
Saturday, April 18, 2009 9:37:55 AM (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]  | 

 

SQL Reports RDLC Errors#

Ever get this error?

More than one data set, data region, or grouping in the report has 
the name 'SOMENAME'.  Data set, data region, and grouping names
must be unique within a report. 

Basically what happened was, somehow VS lost track of an existing datasource you were using, why I don't know. When you went to add a new field or change something it added a 2nd copy of the same datasource, and now you have 2 datasources with same name. You can't do that. To fix this, when you are editing the report, choose Report --> Data Sources from the menu and remove one of the duplicate datasource names.

In a related error, you may notice that you can't use some fields that are part of your dataset.  For example, in my app, I had a field called "CreatedDate".  This was a public property of my object, and it showed up in my data source that I was using to bind to the report, but the report refused to acknowledge it.

So in this case you need to delete the original datasource using the same steps as above, and do something to cause it to add a new copy of the correct datasource (like drag a field onto the report).

Categories: Programming | Reporting
Sunday, March 22, 2009 4:32:16 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Getting Started With OpenSTA#

I have been looking around for a quick easy load testing package.  Right now I'm trying out OpenSTA.  I can't say that it has been very direct, but I am still holding out hope that it will work.

This is the Getting Started Guide that I have been using.

Categories: Misc | Programming | Testing
Monday, March 16, 2009 1:19:16 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]  | 

 

SQL Server encountered error 0x80070422 (FIXED)#

Today we started getting this error when trying to do full text search with SQL Server 2008.

Msg 30046, Level 16, State 1, Procedure CodeMaster_GetCostCodesByCriteria_FullText, Line 47

SQL Server encountered error 0x80070422 while communicating with full-text filter daemon host (FDHost) process. Make sure that the FDHost process is running. To re-start the FDHost process, run the sp_fulltext_service 'restart_all_fdhosts' command or restart the SQL Server instance.

Google has NOTHING on this problem, except 1 other guy reporting it to MS, who tells him to go to some other forum.

Great.

If I find anything I will post it.

UPDATE:

Ok I figured this out.

The problem was that the actual FTS service was disabled (but not just that, so read on).

So go into your services and make sure that this one is running:

SQL Full-text Filter Daemon Launcher (MSSQLSERVER)

But even after I set this up running things weren't working.  More research led me to find out that there was an issue with the fact that we run our SQL Server under a domain account and the full text search was not running as that same user.

So I configured this service to run as the same user and restarted the service.

Then in SQL Server I ran this:

EXEC sp_fulltext_service 'restart_all_fdhosts'

to restart things.

I also right clicked on the FTS catalog (under databasename/Storage/Full Text Catalog), picked properties, and then selected the option to rebuild catalog.

 

Categories: Programming | Database | SQL Server
Thursday, February 26, 2009 3:51:10 PM (Central Standard Time, UTC-06:00) #    Comments [2]  | 

 

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]  | 

 

Checking and Updating Identity Seed in SQL Server#

If you want to check and update the identity on tables in SQL Server, you can use the following code:

select ident_current('tablename') as ident
dbcc checkident('tablename',RESEED,100)
select ident_current('tablename') as newident

 

Categories: Programming | Database | SQL Server | T-Sql
Thursday, January 29, 2009 9:13:29 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Performing a Baseless Merge in TFS#

If you create a branch in TFS, you can easily merge it back later, but if you have 2 branches or folders that you want to merge, but are not related (they weren't branched from one another) you need to do a baseless merge.

This article describes the process:

http://msdn.microsoft.com/en-us/library/bb668976.aspx

But the short end of it is that you run the following command at the VS command prompt:

tf merge /baseless c:\source c:\dest /recursive

It will launch the dialog box for you to manage the merge from there.

Categories: Programming | TFS
Tuesday, January 20, 2009 5:00:29 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]  | 

 

Deleting Projects From TFS#

For some reason the TFS Team Explorer UI doesn't give you the ability to delete team projects.

To do this you need to make use of the TfsDeleteProject command line utility.

Basically just navigate to:

C:\Program Files\Microsoft Visual Studio 8\Common7\IDE

and run the command:

TfsDeleteProject /server:http://SERVERNAME:8080 PROJECTNAME

After you do this, you may need to run the "TfsVersionControl Administration Job" job on the machine running SQL for TFS.  It's under SQL Agent/Jobs.

Finally, the team projects will continue to show up in Source Control Explorer.  This is because you need to do a "GET" on the projects in order for them to clean up local files.  Once you do a get on the projects they will be gone from your workspace list.

Categories: Programming | TFS
Wednesday, November 05, 2008 1:18:22 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]  | 

 

SQL Reporting Services Subscription Ownership#

We utilize data driven subscriptions in SQL Server Reporting Services (SSRS) to automate several reports and their distribution to a group of people.  For example maybe when a work order is created in the database a report with info about that order is emailed to everyone who will have to be involved in fulfiling the order. 

We realized that some of these reports were not going out.  By looking at the log files (located at ) it became clear that we were hitting a permissions issue:

ReportingServicesService!library!4!09/25/2008-08:15:04:: 
e ERROR: Throwing Microsoft.ReportingServices.Diagnostics.Utilities.AccessDeniedException:
The permissions granted to user 'MYDOMAIN\someuser' are insufficient for performing this operation., ; Info: Microsoft.ReportingServices.Diagnostics.Utilities.AccessDeniedException:
The permissions granted to user 'MYDOMAIN\someuser' are insufficient for performing this operation.

Ok that seemed to make sense.  The user "someuser" had left our company and so I'm sure his account was disabled.  After looking around at the report, it's definition, the subscriptions, the data access, nothing was tied to this old employee. 

But.... the subscription itself still is.

The downside of this is that there is no way to change who "owns" the subscription.

However, you can make the changes manually in the database with the following code:

DECLARE @OldUserID uniqueidentifier
DECLARE @NewUserID uniqueidentifier 

SELECT @OldUserID = UserID FROM dbo.Users 
WHERE UserName = 'MYDOMAIN\someuser'

SELECT @NewUserID = UserID FROM dbo.Users 
WHERE UserName = 'MYDOMAIN\newuserhere'

UPDATE dbo.Subscriptions 
SET OwnerID = @NewUserID 
WHERE OwnerID = @OldUserID
Presto, your subscription has a new owner and will once again start running correctly.

UPDATE: I am going to try to work on something that will monitor the subscriptions and notify me if one of them fail.  Check back later.

Categories: Programming | Database | SQL Server
Tuesday, September 30, 2008 3:52:04 PM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

 

Displaying Chart Data With CSS#

Here is a great article about some of the techniques for displaying chart data using CSS.

Examples: http://apples-to-oranges.com/goodies/css-for-bar-graphs/

Categories: Programming | HTML
Sunday, September 21, 2008 7:37:59 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]  | 

 

10 ways to build websites faster#

This is a great article on 10 ways to build websites faster.

They include the obvious ones like using a menu generator, but they also include some cool things like a site from Adobe for selecting color schemes.

Categories: Programming | HTML
Thursday, August 21, 2008 5:04:42 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]  | 

 

10 Concepts You Need To Know As A Developer#

This article: 10 Concepts Every Software Engineer Should Know, is worth taking a look at if you are a developer.

I thought about it for a minute, trying to think of something important that they didn't touch on in this article, and I think the only major thing I would argue for would be entity relationship diagramming: the ability to turn a problem domain into a set of entities and relationships.

Other topics I would have considered: Regular Expressions, code documentation, project estimation, and maybe unit testing.

Categories: Programming
Wednesday, July 23, 2008 2:12:56 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]  | 

 

Deploying Database Development#

Simple-talk.com has a pretty in depth article about deployment and mangement of databases.

Rolling out changes to the application is only 1 part of a deployment.  Updating the database can be more difficult depending on your schema.

We could have more process around the DB development and deployment process.  I will be giving this a read shortly.

Categories: Programming | Database
Wednesday, June 25, 2008 10:34:46 AM (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]  | 

 

Why Do SSRS Deployments Not Update Everything?#

Recently I have been making some changes to our SQL Server Reporting Services machines.  I am finding that many of my changes are not taking effect on the server.

The deployment goes ok.  The reports show that they have been updated, but some things seem to not transfer.

For example, I changed the data source on some reports and redeployed them, but this new setting did not make it to the server.  If I delete the report and THEN deploy it, it works fine.

Another issue was with some reports where I was trying to change some of the parameters to take a default null value.  I made the changes in my reports and deployed.  The reports now ALLOWED a null value, but they were not setup for the null to be the default value. 

Once again deleting the report and deploying fixed the problem, but this is stupid.

Has anyone else had this problem, or have know of the reason why it doesn't work right?

UPDATE:

I got a response from someone on this.  Apprently Microsoft felt that certain changers like changing report parameter details, could cause existing report parameter settings to be overwritten (well duh) and you as a developer probably didn't realize what you were doing (hmmm yes I did) and so they don't update everyone on the server when you redeploy a report.

Brilliant!  No warning, no message, just some things are not updated.

Categories: Programming | Reporting
Wednesday, May 28, 2008 2:34:51 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Rolling back changes on Team Foundation Server#

Once in a while someone checks in some file they didn't want checked in.

You can roll back these changes/checkins by using the Team Foundation Server Power Toy.

Team Foundation Server Power Tool Commands

Team Foundation Server Power Tool (tfpt.exe) is a command-line tool. To use these commands, start tfpt.exe at the Command Prompt. Some of the commands will display a graphical user interface when used. In addition, you can access the Annotate and Treediff commands from Source Control Explorer in Visual Studio or Team Explorer. Team Foundation Server Power Tool includes the following commands:

Unshelve Command
Use the unshelve command to unshelve and merge the changes in the workspace.

Rollback Command
Use the rollback command to roll back changes that have already been committed to Team Foundation Server.

Online Command
Use the online command to create pending edits on writable files that do not have pending edits.

GetCS Command
Use the GetCS (Get Changeset) command to get the changes in a particular changeset.

UU Command
Use the UU (Undo Unchanged) command to undo unchanged files, including adds, edits, and deletes.

Annotate Command
Use the annotate command to download all versions of the specified files and show information about when and who changed each line in the file.

Review Command
Use the review command to optimize the code review process to avoid checking in or shelving.

History Command
Use the history command to display the revision history for one or more files and folders. The /followbranches option returns the history of the file branch’s ancestors.

Workitem Command
Use the workitem command to create, update, or view work items.

Query Command
Use the query command to run a work item query and display the results. If you do not provide a specific query, all the active work items assigned to you are displayed.

TreeDiff Command
Use the treediff command to display a visual representation of the differences between files in two server folders, in a server folder and a local folder, or in two local folders.

Treeclean Command
Use the treeclean command to view and optionally delete files that are not under source control in the current directory and all subdirectories. This command is useful when you want to remove temporary files from your local workspace, such as files created by the compiler.

 

To use it for rollbacks, just add the install path to the tfpt.exe to your PATH environment variable.  Then, browse to the root of the project directory that you want to perform a rollback in and run "tfpt rollback" from the command line.

It will give you a user interface where you can find search for a chance-set to rollback.

Once you do it, you may have to "check in" the changes you just made, but I have used this several times and it has worked great.

 

Categories: Programming | TFS
Monday, May 19, 2008 2:47:19 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

A connection that was expected to be kept alive was closed by the server#

Has anyone been getting these errors when serving up SQL Reporting Services Reports?

A connection that was expected to be kept alive was closed by the server

All of a sudden we have been getting a lot of these, and I am not sure at the moment what is causing them.

We have 2 webservers that are hosting the reportviewer control, which loads up reports from a single reporting server.

This guy suggested that this problem was related to some 10 minute timeout, but I haven't been able to replicate his 10 minute problem.

Some other people are talking about overrideing the webservice proxy classes to set KeepAlive = false, but we have no webservice proxy to override as we are using the reportviewer.

Update:

This guy is talking about changing the SSRS session timeout.

Could "rc:Toolbar=false" be the problem?

Update 2:
Looks like this was all caused by the introduction of an IDP by our network guys.

 

Categories: Programming | Database | SQL Server | Reporting
Monday, April 14, 2008 3:05:27 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Javascript bookmark to aid with page layout#

A coworker sent me this link.  You just bookmark it, and then click the bookmark when you want to examine the layout of your page elements.

javascript:prefFile='';void(z=document.body.appendChild(document.createElement('script')));void(z.language='javascript');void(z.type='text/javascript');void(z.src='http://slayeroffice.com/tools/modi/v2.0/modi_v2.0.js');void(z.id='modi');

And it will add a little floating window in the upper left corner to show you everything you mouse over:

Categories: Programming | HTML | Javascript
Sunday, March 30, 2008 4:36:06 PM (Central Standard Time, UTC-06:00) #    Comments [1]  | 

 

Excluding weekends from a SQL date range#

Recently I wanted to find the time between 2 datetimes, but I wanted to exclude weekends.  To further complicate matters, I wanted to know hours, not just days.

The "standard" way to do stuff like this is to build out a calendar table that has every date for the next 50 years, along with info like "IsWeekend" or "IsHoliday".

But I found some snippets around that I hoped to use to my advantage, and what I came up with works very well:

DECLARE @start DATETIME
DECLARE @end DATETIME

SET @start = '3/7/08 12:50 pm'
SET @end = '3/11/08 1:50 am'

SELECT (DateDiff(hh, @start, @end) - DateDiff(ww, @start, @end)*2*24)/24.0
       
I won't spend a lot of time explaining why it works, but it basically counts the number of weekend "jumps" that are crossed between the 2 dates, and subtracts accordingly.

 

Categories: Programming | Database | SQL Server
Sunday, March 30, 2008 2:45:05 PM (Central Standard Time, UTC-06:00) #    Comments [3]  | 

 

Could not load file or assembly Microsoft.ReportViewer.XXX#

Are you getting one of these errors?

Could not load file or assembly Microsoft.ReportViewer.WebForms

Could not load file or assembly Microsoft.ReportViewer.Common

Could not load file or assembly Microsoft.ReportViewer.ProcessingObjectModel


The problem is that some of these assemblies are supposed to be in the GAC, or at least when you create a basic application using .net, the application is expecting to find them.

You can deal with this in one of 2 ways.  You can find and download the ReportViewer.exe from Microsoft on the clients.  Or, you can copy the missing DLLs out of the GAC on your computer, and add them into your project.

Because I didn't want to have to download extra software to my clients, I decided to take the second option.

To do this, follow the instructions here:

http://www.chrismay.org/2006/08/09/Accessing+DLLs+Stored+In+The+GAC.aspx

To pull the dlls out of the GAC (you can just copy them).

Then add them into your project at the root level (not as references, but just like you were adding another file).  Then, in visual studio, highlight them and select "Copy always" as the option for the "Copy to Output Directory" field.

This will make sure that the DLLs are copied into the BIN directory for deployment.

 

Categories: Programming | Reporting
Saturday, March 22, 2008 11:00:02 AM (Central Standard Time, UTC-06: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]  | 

 

Boilerplate TSQL Transaction Code for SQL Server 2005#

This is some useful stuff from 4guysfromrolla.com

BEGIN TRY
   BEGIN TRANSACTION    -- Start the transaction

   -- Your code here
-- If we reach here, success! COMMIT END TRY BEGIN CATCH -- Whoops, there was an error IF @@TRANCOUNT > 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH
Categories: Programming | Database | SQL Server | T-Sql
Thursday, March 13, 2008 3:50:01 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

SQL Server Reporting Services Email Subscriptions Not Going Out#

We recently ran into a problem with SSRS where our email subscriptions were processing, but no emails were going out.

SSRS doesn't really give you any info in the web interface to give you any clue that something isn't work right, let alone help you figure out what the problem is.

I was able to solve the problem by looking at the various log files that SSRS creates:  ReportServerWebApp__X, ReportServerService__X, and ReportServer__X.

In these config files I was able to find some errors coming back from our mail server. 

This lead me to discover that the problem was with how the email addresses were formatted. 

The issue was that we recently changed which mail server we used for sending out these emails, and we have moved from an Exchange 2003 server to an Exchange 2007 server.

Exchange 2003 would accept domain accounts as destinations for emails, so you could send an email to "cmay" and it would be delivered.  It seems that Exchange 2007 requires that you provide the full email address: cmay@company.com

After changing some of the SPs that served up the data, all worked once again.

 

Categories: Programming | Database | SQL Server | Reporting
Wednesday, March 05, 2008 4:18:38 PM (Central Standard Time, UTC-06:00) #    Comments [2]  | 

 

What ports are being used and by what programs?#

Sometimes you might need/want to know what ports on your machine are being used.

If you try to start up a process listening on some port and it reports that the port is alread in use, what do you do?

The answer is to use this command:

netstat -a -n -o

This will show you all port activity including the PID so you can open up task manager and find which process is using which port.

Categories: Misc | Networking | Programming
Sunday, February 24, 2008 5:45:53 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]  | 

 

Getting the RDL files out of Sql Server Reporting Services (SSRS)#

What happens if you lose the RDL source file for your SQL Reporting report?  Or more accurately, what if your coworkers never check them into source control?

Well, you can get them out of the web interface of SSRS.

To do this:

  1. Login into the /Reports of SSRS
  2. Navigate to the report you want
  3. Click the Properties tab
  4. Then under Report Definition, click "Edit"
  5. Save the RDL file to your local machine.

 

Categories: Programming | Reporting
Saturday, February 02, 2008 9:18:39 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]  | 

 

Http error 403.6 Forbidden IP Address#

Have you ever come across this error message?

403.6
Forbidden IP address of the client has been rejected

If you are using Small Business Server you might come into this quite fast as by default it will lock down IIS to keep machines who are not on the same subnet from accessing the web server.

This means if you VPN in you can't browse the intranet site.  Oops, that's not good.

To fix this problem, you need to edit the website and iis application properties in IIS.  On the Directory Security tab edi the IP address and domain name restrictions.  Change the settings on there from "Deny" to "Grant" and you will be all set.

 

Categories: Programming | IIS
Wednesday, January 16, 2008 4:25:33 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]  | 

 

Validate XML Against A Schema Online#

Have you ever wanted to validate an xml document against a schema, but didn't have any applications at your disposal to do it?

You can use the schema validate tool on decisionsoft.com:

http://tools.decisionsoft.com/schemaValidate/

You upload a schema and an xml doc, and it will attempte to validate the xml against the schema.

Categories: Programming | XML
Monday, January 14, 2008 8:58:18 AM (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]  | 

 

SQL "NOT IN" Will Fail If The List Contains A Null#

If you are using the NOT IN clause with a SQL Select statement with SQL Server it will not work if there is a null value in the list.  Say for example you want to do:

SELECT * FROM 
Employees 
Where 
Employee.Id NOT IN 
(  
   Select EmployeeId from 
   Salaries 
   where Salary < 100000
)

If the inner select returns a null value then the outer select statement will return no rows.

To try it, just run these 2 SQL statments against any table in your DB.

-- will return rows
SELECT * FROM 
sometable
WHERE ID NOT IN (1,2,3)

-- will return nothing
SELECT * FROM 
sometable
WHERE ID NOT IN (1,2,3, null)
Categories: Programming | Database | SQL Server
Monday, October 29, 2007 12:02:18 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Scott Hanselmans Ultimate Tools List#

Too many to list.

Some of my favs are on this list, like Launchy and SnippetCompiler.

Categories: Programming | Tools
Tuesday, October 16, 2007 10:35:45 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

patterns & practices Team Development with TFS Guide#

From CodePlex:

patterns & practices Team Development with TFS Guide (Final Release)

Welcome to the patterns & practices Team Development with Visual Studio Team Foundation Server project site! This guide shows you how to make the most of Team Foundation Server. It starts with the end in mind, but shows you how to incrementally adopt TFS for your organization. It's a collaborative effort between patterns & practices, Team System team members, and industry experts. This guide is related to our Visual Studio Team System Guidance Project.


TeamDevGuide.gif

Download the Guide

Final release is available! Start using the guide today, while we continue to make improvements.

Download the Diagrams

Download the Visio diagrams we used in the guide so that you can modify them and use them to document your own particular environment.

 

Categories: Programming | TFS
Tuesday, October 16, 2007 10:22:23 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Finding the cause for slow loading webpages#

Yahoo has released a tool called YSlow that helps developers identify why a specific website is loading slow.

Take a look at this screen cap (click to enlarge):

 

Categories: Programming | HTML | Javascript | Tools
Tuesday, October 16, 2007 10:18:04 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Dealing with null data in SSRS#

When working with a SSRS report, the report framework will already "Denull" everything.  But in some cases, for example when you are working with numbers, you might want to display a value in lue of the "" that is displayed for nulls.

Now you would THINK, that they would just use the same ISNULL syntax that everyone knows from sql programming.

HAHAHHAHA... of course they didn't do that.

Instead you have to use a combo of IIF and IsNothing like so:

=IIF(IsNothing(Fields!Quantity.Value),0,Fields!Quantity.Value)

It isn't THAT big of a pain, but I wish MS would sometimes just realize how much easier it would be for them to just create an IsNull function in their own codebase than make their users write this out.

Oh well.  I guess when it comes to problems with SSRS, this is waaaaaaayyyyy down my list.

Speaking of "my problems with SSRS"... when are you guys going to support TBLR text??  Drives me nuts.  Everyone does "vertical text" in TBLR format, for pretty much every application, but now in SSRS you are forced to use TBRL.  When you give these reports to engineers that is the very first thing they say "You need to turn this text around the other way".... yes I know, I got my degree in Civil Engineering with a focus on structure design, so when you come from a background of seeing all vertical text (like on any plans) as ALWAYS, by requirement, aligned in a TBLR manner, and then you are forced to cock your head the other way to read it, it is really a pain.

But I guess I would still like to see MS fix their *terrible* PDF rendering first.  I just LOVE watching my reports take 4x as long as in CR, and end up 100x bigger in file size than they are after being saved in acrobat (15 MB for a 1 page PDF, open in Acrobat, save the file again, down to 150KB, with no visible change in appearance or quality).

 

Categories: Programming | Database | SQL Server | Reporting
Thursday, September 27, 2007 10:22:45 AM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

 

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]  | 

 

MSDN Virtual Labs#

Microsoft has these "virtual labs" where you are supposed to be able to get hands on with some of their products w/o all the pain of downloading and installing them.

http://msdn.microsoft.com/virtuallabs/

Right now I can't the site to respond, but I am guessing it is a temp problem, not that they have removed this service.

Some of the labs they have are:

ASP.NET 2.0

ASP.NET

BizTalk Server

Commerce Server

Connected Systems

Data Access and Storage

Internet Information Services (IIS)

JPlusN (J+N)

Microsoft Expression

.NET Framework 3.0

Office

Security

Smart Client

Soup to Nuts

SQL Server 2005

SQL Server 2005 Upgrade

TechNet Virtual Labs

Visual Basic

Visual C#

Visual C++

Visual J#

Visual SourceSafe

Visual Studio .NET 2003

Visual Studio 2005

Visual Studio Team System

Web Services

Windows Embedded CE 6.0

Windows Mobile

Windows Vista

Windows XP Embedded

 

 

Thanks to Somasegar for the links.
Categories: Programming
Thursday, July 19, 2007 11:17:22 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Haacks 19 Laws Of Programming#

Haacked blogs about the 19 laws of programming.

My favorite, and one that I personally know to be very true, is Brooks law:

Adding manpower to a late software project makes it later.

Which can also be stated as:

The bearing of a child takes nine months, no matter how many women are assigned.

 

Categories: Funny | Interesting | Programming
Thursday, July 19, 2007 10:35:43 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Code Comment Checking Policy#

I have all but given up on Code Checkin Policy in TFS.

For me, running the policy checker against one of my solutions takes about 30 minutes.

That is unacceptable.

But, there is still some hope of running the static analysis on the back end, so I am still looking around at the goings on in this area.

A new Code Comment Checking Policy has been released, which would be really nice way to force the people to comment their code.

Categories: Misc | Programming
Thursday, July 19, 2007 10:11:45 AM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

 

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]  | 

 

Looking for TFS hosting? No luck.#

I recently sought out any companies that were providing hosted TFS projects.  Microsoft is doing this with CodePlex.com, but only for open source projects.

Amazingly there is nothing out there for people who want to pay to have their project hosted in a TFS environment.

Some sites suggest that this may be offered soon: http://www.staheli.org/vsteamsystem/

But as of now, nothing...

Which is too bad, because I think the source code control of TFS is pretty nice, and I would like to use it in the future on some of my projects.

Categories: Programming | TFS
Tuesday, July 17, 2007 1:24:19 PM (Central Daylight Time, UTC-05:00) #    Comments [6]  | 

 

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]  | 

 

Team System Widgets#

I am still trying to find more value in the Team System/TFS combo.  There are some really great benefits that we are seeing in terms of using TFS for our source control, but a lot of the things I had hoped to do with TFS are simply not good enough to actually use.  Unit testing, continuous integration, bug tracking, code policy etc.

Here are a list of addin widgets for team system:
http://teamsystemexperts.com/widgets.aspx

I'm hoping that some of these can provide some added value to the entire system.

Categories: Programming | TFS
Saturday, June 30, 2007 1:12:18 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]  | 

 

3 things I learned in (and out of) college#

Dare Obasanjo has a post on the "Three Things I Learned About Software in College," to which Scott Hanselman followed up with Three Things I Learned About Software WHILE NOT in College.

So here are my 3 from each category:

Learned in college:

1) A lot of people getting a CS degree will never be able to write a real program (as I was getting my degree in structural engineering (CE)).

2) New features and scope creep can cause projects to be never ending, and end up not being released at all.

3) How to really work hard, really study hard, and really focus on a task with a fast approaching deadline.


Learned OUT of college:

1) Just because someone has "Sr." in their title doesn't MEAN they know anything, but they might.  If their logic sounds flawed, don't assume it is because they are "Sr" and you are "Entry": you are probably right.

2) "Expert" can mean different things to different people.  You can be in the top 2% of one company, but a middle of the pack guy in another.  Avoid calling yourself an "expert" (or acting like one) unless you know who you are talking to, and you actually are the expert.

3) There is no "Best" way to do most things.  I had thought that if I looked hard enough and studied enough examples, I would know the "best" way to do things when I arrived at them.  But one groups "best practice" is something another group will not touch.  See the current OR/M arguments for a perfect example, or if you prefer just look at divide over using Datasets. 

That being said, there are definitely some agreed upon "Worst Practices", so avoid these at all costs.

Categories: Misc | Programming
Friday, June 29, 2007 9:03:32 AM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

 

Making a column non-null and unique in SQL Server 2005#
Someone asked me how to do this the other day, and I couldn't find a simple way to do it in the SQL Server Management Studio, but the script is pretty simple:

ALTER TABLE tablename
ALTER COLUMUN
   columnname varchar(50) NOT NULL
GO ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE( columnname ) GO
Categories: Programming | Database | SQL Server
Thursday, June 28, 2007 8:10:19 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]  | 

 

Dream.In.Code#

I saw a link from Scott Hanselman's site to DreamInCode.net, which is looks like a community site for programmers.

I have been looking for a forum for software consultants like myself, so I will have to check out the forums:

http://www.dreamincode.net/forums/

There is the "Caffeine Lounge", which sounds like the perfect place for me.  When the guys at starbucks start your order before you say anything, you have probably been in there too often.

Categories: Misc | Programming
Tuesday, June 26, 2007 5:41:41 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Plasma Unit Testing#

I came across this CodePlex project called Plasma which is supposed to aid in testing web apps with standard unit test frameworks.

I couldn't find much info on their codeplex site, but I will be keeping track of it to see if I can find some info.

Categories: Programming | Testing
Wednesday, June 20, 2007 3:03:52 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]  | 

 

ALT.NET#

Somehow the term ALT.NET has been created to describe people who use .Net to program, but try to avoid the "standard" practices and tools that microsoft pushes.

Roy Osherove has an article where he pits the HOT and NOT as seen by the alt.net guys.

My major issue with trying to adopt more of these practices is that I work mostly on existing large applications.

I can't just show up at a client who already has millions of LOC using a more standard approach with thousands of stored procedures, and jump into a Monorail/NHibernate project.

For now I am focusing on getting one of my clients using a server based build and deployment.  We have already moved off of VSS, which is making a big difference in our productivity.

Categories: Programming | TFS | VSS
Tuesday, June 19, 2007 10:51:54 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

What Files Shoud Go In Source Control#

I was searching for some guidance on this and came across a nice paper:

Explained :Structuring Your Solutions And Projects In Source control Using Team Foundation Server

What Files Should Be Source Controlled?

The following list identifies the key file types that you should add to source control. These are the file types that are added when you click Add Solution to Source Control.

Solution files (*.sln). Solution files maintain a list of constituent projects, dependencies information, build configuration details, and source control provider details.

Project files (*.csproj or *.vbproj). Project files include assembly build settings, referenced assemblies (by name and path), and a file inventory.

Visual Studio Source Control Project Metadata (*.vspscc). These files maintain project bindings, exclusion lists, source control provider names and other source control metadata.

Application configuration files (*.config). XML configuration files contain project and application specific details used to control your applications ’s run time behavior.

 

Web applications use files called Web.config. Non-Web applications use files called App.config.

Note: At run time, the Visual Studio build system copies App.config to your project’s Bin folder and renames it as Yourappname.exe.config. For non-Web applications, a configuration file is not automatically added to a new project. If you require one, add it manually. Make sure you call it App.config and locate it within the project folder.

Source files (*.aspx, *.asmx, *.cs, *.vb, …). Source code files, depending on application type and language.

Binary dependencies (*.dll). If your project relies on binary dependencies such as third party DLLs, you should also add these to your project within source control. For more information about managing dependencies, see "Explained: Managing Source Control Dependencies in Visual Studio Team System."

What Files Should Not Be Source Controlled?

The following files are not added to source control because they are developer specific:

Solution user option files (*.suo). These contain personalized customizations made to the Visual Studio IDE by an individual developer.

Project user option files (*.csproj.user or *.vbproj.user). These files contain developer specific project options and an optional reference path that is used by the Visual Studio to locate referenced assemblies.

WebInfo files (*.csproj.webinfo or *.vbproj.webinfo). This file keeps track of a project's virtual root location. This is not added to source control to allow individual developers to specify different virtual roots for their own working copy of the project. While this capability exists, you and all team members are recommended to use a consistent (local) virtual root location when you develop Web applications.

Build outputs that include assembly dynamic-link libraries (DLLs), Interop assembly DLLs and executable files (EXEs). Note that you are advised to add assemblies that are not built as part of your system build process (such as third-party controls and libraries) to Source Control within the projects that reference them.

Categories: Programming | TFS
Thursday, June 14, 2007 2:09:45 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Tips for Testable Code#

I linked to this article in my last post, but here are 2 from Roy that are really about HOW to write code that is testable.

Tips for Testable code and for testing legacy code

Achieving And Recognizing Testable Software Designs – Part I

Categories: Programming | Testing
Wednesday, June 13, 2007 9:43:57 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Writing Tests that work in NUnit and MSTest#

As someone who is trying to jump into the unit testing world, one of the major problems I had was deciding on using NUnit (which everyone uses) or use MSTest(built in).

I didn't want to jump into this and realize 500 hours later that I picked the wrong framework.  Well, now it seems I don't have to worry about that as much. 

First I was reading this article by Roy Osherove, and somehow I ended up on this page talking about converting between NUnit and VSTS projects, and from there I found a link to this page, which contained this great piece of code:

#If NUNIT Then
Imports NUnit.Framework
Imports TestClass = NUnit.Framework.TestFixtureAttribute
Imports TestMethod = NUnit.Framework.TestAttribute
Imports TestInitialize = NUnit.Framework.SetUpAttribute
Imports TestCleanup = NUnit.Framework.TearDownAttribute
#Else
Imports Microsoft.VisualStudio.TestTools.UnitTesting
#End If

This allows you do have the came code for NUnit and MSTest.  Just change the NUNIT variable and recompile.

The other thing you need to do is use <TestAttribute()> instead of <Test()> on your NUnit tests, but I don't see the difference there.

 

Categories: Programming | Testing | TFS
Wednesday, June 13, 2007 9:36:25 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Adding Static Code Analysis To Team System/TFS#

So I have this problem.

If someone declares:

Public iProductId as Integer

then I want to be notified.  But if someone declares:

Protected WithEvents txtUserName as Textbox

I don't want to be bothered.

Every control declaration we have throws an error in the static code analysis tools.

So after asking around, I guess it is not possible to cusomize the existing rules to exclude common prefixes such as lbl, txt, cmd etc.

So apparently the only option left is to disable those rules and create my own. 

So here are a few links that deal with creating custom links.

MSDN

Kevin Castle

FxCop Team

 

Categories: Programming | VS.Net | TFS
Monday, June 11, 2007 1:48:08 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Team Foundation Server Power Tool and Forums#

MS has released a power tool for TFS, and here are the MS hosted forums:

Team Foundation Server - General
Discuss Team Foundation Server general concepts.

Team Foundation Server - Setup
Discuss Team Foundation Server setup and configuration.

Team Foundation Server - Administration
Discuss Team Foundation Server administration and operations.

Team Foundation Server - Version Control
Discuss Team Foundation Version Control, including branching, merging, and shelving.

Team Foundation Server - Work Item Tracking
Discuss Team Foundation Work Item Tracking, including work item customization and Office integration.

Team Foundation Server - Reporting
Discuss Team Foundation Reporting, which uses SQL Server 2005 Reporting services to report team project metrics.

Team Foundation Server - Build Automation
Discuss Team Foundation Server's build automation features.

Team Foundation Server - Process Templates
Discuss Team Foundation Server process template development and customization.

Categories: Programming | TFS
Friday, June 08, 2007 5:19:26 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Uploading files with Silverlight#

Brad Abrams has a post on a photo viewer app written for Silverlight that has fileupload ability.

I would be interested to see how that is done, and what the UI is like.

Categories: Programming | Silverlight
Thursday, June 07, 2007 10:10:04 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Running VSSConverter Against SQL Server 2005#

The VSSConverter tool which allows you to convert from VSS to TFS will attempt to utilize a local version of SQL Express.

This sucks, as I hate SQL Express.

After some searching/trials/errors, I found a way to get it to work against a SQL Server 2005 database.

Just add the SQL tag to your migration settings xml file like so:

<Source name="VSS">

      <VSSDatabase name="D:\Program Files\Microsoft Visual SourceSafe\VSSHttp"></VSSDatabase>

      <UserMap name="D:\VSS2TeamFoundation\Usermap.xml"></UserMap>

      <SQL Server="name_of_your_SQL_Server" />

</Source>

Categories: Programming | TFS | VSS
Thursday, June 07, 2007 2:26:49 PM (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]  | 

     

    Software Development and TDD Anti-Patterns#

    This is awesome!

    Wikipedia has a whole list of programming anti-patterns, and James Carr lists some TDD anti-patterns.

    Some of these are pretty funny:

    Magic numbers: Including unexplained numbers in algorithms

    Superboolean logic: unnecessary comparison or abstraction of boolean arithmetic

    Boat anchor: Retaining a part of a system that no longer has any use

    Categories: Programming | .Net Framework | Testing
    Tuesday, May 29, 2007 11:14:43 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]  | 

     

    Upgrading from TFS Workgroup to Standard#

    Here is an article from MS on how to od the upgrade.

    Thankfully, it is a very easy process.

    Categories: Programming | TFS
    Tuesday, May 29, 2007 10:26:20 AM (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]  | 

     

    Simulating HttpContext #
    Update: Phil Haack has updated his HttpContext Simulator with some new goodies.

    Here is an article by Haacked showing how one can create a test friendly httpcontext.

    I modified his example some and started using it in some tests; works very nice!

    Here is another implementation based on Haack's example that is supposed to also work with session.

    I almost NEVER use session if I can avoid it, but still this could come in handy.

    Categories: Programming | Testing
    Monday, May 28, 2007 2:23:03 PM (Central Daylight Time, UTC-05:00) #    Comments [4]  | 

     

    Null Object Refactoring#

    Here is a nice article on Null Object Refactoring, a process where you create a null representation of an object for use when you want to treat the object as null, rather than passing around a truely null object.

    This is one of Fowlers refactoring suggestions from his book: Refactoring: Improving the Design of Existing Code and on his site: http://www.refactoring.com/catalog/introduceNullObject.html

    Categories: Programming
    Friday, May 25, 2007 1:18:48 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    VSTS ASP.NET Unit Tests#

    There is virtually no information on the internet about how to use these tests.

    This is one of the vew pages that actually shows a working example.

    This discussion group seems to be mostly dealing with standard unit tests, and winform unit testing.

     

    Categories: Programming | Testing
    Tuesday, May 22, 2007 5:22:01 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]  | 

     

    TeamPlain for TFS released for free#

    This is good news for those of us who were kinda pissed that Team Foundation Server didn't come with this type of interface to begin with:

    http://blogs.msdn.com/bharry/archive/2007/03/26/microsoft-acquires-teamplain.aspx

     

    Categories: Programming | TFS
    Monday, May 21, 2007 2:33:57 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

     

    Creating a test SSL certificate#

    Here is a nice article on creating a test (bogus) SSL certificate for your local develoment machine.

    ScottGu has a nice article on how to do something similar with IIS7, which is going to be the webserver on Vista machines.

    Categories: Programming | IIS
    Monday, May 14, 2007 1:17:25 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]  | 

     

    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]  | 

     

    Getting Just the Date Out Of GETDATE#

    SQL Servers' GETDATE() function will return the current DateTime.  But what if you just want the current date.

    CAST(FLOOR(CAST(GETDATE() AS float)) AS datetime)

    or

    CAST(CONVERT(VARCHAR(10), GETDATE(), 111) AS DATETIME)

    See this page for even more options.

    Or, if you want to get just the current time out of GETDATE or any datetime for that matter, check out this page (it is one of the FAQs).

     

    Categories: Programming | Database | SQL Server
    Sunday, March 04, 2007 10:36: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]  | 

     

    Problems with SQL RS on Windows 2000#

    I was having problems with getting RS to work correctly on a windows 2000 server.  I would browse to the page, and it would prompt me for my credentials.  I would use the Admin loign, and it wouldn't take, finally giving me an error like this:

    Server Error in '/Reports' Application.
    --------------------------------------------------------------------------------

    Access to the path "C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\ReportManager\bin" is denied.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.UnauthorizedAccessException: Access to the path "C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\ReportManager\bin" is denied.

    ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

    I found someone who figured out the impersonation problem:

    The problem happens when installing RS on Windows 2000 Server that is a domain controller.  RS doesn't do the setup correctly.  The basic steps to fix the problem are

    1. Grant impersonate privilege to IWAM_<machine> account (see knowledge base article 824308).  Go to domain controller security policy  in administrative tools. Click security settings -> Click local policies -> click user right assignment.  In the right pane, double click impersonate a client after authentication.  In security policy setting window, click define these policy settings.  Click add -> click browse.  In select users or groups window, select IWAM account name and click add.  Then, click Ok -> Click OK -> Click OK.  At command prompt, type the following command: secedit /refreshpolicy machine_policy /enforce.  Then, type iisreset.

    2.  Remove IWAM_<machine> account from guest group.  Go to active directory users and computers in administrative tools.  Open users folder.  In right pane, double click IWAM_<machine>.  Select member of tab.  Remove guest.  Click OK.

    3.  Reboot.

    4.  Run rsactivate.  From command prompt, change directory to C:\Program Files\Microsoft SQL Server\80\Tools\Binn.  The run following command: RSActivate.exe -c "c:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\ReportServer\RSReportServer.config" -t.

    See the following link for more details http://msdn.microsoft.com/library/default.asp?url=/library/en-us/RSINSTALL/htm/gs_installingrs_v1_8k82.asp .

    For now, this seems to have fixed this problem.

    Categories: Programming | SQL Server | Reporting
    Tuesday, February 06, 2007 9:27:48 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]  | 

     

    Software Is Hard#

    This article discusses the turmoil of a multi-year software project, and attempts to answer the question: Why is writing software hard?

    http://www.salon.com/books/int/2007/02/03/leonard/

    Categories: Interesting | Programming | Software
    Sunday, February 04, 2007 11:12:21 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Host Project With CodePlex#

    http://www.codeplex.com will allow you to host your project on their servers, and apparently they are running TFS.

    Categories: Interesting | Programming
    Wednesday, January 31, 2007 2:12:36 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

     

    Regu