count database updates for all tables

October 17, 2011

To count all database updates for all tables (that containe a datetime field), just execute this query:

– purpose – see if this database is being updated
– use a set of queries on datetime fields.
– Make the queries dynamic, and pass in the table and column names.
– collate results into a temp table and then display all together
declare @t_name varchar(50)
declare @c_name varchar(50)
declare @query_base varchar(250)
set @query_base = ‘select {QQQTABLE} as [TableName], count(*) as CountRecentUpdates from QQQTABLE where QQQCOLUMN > dateadd(d,-1,getdate() )’
declare @query varchar(500)
declare @TempTableInsert varchar(80)
set @TempTableInsert = ‘ insert into #MyTempTable ([TableName] , [CountRecentUpdates] ) ‘

CREATE TABLE #MyTempTable ([TableName] varchar(50), [CountRecentUpdates] varchar(50) )

declare ci cursor for
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (DATA_TYPE = ‘datetime’) AND (NOT (COLUMN_DEFAULT IS NULL))

open ci

fetch next from ci into
@t_name,
@c_name

WHILE @@FETCH_STATUS = 0

BEGIN

–print @t_name + ‘ ‘ + @c_name

set @query = replace(@query_base,’QQQTABLE’, @t_name)
set @query = replace(@query ,’QQQCOLUMN’, @c_name)
set @query = replace(@query ,’{‘ , char(39) )
set @query = replace(@query ,’}’ , char(39) )
set @query = @TempTableInsert + @query
–print @query
EXECUTE(@query)
– *************************************************************
– RE-LOAD THE CURSOR
fetch next from ci into
@t_name,
@c_name

end
close ci
deallocate ci

select * from #MyTempTable
drop table #MyTempTable

mvc db context error

October 17, 2011

I was following the MVC Movie example, and decided at one point not to follow the directions strictly. (http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part7-cs)

I got the error: “The model backing the ‘MovieDBContext’ context has changed since the database was created. “

There is a fix described at http://stackoverflow.com/questions/3552000/entity-framework-code-only-error-the-model-backing-the-context-has-changed-sinc

But, I just deleted the table from movies.sdf that had the index definitions in it, and things started working again.

mvc3 install

August 2, 2011

see http://blog.mjjames.co.uk/2010/12/mvc-3-rc2-install-error-0×80070643.html

I had the common problem where vstudio 2010 wouldn’t update.

The following worked:
1) start AspNetMVC3ToolsUpdateSetup.exe, let it stop at the acknowledge screen
2) go to the c:\temp directory and copy the directory of unpacked files
3) run the vstudio kb update exe separately (mine worked)
4) then go back and run AspNetMVC3ToolsUpdateSetup.exe. I always ran as administrator.

summarize a datatable

June 23, 2011

This might be ugly code … but I just dropped it into an admin page on a project, and it worked first time. Contains comments that tell how to use it.
What does it do? It takes a datatable and sums the columns that you tell it to, and then appends this row to the bottom of the table.

' ---------------------------------------------------------
' purpose - summarize a datatable by summing selected columns
' INPUTS: title column, sum columns
' HOW TO USE:
'Dim iret As Integer
'iret = objD.SummaryRow(dt,0, 3, "Total:", 5)
' (put the count of rows in the 0 column, the Total string in col 3, and the sum in column 5)
' you can add up to 10 columns to sum
' be careful not to put strings into datetime columns, for example
Function SummaryRow( _
ByRef dt As System.Data.DataTable, _
ByVal iCountCol As Integer, _
ByVal iTitleCol As Integer, _
ByVal sTitle As String, _
Optional ByVal i0 As Integer = 0, _
Optional ByVal i1 As Integer = 0, _
Optional ByVal i2 As Integer = 0, _
Optional ByVal i3 As Integer = 0, _
Optional ByVal i4 As Integer = 0, _
Optional ByVal i5 As Integer = 0, _
Optional ByVal i6 As Integer = 0, _
Optional ByVal i7 As Integer = 0, _
Optional ByVal i8 As Integer = 0, _
Optional ByVal i9 As Integer = 0) As Integer
Dim iParms As New ArrayList
If (i0 > 0) Then iParms.Add(i0)
If (i1 > 0) Then iParms.Add(i1)
If (i2 > 0) Then iParms.Add(i2)
If (i3 > 0) Then iParms.Add(i3)
If (i4 > 0) Then iParms.Add(i4)
If (i5 > 0) Then iParms.Add(i5)
If (i6 > 0) Then iParms.Add(i6)
If (i7 > 0) Then iParms.Add(i7)
If (i8 > 0) Then iParms.Add(i8)
If (i9 > 0) Then iParms.Add(i9)
Try
Dim NewSummaryRow As System.Data.DataRow = dt.NewRow
NewSummaryRow(iTitleCol) = sTitle
Dim s As Decimal = 0

