Archive for the ‘Uncategorized’ Category

mixed razor and html (a little beyond the simple examples you find at w3 school)

July 1, 2014

mixed razor and html (a little beyond the simple examples you find at w3 school)

(sorry about this post all in an image … I’m not skilled enough at word press to format all my bracket characters)

here is what finally worked
we took out as much razor as possible, and now I’m happy. I failed to catch another error in the image of all my travails with this – we got the system message that echoed to the screen, and the fix for that was to put in a “using” statement … and I could not get this to work in a reasonable amount of time. (less than 4-6 hours) Less razor is a good thing.


adding a website to tfs

October 16, 2012

What didn’t work:

1) create empty Visual Studio 2010 solution

2) add an existing website to the solution. (http://localhost:81/myWebSite ) . It was port 81 because I also have Sharepoint on this pc.

What was wrong? the website could not be added to TFS.

Steps to fix:

1) add another existing library project to the solution (I needed it anyway). I think otherwise I couldn’t delete the website from the solution.

2) delete the website from the solution

3) re-add the same website, this time using the “File System” rather than IIS.

4) Check in to TFS no problems.



when all else fails

September 11, 2012

kind of a comment on that last post – actually, I had the code correct for about 15 minutes or so,  and continued to get 404 errors, and also my test html page did not reflect the posting url in the latest copy of the html file  in my project (which was weird). So I went to the trusty IE/tools/in private browsing to make sure I was starting from a clean playing field, and it all worked.

Too bad that the cached junk had led me down a few stray rabbit trails.

change page url

June 4, 2010

ok, what I learned was that you can’t change the page url using the httpcontext.current.request.rewritePath function. But, to achieve that effect, I did the following:

Protected Sub ddlListRecentErrorSessions_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlListRecentErrorSessions.SelectedIndexChanged
Dim sSession As String = Me.ddlListRecentErrorSessions.SelectedValue
'handle_load_gridview_for_session(Me.gvResult, sSession)
End Sub

'Using Context.RewritePath is not for changing how the URL is displayed
'in the browser. Let's be very, very clear.
'You cannot change what is displayed in the browser address bar.
Sub set_url_for_session(ByVal sSession As String)
' change the url to use our session
Dim sPath As String = HttpContext.Current.Request.Path
Dim sQuery As String = "?session=" + sSession
Diagnostics.Debug.Print("set_url SESSION=" + sSession)
Dim sFullPath As String = sPath + sQuery
Response.Redirect(sFullPath, True)
'HttpContext.Current.RewritePath(sPath, True, sQuery)
End Sub

Ghost Process Writing to Visual Studio 2008 Debug Immediate Window

November 4, 2009

If you’ve never seen something like this, you might not believe it.

In debugging a website running under, I had debug.print lines from another website appearing in the immediate window.
They stopped if:
1) I shut down IIS (of course, that killed my debugging as well)
2) I detached the asp_wp worker process from the debugger (and then I couldn’t debug my own project)
3) killing the asp_wp processes from Task Manager gave a brief respite, but the messages started again once the worker process was reactivated.

What I finally did, and this is a temporary fix, is to luckily guess the offending website under IIS, and rename the directory. Now, that website is not able to be browsed.

I had only one instance of IE or any other browser open during the time when I was trying to fix the problem. (generally I have many open)

I suspected some scheduled process browsing to the website – that is still a possibility.
Also, I suspect a coding practice of mine, which is to use some debug logging code in static (vb – shared) functions. Perhaps IIS is for some reason opening this virtual directory? (I know I said web site above, but actually I mean a virtual directory under the same website running in the same IIS .Net 2 process.)
Also, the virtual directory in question was the last one in alphabetical order of all my virtual directories.

I did not search Knowledge Base about this. It’s something I’ve lived with for weeks, at least, and just ignored, until this AM.

How to set an environment variable by setting it in the registry

June 5, 2009

It’s easy to do a “getenv” , but you’d be surprised at how hard it is to set an environment variable.
Sorry, I’m not going to take the time to write here what I learned from some excellent explanations found at codeguru and elsewhere, but I’ll try to post those links at the last.
1) set the current user\environment\yourstring=value in the registry
2) send a windows refresh message (this doesn’t communicate with whatever command prompts you may already have, but it will work for the calling process)
3) whatever new command prompt or process will use your new setting

LRESULT CMainDlg::OnSetMyEnvironmentValue(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
CString sNetId;

return Handle_SetEnv(sNetId);
return 0;

int CMainDlg::Handle_SetEnv(CString sNetId)
//MessageBox (sNetId, "netid", 0) ; //sNetId.GetBuffer()

// set env variable
int iRet = 0;
iRet = SetEnvironmentVariable("netid", sNetId.GetBuffer() );

if( iRet <=0 )
return -1;
return 0;


int CMainDlg::Handle_SetReg(CString sNetId)
CString subKey = "Environment";
HKEY hKey;
char *m_tmpChar = new char[100];

if (RegOpenKeyEx(HKEY_CURRENT_USER, subKey, 0, KEY_SET_VALUE, &hKey))
MessageBox("Error opening the key");
RegCreateKey(HKEY_CURRENT_USER, subKey,&hKey);

if ( RegSetValueEx(hKey, "netid" , NULL , REG_SZ, (unsigned char*)sNetId.GetBuffer() ,sNetId.GetLength() +1) )
MessageBox("Error setting the value");

return 0;

int CMainDlg::Handle_RefreshEnvironment()
DWORD_PTR dwReturnValue;

500, &dwReturnValue);
return dwReturnValue;