For i As Integer = 0 To iParms.Count - 1
s = 0
Dim kolumn As Integer = iParms(i)
NewSummaryRow(kolumn) = 666 ' default it

For Each r As System.Data.DataRow In dt.Rows
s += r(kolumn)
Next
NewSummaryRow(kolumn) = s
Next
NewSummaryRow(iCountCol) = "Count:" + dt.Rows.Count.ToString
dt.Rows.Add(NewSummaryRow)
Catch ex As Exception
Diagnostics.Debug.Print("!!!!!!!!!!!!!!!!!! ERROR utils_data.SummaryRow " & ex.ToString())
Return -1
End Try
Return 1
End Function

fix all submit buttons at one swell foop

May 25, 2011

The problem: my users are apparently getting clicky on me and causing multiple additions of data for us. When the application was first developed, we did not bounce-protect the buttons, because it was not a credit-card related application, and we didn’t think about it.

Techniquest you’ll learn:
1) a number of jQuery tricks
2) perhaps more deeply how Asp.Net form submit works (how it passes “event” to the server). We provide a bullet proof function to create the necessary hidden variables and add them to the DOM even if you don’t have any controls set to AutoPostback.

How to try this yourself:
ASPX and in-line Javascript
screen capture of my html
safeSubmit.js file
* we bind a javascript click event to every submit button in the current page (we’re thinking to plug this into our master page to fix the entire project)
* set_event_hidden_vars – creates EVENTTARGET and EVENTCOMMAND if they don’t already exist
* safe_submit – disables the button and communicates with the user. We put a delay in before the submit because otherwise the user wouldn’t see any of our cosmetic changes to the button.

// purpose - select all the submit buttons, and then bind a safe submit function to them
function bindEvents() {
// get an array of inputs of type submit
var btnArray = $(':submit');

for (var i = 0; i < btnArray.length; i++) {
var btn = btnArray[i];
//use jQuery to get the btn, then call bind
if (btn != null) $(btn).bind("click", safe_submit); // this syntax runs, but it doesn't pass the the this object
}

}

// purpose - if the asp.net hidden vars that simulate events are present, use them.
// otherwise, create them with the correct values
function set_event_hidden_vars(btn) {
var hdn = document.getElementById('__EVENTTARGET');
if (hdn == null) {
var shdn = '';
shdn = shdn.replace('qqq', btn.id);
var h = $(shdn);
$(document.forms[0]).append(h); // my pages are submitting from form[0]
//$('form').append(h);

var scmd = '';
var c = $(scmd);
$(document.forms[0]).append(c);
//$('form').append(c);
}
else hdn.value = btn.id;

}

// purpose - general routine to submit a button but to disable it so we don't get double clicks
function safe_submit(p) {
if (bShowAlerts > 0) alert('safe_submit');
if (p == null) {
alert('p is null');
return false;
}
var btnArray = $(this);
var btn = btnArray[0];
if (btn != null) {
// show the user that the button has changed
// $(btn).hide('slow'); // this worked
//$(btn).css("background-color", "green");
$(btn).css("border-color", "white");
$(btn).css("foreground-color", "white");
$(btn).val("Please wait a bit ...");
btn.disabled = true;

if (bShowAlerts > 0) alert('safe_submit ' + btn.id)

// the hidden vars communicate with the server
set_event_hidden_vars(btn)

setTimeout(submit_after_delay, 500);

}
else {
alert('the button was null');
return false;
}

}

function submit_after_delay() {
document.forms[0].submit();
}

udf function to return words for money

February 14, 2011

We started using this function because crystal reports has a nice formatting function to do the number to words conversion, but I think that Microsoft SQL Reporting doesn’t have such a function.

modified from the original to allow billions and also negatives

examples:
SELECT [dbo].[fnMoneyToEnglish] ( -999999999999.12 )
returns
( Nine Hundred Ninety-Nine Billion Nine Hundred Ninety-Nine Million Nine Hundred Ninety-Nine Thousand Nine Hundred Ninety-Nine Dollars and 12 Cents )

SELECT [dbo].[fnMoneyToEnglish] (-10.11)
returns
( Ten Dollars and 11 Cents )


USE [BursarReceipt]
GO

/****** Object: UserDefinedFunction [dbo].[fnMoneyToEnglish] Script Date: 02/14/2011 11:29:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- http://www.sqlusa.com/bestpractices2005/moneyformat/
-- SQL convert dollar amount into words for check printing - Dollars and cents format
-- Convert numbers to words - SQL amount into words - Currency to words
-- SQL money format to English - Translate money to text
-- Translate dollar amount to words - Convert numbers into English words
ALTER FUNCTION [dbo].[fnMoneyToEnglish](@Money AS Money)

RETURNS VARCHAR(1024)

AS

BEGIN
DECLARE @Number as BIGINT
DECLARE @MinusFlag as Bit

if @Money < 0
begin
set @Money = -1 * @Money
Set @MinusFlag = 1
end

SET @Number = FLOOR(@Money)

DECLARE @Below20 TABLE (ID int identity(0,1), Word varchar(32))

DECLARE @Below100 TABLE (ID int identity(2,1), Word varchar(32))

INSERT into @Below20 (Word) VALUES ( 'Zero')
INSERT into @Below20 (Word) VALUES ('One')
INSERT into @Below20 (Word) VALUES ('Two')
INSERT into @Below20 (Word) VALUES ('Three')
INSERT into @Below20 (Word) VALUES ('Four')
INSERT into @Below20 (Word) VALUES ('Five')
INSERT into @Below20 (Word) VALUES ('Six')
INSERT into @Below20 (Word) VALUES ('Seven')
INSERT into @Below20 (Word) VALUES ('Eight')
INSERT into @Below20 (Word) VALUES ('Nine')
INSERT into @Below20 (Word) VALUES ('Ten')
INSERT into @Below20 (Word) VALUES ('Eleven')
INSERT into @Below20 (Word) VALUES ('Twelve')
INSERT into @Below20 (Word) VALUES ('Thirteen')
INSERT into @Below20 (Word) VALUES ('Fourteen')
INSERT into @Below20 (Word) VALUES ('Fifteen')
INSERT into @Below20 (Word) VALUES ('Sixteen')
INSERT into @Below20 (Word) VALUES ('Seventeen')
INSERT into @Below20 (Word) VALUES ('Eighteen')
INSERT into @Below20 (Word) VALUES ('Nineteen')

INSERT into @Below100 (Word) VALUES ('Twenty')
INSERT into @Below100 (Word) VALUES ('Thirty')
INSERT into @Below100 (Word) VALUES ('Forty')
INSERT into @Below100 (Word) VALUES ('Fifty')
INSERT into @Below100 (Word) VALUES ('Sixty')
INSERT into @Below100 (Word) VALUES ('Seventy')
INSERT into @Below100 (Word) VALUES ('Eighty')
INSERT into @Below100 (Word) VALUES ('Ninety')

DECLARE @English varchar(1024)
(
SELECT @English =
Case

WHEN @Number = 0 THEN ''

WHEN @Number BETWEEN 1 AND 19

THEN (SELECT Word FROM @Below20 WHERE ID=@Number)

WHEN @Number BETWEEN 20 AND 99

-- SQL Server recursive function

THEN (SELECT Word FROM @Below100 WHERE ID=@Number/10)+ '-' +

dbo.fnMoneyToEnglish( @Number % 10)

WHEN @Number BETWEEN 100 AND 999

THEN (dbo.fnMoneyToEnglish( @Number / 100))+' Hundred '+

dbo.fnMoneyToEnglish( @Number % 100)

WHEN @Number BETWEEN 1000 AND 999999

THEN (dbo.fnMoneyToEnglish( @Number / 1000))+' Thousand '+

dbo.fnMoneyToEnglish( @Number % 1000)

WHEN @Number BETWEEN 1000000 AND 999999999

THEN (dbo.fnMoneyToEnglish( @Number / 1000000))+' Million '+

dbo.fnMoneyToEnglish( @Number % 1000000)

WHEN @Number BETWEEN 1000000000 AND 999999999999

THEN (dbo.fnMoneyToEnglish( @Number / 1000000000))+' Billion '+

dbo.fnMoneyToEnglish( @Number % 1000000000)

ELSE ' INVALID INPUT' END

)

SELECT @English = RTRIM(@English)

SELECT @English = RTRIM(LEFT(@English,len(@English)-1))

WHERE RIGHT(@English,1)='-'

IF @@NestLevel = 1

BEGIN

SELECT @English = @English+' Dollars and '
SELECT @English = @English+
convert(varchar,convert(int,100*(@Money - @Number))) +' Cents'
if (@MinusFlag = 1)
begin
set @English = '( ' + @English + ' )'
end

END

RETURN (@English)

END

GO

Unit testing with web services

June 17, 2010

I’m currently using visual studio 2008 unit testing to develop a class library, and into the library I put one of my classes that calls a web service. So I added a service reference to the class library.

But when I tried to test something that intantated the web service client, I kept getting weird errors as I ran the unit test.

It turns out that when I copied the app.config from the class library that included the web service definitions into the app.config of the unit testing project, the error went away. I’m not sure why the debugging project needs to have the service definitions.

WPF databinding

June 16, 2010

ok, so I never got the databinding to work quite right between my listbox and the various add,update,delete operations I was doing with Linq to SQL.

However, I did get it all to look good, with the listbox getting updated, and this is how I did it.

The magic function was: GetNewBindingList called from my linq table object.

Somehow it feels like the linq to sql class should inform the listbox that it needs to refresh and there should be some magic setting, but for the time being:
XAML extract:

set the datasource in the window:
<Window x:Class="HomerV3_Queries.Window_Queries"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
bind to it at the listbox. "Queries" is the table I'm binding to.:
ItemsSource="{Binding Path=Queries,UpdateSourceTrigger=PropertyChanged}"

C# code called after every database change – note the commented out stuff that does not work:

void PageRefresh()
{
//_context.SubmitChanges();

//_context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, _context.Queries);
//lbQueries.UpdateLayout();
//lbQueries.ItemsSource = null;
//lbQueries.Items.Clear();
lbQueries.ItemsSource = _context.Queries.GetNewBindingList();
//lbQueries.Refresh();
lbQueries.SelectedIndex = -1;
txtQuery.Text = "";
txtTitle.Text = "";
}

sharepoint 2010 just installed

June 9, 2010

why should I feel such a sense of triumph at finally getting this to work on my windows 7 laptop? Probably I had made some mistakes along the way – notably when I installed sql server enterprise on top of developer, and then applied the wrong file for the service pack 1 for about a week.

I think it was a little weird that installing the identity framework did not work, but installing Geneva did (I had never previously installed Geneva, so perhaps the identity service pack wasn’t doing anything for me).

The best resource (in addition to the msdn doc on how to install 2010) is probably the Rehman Gul blog post titled “Sharepoint 2010 Configuration Wizard Errors on Windows 7″.

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
set_url_for_session(sSession)
'handle_load_gridview_for_session(Me.gvResult, sSession)
End Sub

'http://forums.asp.net/p/1315610/2601836.aspx
'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)
Response.End()
'HttpContext.Current.RewritePath(sPath, True, sQuery)
End Sub


Follow

Get every new post delivered to your Inbox.