Here were some helpful links:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment



looks like broadcasting the wm_settingchange won’t talk to cmd prompts

recursive stored procedure

March 11, 2009

The business purpose of this stored procedure is to permit a project to contain a sub-project. Because each sub-project could again contain other projects, it looked like I could potentiall get infinite loops in my logic. Therefore I wanted to prevent loop backs in my chains of projects.

The recursive stored procedure was able to walk up the chain of containing projects, and could be used to prevent a project from being inserted twice in the same chain.

There were a few tricks involved, and since it’s been about a month since I worked on this, I’m not sure I can remember all that, and for the time being will simply post the create scripts and hope that they are not too implementation specific and perhaps useful to somebody.

There are two important tables – a Projects table, where each project has an integer projectkey, and then a ProjectsOfProjects table, where each entry has a parent key, a child key, and a grandparent key. If you walk up a chain of records, at some point the grandparent key is null, and that is the end of the chain.

/****** Object: StoredProcedure [dbo].[ProjectAncestors] Script Date: 03/11/2009 17:14:20 ******/
-- =============================================
-- purpose: can we add this child to the specified parent?
-- return false if no, true if yes,
-- returns all the ancestors by recursively calling itself
-- until the last record has a null for the parent key
-- exec ProjectAncestors 40, 30 , 8 , 1
-- Child key - the current project
-- Parent key - the parent project
-- Parent_ikey - the field in the ikey'th record in the ProjectsOfProjects table where the parent's parent is defined
-- (this is the trick that enables us to "walk up" the table and get all the ancestors
SAMPLES: (we had already set up the ProjectsOfProjects table so that there were some children and parents defined)
exec ProjectsOfProjects_ADD 50 , 30, 8 , 1
NOTE - the first execution of [ProjectAncestors] has to have @start=1

declare @OkToInsert bit
exec @OkToInsert = ProjectAncestors 60,30,8,1
print @OkToInsert

exec ProjectAncestors 40, 30 , 8, 1
-- =============================================
CREATE PROCEDURE [dbo].[ProjectAncestors]
@childkey int,
@parentkey int,
@parent_ikey int,
@start int ,
@returncode int OUTPUT

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
set @returncode = -99

print '******* run [ProjectAncestors] NestLevel=' + convert(varchar(10), @@nestlevel)

declare @Kount int

-- 1) if temp table doesn't exist, then create it
if @start = 1
IF OBJECT_ID('tempdb..#ProjectAncestors') IS NOT NULL drop table #ProjectAncestors

-- set up the table to hold the chain of ancestors
CREATE TABLE #ProjectAncestors (parentkey INT)
-- set up the table to hold the global variable
CREATE TABLE #GlobalVars (childkey INT)
INSERT INTO #GlobalVars (childkey ) VALUES (@childkey )

print ' set the original childkey ' + convert(varchar(10), @childkey)

-- 2) go ahead and insert the parameter
INSERT INTO #ProjectAncestors (parentkey ) VALUES (@parentkey )

-- 3) check for the end - when the parent_ikey is null, there are no more relationships defined in the ProjectOfProjects table
if @parent_ikey is NULL
-- a. is it valid to make the relationship? if the desired child was already in the list of ancestors, then it is NOT
-- BUT - remember, this is a recursive procedure, the child key is changing each time we call it. We need to check
-- on the original child key
declare @original_childkey int
select @original_childkey=childkey from #GlobalVars
print ' test the @original_childkey=' + convert(varchar(12),@original_childkey)
select @Kount = count(*) from #ProjectAncestors where parentkey=@original_childkey

-- return the result set
select * from #ProjectAncestors

drop table #ProjectAncestors

print '[ProjectAncestors] just before return @Kount=' + convert(varchar(10),@Kount )
if @Kount > 0
print ' return 0 from [ProjectAncestors]'
print ' the input child record ' + convert(varchar(25), @original_childkey)
print ' was found in the list of ancestors, and therefore cannot be added'
set @returncode = 0
print ' @returncode in [ProjectAncestors]:' + convert(varchar(10),@returncode )
IF OBJECT_ID('tempdb..#ReturnCode') IS NOT NULL
insert into #ReturnCode (returncode) values (@ReturnCode)

return 0
print ' return 1 from [ProjectAncestors]'
print ' the input child record ' + convert(varchar(25), @original_childkey)
print ' was NOT found in the list of ancestors, and therefore CAN be added'
set @returncode = 1
print ' @returncode in [ProjectAncestors]:' + convert(varchar(10),@returncode )
IF OBJECT_ID('tempdb..#ReturnCode') IS NOT NULL
insert into #ReturnCode (returncode) values (@ReturnCode)
return 1


print '@parent_ikey is NOT NULL ' + convert(varchar(10),@parent_ikey)

declare @new_parentkey int
declare @new_ikey int
select @new_parentkey=parentkey, @new_ikey=parent_ikey from ProjectsOfProjects where childkey=@parentkey and ikey=@parent_ikey

-- **************************************************************
-- **************************************************************
-- if it is not null, we recurse
exec projectAncestors @parentkey, @new_parentkey, @new_ikey , 0 , @returncode


And the structure of the ProjectOfProjects table is:

CREATE TABLE [dbo].[ProjectsOfProjects](
[ikey] [int] IDENTITY(1,1) NOT NULL,
[parentkey] [int] NOT NULL,
[childkey] [int] NOT NULL,
[parent_ikey] [int] NULL,
[ikey] ASC

Type initializer exception for shared class

February 11, 2009

From time to time I have gotten a baffling error – “Type initializer exception was unhandled by user code”.

I had a shared (static) class that I use for some utilitity functions, and in that I have a shared constructor and a shared Init function to set a few of the shared variables. And this has run with no incident hundreds if not over a thousand times.

Background – this is a VStudio 2008 web site run from a file directory, not from IIS.

What I notice, however, is that when I run Visual Studio Debug, it may work once, but a second time , if there is a hanging instance of AspDotNet Development Server in my toolbar, then the second time I attempt to debug, my shared class will apparently not instantiate, and I get that weird message. I close Visual Studio, reopen, and then things work.

Also, in the past when I was running from IIS, I attempted to do the same thing (initialize a few variables in this shared class), but I attempted to do it in global.asax. I have since given up on that – the type initializer messages were too weird for me.

checkboxlist and the selected item

November 12, 2008

I’ve got a lot of linking tables in my database – a linking table has keys from two tables. For example, I’m assigning employees to a project. I think of the project key as the major key, and the employee key as the minor key – since I can assign multiple employees to work on a project.

I thought it would be pretty natural to control how employess got assigned with a checkboxlist control. If an employee were assigned, then his checkbox would be checked, and if he were waiting assignment, it would not be checked. Then simply checking the box should assign him to a project by creating a record in the link table.

But, the CheckListBox.SelectedIndex is not the item I click on – it turns out it is the first in the list that happens to be checked. This may be useful for some people, but not so useful for me. Here is the code for the _selectedIndexChanged event that works for me.

    Protected Sub chkList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkList.SelectedIndexChanged

            'dont - sometimes throws an exception Diagnostics.Debug.Print("TEXT:" & chkList.SelectedItem.Text + " VALUE:" + chkList.SelectedItem.Value.ToString + " CHECKED?:" + chkList.SelectedItem.Selected.ToString() + " INDEX:" + chkList.SelectedIndex.ToString)

            Dim sLinkKey As String = ""
            Dim sMinorKey As String = ""
            ' note - in the link table, if the value is not selected, there is no record, therefore the link key is zero

            ' is the selected item checked or not?
            Dim iIndex As Integer = get_the_index_from_id()  ' returns the first selected item's index
            If (iIndex = 0) Then
                If (chkList.Items(iIndex).Selected) Then
                    Handle_Add(Me.m_MajorKey, sMinorKey) ' add a record to the link table with project key and employee key
                    Handle_Delete(sMinorKey)    ' delete the records from the link table where the employee key matches
                End If
            End If


            Handle_LoadData()  ' reload data and refresh the box each time

        Catch ex As Exception
            Diagnostics.Debug.Print("***************************** ERROR " & ex.Message)
        End Try
    End Sub

    ' ---------------------------------------------------------------------------------------------------------
    ' note - in a checkboxlist, the first selected item is the first one that happens to be checked, not the one that you clicked with the 
    ' mouse. To get the index of the item in the array of checkboxes, you have to split it out of EventTarget.
    Function get_the_index_from_id() As Integer
        Dim sCmd As String
        Dim sEvent As String
            sCmd = Request.Form("__EVENTTARGET")
            sEvent = Request.Form("__EVENTARGUMENT")
            Dim sA As String() = sCmd.Split("$")
            Dim n As Integer = UBound(sA)
            Dim sIndex As String = sA(n)
            Return CInt(sIndex)

        Catch ex As Exception
            Return -666
        End Try

        Return -1
    End Function

javascript – replace non printing blank space

November 4, 2008


My html displays as a span, and I pad it with spaces when the underlying data is null. It causes problems when I try to update the data without stripping away those spaces.

There were two solutions – 1) don’t use innerHtml to get the contents of the span, use innerText, and 2) get the correct Javascript syntax for the replace.

how to replace &nbsp; in javascript

  var sText = actual.innerHTML;
  // use innerText instead – it won’t have the weird spaces problem
  //sText = actual.innerText;
  // get rid of nbsp
  sText = sText.replace(/&nbsp;/g, ”);  // replace global