Friday, November 13, 2009

Get a Weak or Strong DataTable Row from a selected DataGridView row.
 
Private Sub btnGetDataGridViewSelectedRowData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetDataGridViewSelectedRowData.Click
 
        '-----------------------------------------------------------------------------------------------------------------------------------
        'Find the first selected row (should only be zero or one since DataGridView1.SelectionMode = FullRowSelect)
        '-----------------------------------------------------------------------------------------------------------------------------------
        Dim row As Integer = DataGridView1.SelectedRows.Count
        Dim selectedRowCount As Integer = _
        DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
 
        If selectedRowCount <= 0 Then
            MessageBox.Show("First, select a row in the grid above.")
        Else
            '-----------------------------------------------------------------------------------------------------------------------------------
            'Get Weakly Typed DataRow from DataGridView selected Row
            '-----------------------------------------------------------------------------------------------------------------------------------
            Dim myRow As DataRow = DirectCast(DataGridView1.Rows(DataGridView1.SelectedRows(0).Index).DataBoundItem, DataRowView).Row
 
            '-----------------------------------------------------------------------------------------------------------------------------------
            'DataGridView was originally bound to a Strongly Typed DataTable, so get the Strongly Typed DataRow
            '-----------------------------------------------------------------------------------------------------------------------------------
            Dim myStrongRow = CType(myRow, dsStrongDataSet.dtStrongDataTableRow)
 
        End If
 
    End Sub

Monday, November 02, 2009

DataGridView CSV Editor

·          Load CSV File into Dataset -> DataGridView

·          Show cells with Validation Errors with backcolor & tooltip

·          Right-Click cell to correct cell via tooltip

·          Restrict KeyPress Keys

·          Show cell as “edited” via cell backcolor

   

    Public Function GetCSVDataTable(ByVal filePath As String) As DataTable

 

        ' The dataset to return

        Dim dt As DataTable = Nothing

        Try

            '--------------------------------------------------------------------

            ' Create "Excel Like" Column Headers

            '--------------------------------------------------------------------

            Dim columns() As String = {"A", "B", "C", "D", "E", "F", "G", "H"}

 

            '--------------------------------------------------------------------

            ' Create dataset and datatable to hol;d the csv data

            '--------------------------------------------------------------------

            Dim ds As New DataSet

            Dim mTablename As String = "table1"

            ' Add the new Datatable to the DataSet

            ds.Tables.Add(mTablename)

            dt = ds.Tables("table1")

 

            '--------------------------------------------------------------------

            ' Add columns to datatable

            '--------------------------------------------------------------------

            For Each col As String In columns

                Dim added As Boolean = False

                Dim _next As String = ""

                Dim i As Integer = 0

 

                While Not added

                    ' Build the column name and remove any unwanted characters

                    Dim columnname As String = col + _next

                    columnname = columnname.Replace("#", "")

                    columnname = columnname.Replace("'", "")

                    columnname = columnname.Replace("&", "")

                    columnname = columnname.Replace("""", "")

 

                    ' See if the column already exists

                    If Not ds.Tables(mTablename).Columns.Contains(columnname) Then

                        ds.Tables(mTablename).Columns.Add(columnname)

                        added = True

                    Else

                        ' If it did exist then we increment the sequencer and try again

                        i = i + 1

                        _next = "_" + i.ToString()

                    End If

                End While

            Next

 

            '--------------------------------------------------------------------

            ' Open the CSV file with a stream reader

            '--------------------------------------------------------------------

            Dim sr As New StreamReader(filePath)

 

            '--------------------------------------------------------------------

            ' Read the entire CSV string into one big string

            '--------------------------------------------------------------------

            Dim allData As String = sr.ReadToEnd()

 

            '--------------------------------------------------------------------

            ' Split off each CSV row at the Carriage Return / Line Feed

            ' Default line ending in most windows exports

            ' You may have to edit this to match your particular file

            '--------------------------------------------------------------------

            Dim rows As String() = allData.Split(vbCr.ToCharArray)

 

            '--------------------------------------------------------------------

            ' Add each row to the Dataset until _MaxRowsCount met

            '--------------------------------------------------------------------

            Dim rowCount As Integer = 0

            For Each rowValue As String In rows

                rowCount += 1

                If rowCount > Me._MaxRowsCount Then Exit For

                '--------------------------------------------------------------------

                ' Remove quotation field markers

                '--------------------------------------------------------------------

                Dim row As String = rowValue.ToString().Replace("""", "")

 

                '--------------------------------------------------------------------

                ' Split the row at the delimiter

                '--------------------------------------------------------------------

                Dim rowItems As String() = row.Split(",".ToCharArray())

 

                '--------------------------------------------------------------------

                ' set array to Me._MaxColsCount - 1

                '--------------------------------------------------------------------

                ReDim Preserve rowItems(Me._MaxColsCount - 1)

 

                '--------------------------------------------------------------------

                ' Add the rowItems to a new DataSet.DataTable.DataRow

                '--------------------------------------------------------------------

                ds.Tables(mTablename).Rows.Add(rowItems)

            Next

 

            ' Cleanup - Release StreamReader Resources

            sr.Close()

            sr.Dispose()

 

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

        ' Return the imported data

        Return dt

 

    End Function

 

Private Sub ValidateDataInGrid()

 

' cell init

dataGridViewRow.Cells(iCol).Style.BackColor = _colorBackLnum

sb = New StringBuilder

dataGridViewRow.Cells(iCol).ToolTipText = ""

dataGridViewRow.Cells(iCol).Tag = ""

 

' cell rules

If x.Length < 17 Then

              sb.Append("Field is too short must be 17 charaters." + vbCrLf)

dataGridViewRow.Cells(iCol).Style.BackColor = Me._colorErrorManual

              cellErrorCount += 1

ElseIf x.Length > 17 Then

              sb.Append("Field is too long must be 17 characters." + vbCrLf)

              dataGridViewRow.Cells(iCol).Style.BackColor = Me._colorErrorManual

              cellErrorCount += 1

End If

 

' cell right-clickable error

If compareDtPointer < _CompareDt.Rows.Count Then

              Dim lnumber = _CompareDt.Rows(compareDtPointer)("Field").ToString.Replace("-", "").ToUpper

              If x.ToUpper <> lnumber Then

                     sb = New StringBuilder

                     sb.Append("Right click to change Field to " + lnumber + "." + vbCrLf)

                     cellErrorCount += 1

                     dataGridViewRow.Cells(iCol).Tag = "rightClickable"

                     dataGridViewRow.Cells(iCol).Style.BackColor = _colorRightClickable

              End If

End If

 

' cell results

dataGridViewRow.Cells(iCol).Value = x

Dim err As String = sb.ToString

If err <> "" Then

       dataGridViewRow.Cells(iCol).ToolTipText = err

End If

 

End Sub

 

    Dim _CellRow As Integer = -1

    Dim _CellCol As Integer = -1

    Private Sub gvCSV_CellMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gvCSV.CellMouseDown

 

        '--------------------------------------------------------------------

        'right mouse click?

        '--------------------------------------------------------------------

        If e.Button = Windows.Forms.MouseButtons.Right Then

            '--------------------------------------------------------------------

            'yes, if right clickable

            '   get column & row of grid cell

            '   Isolate last string from tooltip message:

            '       e.g. "Right click to change Field to L2345678901234567." --> "L2345678901234567"

            '   change cell text to "L2345678901234567"

            '--------------------------------------------------------------------

            Dim col As Integer = e.ColumnIndex

            Dim row As Integer = e.RowIndex

            If gvCSV.Item(col, row).Tag.ToString.ToLower = "rightclickable" Then

                Dim toolTip As String = gvCSV.Item(col, row).ToolTipText.Replace(vbCrLf, "").Replace(".", "")

                Dim toolTipArray As String() = toolTip.Split(" ".ToCharArray)

 

                Dim x As String = toolTipArray(toolTipArray.Length - 1)

                gvCSV.Item(col, row).Value = x

                gvCSV.Rows(row).Cells(col).Style.BackColor = Me._colorEdited

            End If

        End If

 

    End Sub

    Private Sub gvCSV_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gvCSV.CellEnter

        _CellCol = e.ColumnIndex

        _CellRow = e.RowIndex

    End Sub

    Private Sub gvCSV_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles gvCSV.EditingControlShowing

        If Not e.Control Is Nothing Then 'gvCSV.CurrentCell.ColumnIndex = 1 And Not

            Dim tb As TextBox = CType(e.Control, TextBox)

            '---add an event handler to the TextBox control---           

            AddHandler tb.KeyPress, AddressOf gvCSV_KeyPress

            AddHandler tb.TextChanged, AddressOf gvCSV_TextChanged

        End If

 

    End Sub

    Private Sub gvCSV_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gvCSV.KeyDown

        'Nothing to do

    End Sub

    Private Sub gvCSV_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles gvCSV.KeyPress

 

        '--------------------------------------------------------------------

        'Allow only A-Z or Numeric (supress all other keys

        '--------------------------------------------------------------------

        If e.KeyChar Like "[A-z]" Or IsNumeric(e.KeyChar) Then

            e.Handled = False

        Else

            e.Handled = True

        End If

 

    End Sub

    Private Sub gvCSV_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFilePath.TextChanged

        'Nothing to do

    End Sub

    Private Sub gvCSV_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gvCSV.CellEndEdit

        '--------------------------------------------------------------------

        'chane cell backcolor to "Edited"

        '--------------------------------------------------------------------

        If _CellRow <> -1 And _CellRow <> -1 Then

            gvCSV.Rows(_CellRow).Cells(_CellCol).Style.BackColor = Me._colorEdited

            'No!  -> Application.DoEvents()

        End If

    End Sub

 

Wednesday, October 28, 2009

Public Function Convert(ByVal mFile As String, ByVal mTablename As String, ByVal delimiter As String) As DataSet
            ' The dataset to return
            Dim ds As New DataSet

            ' Open the file with a stream reader
            Dim sr As New StreamReader(mFile)

            ' Split the first line into the fields and add to string array called columns
            Dim columns As String() = sr.ReadLine().Split(delimiter.ToCharArray())

            ' Add the new Datatable to the DataSet
            ds.Tables.Add(mTablename)

            ' Cylcle the columns, adding those that do not exist yet and sequencing the ones that do
            For Each col As String In columns
                Dim added As Boolean = False
                Dim _next As String = ""
                Dim i As Integer = 0

                While Not added
                    ' Build the column name and remove any unwanted characters
                    Dim columnname As String = col + _next
                    columnname = columnname.Replace("#", "")
                    columnname = columnname.Replace("'", "")
                    columnname = columnname.Replace("&", "")
                    columnname = columnname.Replace("""", "")

                    ' See if the column already exists
                    If Not ds.Tables(mTablename).Columns.Contains(columnname) Then
                        ds.Tables(mTablename).Columns.Add(columnname)
                        added = True
                    Else
                        ' If it did exist then we increment the sequencer and try again
                        i = i + 1
                        _next = "_" + i.ToString()
                    End If
                End While
            Next


            ' Read the rest of the data in the file
            Dim allData As String = sr.ReadToEnd()

            ' Split off each row at the Carriage Return / Line Feed
            ' Default line ending in most windows exports
            ' You may have to edit this to match your particular file
            ' This will work for Excel, Access etc default exports.
            Dim rows As String() = allData.Split(vbCr.ToCharArray)

            ' Add each row to the Dataset
            For Each rowValue As String In rows

                ' Remove quotation field markers
                Dim row As String = rowValue.ToString().Replace("""", "")

                ' Split the row at the delimiter
                Dim items As String() = row.Split(delimiter.ToCharArray())


                ' Add the item to the dataset
                ds.Tables(mTablename).Rows.Add(items)

            Next

            ' Cleanup - Release StreamReader Resources
            sr.Close()
            sr.Dispose()

            ' Return the imported data
            Return ds

        End Function
Regards

Friday, October 16, 2009

Email Excellence
--------------------------------------------------------
Should I email at all?
--------------------------------------------------------
Is writing a good idea?
Do I need a record?
Write email only as a last resort.
Narrow the distribution to "Needs to know".
--------------------------------------------------------
Plan the Reader Outcomes
--------------------------------------------------------
Define the Parent Decisions / Destinations first
 - reader action    - show up on time
 - reader reaction  - understand the the impact of being late
--------------------------------------------------------
Corporate Rules
--------------------------------------------------------
Business only
Be Professional
Subject to Monitoring
store & retain - 60 days
confidential
--------------------------------------------------------
Outline as map to first Draft
--------------------------------------------------------
Satellite Outline
 - action    - ?
 - reaction  - ?
      main idea
         point
         point
      main idea
         argument
         argument
then sequence the ideas & points
--------------------------------------------------------
After the Outline
--------------------------------------------------------
effective opening
shaping & sequencing complex info
ORSON Template - Top, Middle, Bottom
-  Orient
     -  Subject Line - Project - Task - Action
     -  Connect - remember "X" thing, then connect "X", to "your Purpose"
     -  Purpose
         - State Purpose
           - To Request Action
             - I'm writing/just a note to request/seek assistance/info
           - To Deliver Info / Just Say Something
             - I'm writing/just a note to summarize/outline/detail/let you know/alert/bring attention/ say how much we
           - To Respond to your request
             - I'm writing/just a note to respond to/in response to/re: your request
      - avoid too short of a reply
             - be sure to answer all questions
  - Summary Bullets - used "Headlines!", give different readers "choices"
           - 1
           - 2
           - 3
         - Be Plain
         - Sequence
-  Spellout -
     -  Chunk the items in bullets/blocks
      -  One point at a time, sequenced
        -  1st sentence of paragraph, stick to it
        -  Be effective, make sure reader is impacted
     - 
     - 
-  Nail Down
     -  Emphasize Next Steps
     -  Add some genuine warmth, not insincere
     - 
     - 
Orient the user via effective opening
watch out for stream of conciousness
Write when you are NOT under pressure!
--------------------------------------------------------
Counterproductive Behaviors
--------------------------------------------------------
Vehemence
Strong language
Blaming
Sarcasm or exaggerating for effect
Commenting on someone else's area of expertise
Attributions to Others
Limited Information
 - Do I have whole story?
 - Admit what you do not know
Rumor
Speculation
Violations of individual privacy
The Hero Syndrome
Extended email threads
--------------------------------------------------------
Remove Track Changes
--------------------------------------------------------
copy doc to new doc before sending
--------------------------------------------------------
Writing by Committee
--------------------------------------------------------
Use a white board
One notetaker
Make Satellite Outline

 

Tuesday, September 29, 2009

--------------------------------------------------------------------------------------------------------------------------------
--SQL Server - left join data sums/counts/averages to date range to account for zero days or zero weeks
--use recursive common table expression (CTE) and nested CTEs to accumulate "data dates" over the latest "n" weeks
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------
-- weekly sums/counts/averages
--------------------------------------------------------------------------------------------------------------------------------
declare
@parameterDate asdatetime;
set
@parameterDate ='2/2/2009';--@parameterDate;
declare
@ProjectID asint;
set
@ProjectID = 42;
WITH
DateCTE(WeekStart)AS
)
(SELECTDATEADD(DD, 1 -DATEPART(DW,convert(varchar,@parameterDate,111)),convert(varchar,@parameterDate,111))AS WeekStartUNIONallSELECTDATEADD(DD,-7, WeekStart)AS WeekStart FROM DateCTE WHERE WeekStart <DATEADD(DD, 60, @parameterDate)
--select top 6 WeekStart from DateCTE
,
,
Date6CTE as(SELECTtop 12 WeekStart from DateCTE)Date7CTE as (Select Date6CTE.WeekStart,DatePart(wk, Date6CTE.WeekStart)as Week,DatePart(year, Date6CTE.WeekStart)as WeekYearFROM Date6CTE)
--select * from Date7CTE
,
Date7CTE
DatesSumCTE(WeekStart, Week, WeekYear, ProjectName, ProjectID)as (Selectdistinct .WeekStart,
Date7CTE
.Week,
Date7CTE
.WeekYear,
p
p
.ProjectName, .ProjectIDfrom Date7CTE, Projects AS p where ProjectID = @ProjectID)
--select * from DatesSumCTE
select
CONVERT(VARCHAR(20), DatesSumCTE.WeekStart, 101)as WeekStartXX,CONVERT(VARCHAR,DATEPART(MM, DatesSumCTE.WeekStart))+'/'+
CONVERT(VARCHAR,DATEPART(d, DatesSumCTE.WeekStart))+'/'+
right(CONVERT(VARCHAR,DATEPART(YY, DatesSumCTE.WeekStart)), 2)as WeekStart
,
DatesSumCTE.ProjectName
--, DatesSumCTE.ProjectID
,
COUNT(DISTINCT s.ChildLNumber)ASCount
--, DatesSumCTE.WeekYear
--, DatesSumCTE.Week
--, 'Childs Per Week' as SeriesField
FROM
DatesSumCTE
left
JOIN ParentTable AS r ON DatesSumCTE.ProjectID = r.ProjectID
left
JOIN ChildTable AS s ON s.ParentID = r.ParentID
and
and
and
s.DateProcessed ISNOTNULL s.DateData ISNOTNULLDATEADD(DD, 1 -DATEPART(DW,convert(varchar,s.DateData,111)),convert(varchar,s.DateData,111))= DatesSumCTE.WeekStart
GROUP
BY CONVERT(VARCHAR(20), DatesSumCTE.WeekStart, 101 )
,CONVERT(VARCHAR,DATEPART(MM, DatesSumCTE.WeekStart))+'/'+
CONVERT(VARCHAR,DATEPART(d, DatesSumCTE.WeekStart))+'/'+
right(CONVERT(VARCHAR,DATEPART(YY, DatesSumCTE.WeekStart)), 2)
,
DatesSumCTE.ProjectName
--, DatesSumCTE.ProjectID
--, DatesSumCTE.WeekYear
--, DatesSumCTE.Week
--ORDER BY DatesSumCTE.ProjectName, DatesSumCTE.WeekStart
--------------------------------------------------------------------------------------------------------------------------------
-- daily sums/counts/averages
--------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
--days of week for today's date
-----------------------------------------------------------------------
USE
GO
[dbFAST]
WITH
DateCTE(WeekStart)AS
)
,
(SELECTDATEADD(DD, 1 -DATEPART(DW,convert(varchar,GetDate(),111)),convert(varchar,GetDate(),111))AS WeekStartUNIONallSELECTDATEADD(DD, 1, WeekStart)AS WeekStart FROM DateCTE WHERE WeekStart <DATEADD(DD, 7,GetDate())Date7CTE as(SELECTtop 7 WeekStart from DateCTE)
Select
WeekStart
Date7CTE.WeekStart FROM Date7CTE
-----------------------
2009
2009
2009
2009
2009
2009
2009
-09-13 00:00:00.000-09-14 00:00:00.000-09-15 00:00:00.000-09-16 00:00:00.000-09-17 00:00:00.000-09-18 00:00:00.000-09-19 00:00:00.000
-----------------------------------------------------------------------
--results - daily count by project
-----------------------------------------------------------------------
declare
@parameterDate asdatetime;
set
@parameterDate ='1/3/2009';--getdate();
WITH
DateCTE(DayOfWeek)AS
)
,
,
Date7CTE
(SELECTDATEADD(DD, 1 -DATEPART(DW,convert(varchar,@parameterDate,111)),convert(varchar,@parameterDate,111))AS DayOfWeekUNIONallSELECTDATEADD(DD, 1, DayOfWeek)AS DayOfWeek FROM DateCTE WHERE DayOfWeek <DATEADD(DD, 7, @parameterDate)Date7CTE as (SELECTtop 7 DayOfWeek from DateCTE)DatesDataCTE(DayOfWeek, ProjectName, ProjectID)as (Selectdistinct .DayOfWeek,
p
,
.ProjectName, p.ProjectIDfrom Date7CTE, Projects AS p )EmptyProjectWeekCTE(ProjectID,Count)as
(
DatesDataCTE
select .ProjectID,COUNT(DISTINCT s.DataPoint)ASCount
FROM DatesDataCTEleftJOIN Parents AS r ON DatesDataCTE.ProjectID = r.ProjectID leftJOIN Data AS s ON s.ParentID = r.ParentID and s.DateProcessed ISNOTNULL
andconvert(varchar,s.DateDroppedOff,111)=convert(varchar, DatesDataCTE.DayOfWeek,111)
DatesDataCTE
GROUPBY .ProjectID)
select
CASE
DATEPART(weekday,DatesDataCTE.DayOfWeek)
WHEN 1 THEN'Sunday, '
WHEN 2 THEN'Monday, '
WHEN 3 THEN'Tuesday, '
WHEN 4 THEN'Wednesday, '
WHEN 5 THEN'Thursday, '
WHEN 6 THEN'Friday, '
WHEN 7 THEN'Saturday, '
END
+CONVERT(VARCHAR(10), DatesDataCTE.DayOfWeek, 7)AS [Day Date]
--DatesDataCTE.DayOfWeek,
,
DatesDataCTE.ProjectName
--DatesDataCTE.ProjectID
,
COUNT(DISTINCT s.DataPoint)ASCount
FROM
DatesDataCTE
left
JOIN Parents AS r ON DatesDataCTE.ProjectID = r.ProjectID
left
JOIN Data AS s ON s.ParentID = r.ParentID
and
and
s.DateProcessed ISNOTNULLconvert(varchar,s.DateDroppedOff,111)=convert(varchar, DatesDataCTE.DayOfWeek,111)
where
DatesDataCTE.ProjectID in(select ProjectID from EmptyProjectWeekCTE whereCount> 0)
GROUP
DatesDataCTE
DatesDataCTE
DatesDataCTE
BY .DayOfWeek, .ProjectName, .ProjectID
ORDER
 
BY DatesDataCTE.ProjectName, DatesDataCTE.DayOfWeek

Wednesday, September 02, 2009

Inside MS WSS 3.0 – Pattison & Larson
Chapter 1 – Getting Started
 
·         WSS is a Site Provisioning (Creating) Engine
·         Multiple SQL DBs (2005 / 2000 / Express) store content & configuration data
·         Farm – one or more computers providing WSS to users
·         Configuration DBfarm wide settings
o        Server names
o        User roles
·         Content DBone per WSS Application
o         
·         WSS runs on top of IIS
·         Needs IIS to handle incoming HTTP requests
·         The IIS Default Site has listener that passes HTTP requests to sharepoint/home grown sites
o        Each custom site has
§         Ports
§         IP addresses
§         Host headers
§         Separate security
·         Authentication
·         Authorization
·         Network Settings
·         ISS Site that runs WSS = Web Application
·         WSS Central Administration
o        Can Convert standard site to WSS Site
 
 
WSS Site Collection – formerly called 'Site'
  • Contains WSS Sites
  • A scope of
    • Admin privileges
    • User membership
    • Security Authorization Groups
    • Deploy, Backup & Restore
    • Custom Queries
    • Site Elements
      • E.g. Custom Column
 
WSS Site - formerly called 'Web'
  • Has one Content DB
  • One configuration – users, roles, permissions
  • Users
    • Can inherit from Parent Site
    • Or override
  • Authentication – done by IIS & ASP.NET
  • Authorization – Performed by WSS
  • Site Administrator can
    • Customize Web Part Pages
      • Add, change, delete Web Parts
  • Site User  can
    • Personalize Web Part Pages
      • Add, change, delete Web Parts
 

Friday, August 28, 2009

http://forums.oracle.com/forums/thread.jspa?threadID=685308

select to_char( date '2008-01-04', 'IW' ) from dual

Basically, there are 3 to_char format models to get week number:

* W - week number in a month

* WW - week number in a year, week 1 starts at 1st of Jan

* IW - week number in a year, according to ISO standard -

 

alternative: ROUND(TO_NUMBER(TO_CHAR(datefield,'ddd'))/7)

Wednesday, July 22, 2009

Tuesday, July 21, 2009

-------------------------------------------------------------------------------------------------
Mission turn an 8Gig RAM, quadcore desktop with Vista into a Hyper-V Host
-------------------------------------------------------------------------------------------------

My 8 year old laptop finally died,
so I bought a new 8Gig RAM, quadcore deskdop & 23 inch monitor for under $750 including tax
and will replace/partition Vista Home with Windows Server 2008 +  Hyper V

Goal:
1) VM#1 - Sharepoint / VS 2008 / SQL 2008 Development Server
2) VM#2 - Home PC with MS Office
3) On a "pristene" Host

VM Instances  are

- easier to backup, screw up and recover that host OS Instances
- and they can run concurrently (I need to verify in Hyper-V)

It will take a while.

-------------------------------------------------------------------------------------------------
Installing Windows Server 2008 Enterprise
-------------------------------------------------------------------------------------------------

1) Install Windows Server 2008 Enterprise from DVD
2) Change Time Zone
3) Change Computer name and reboot
4) Enable Internet - Control Panel -> Device Manager
- - a) Under Network Adapters, left click "RealTek - and reinstall driver from Driver_Vista_6225_0720/64
5) Start -> All Programs -> Windows Update

....Standard VGA Graphics Adapter


-------------------------------------------------------------------------------------------------
Installing Windows Server 2008 Hyper-V
-------------------------------------------------------------------------------------------------

Robert J. Shimonski wrote a very useful article at this link.

http://www.virtualizationadmin.com/articles-tutorials/microsoft-hyper-v-articles/installation-and-deployment/installing-windows-server-2008-

hyper-v.html

In order to utilize virtualization you must
1) have a clean install of Windows Server 2008 Enterprise (not Standard)
2) then "Add a Hyper-v role " which will install Hyper-V onto the host machine


 Before I read this article, I got confused and downloaded "Microsoft Hyper-V Server 2008 - English"
 from http://www.microsoft.com/downloads/details.aspx?FamilyId=6067CB24-06CC-483A-AF92-B919F699C3A0&displaylang=en.

 But in a nutshell, just install Windows Server 2008 Enterprise/Standatrd,
 and then add the Hyper-V roles, which will run an installer

Click Start and click to open Server Manager.
Locate the Roles Summary area of the main Server Manager window.
Click Add Roles.
On the Specific Server Roles page click, Add Hyper-V.
Follow the prompts to finish installing the Role and click OK when finished.
then you will be prompted to reboot.

After reboot. Installation continues, then you get a message:
...."additionsal steps are required to run VMs
...."run the Virtual Machine Wizard by opening the Hyper-V role homepage
....in Control Panel -> Administrative Tools -> Server manager."

So now you have your VM manager!

-------------------------------------------------------------------------------------------------
Step 2: Create and set up a virtual machine
-------------------------------------------------------------------------------------------------

http://technet.microsoft.com/en-us/library/cc732470(WS.10).aspx#BKMK_step3

-------------------------------------------------------------------------------------------------
Step 3: getting guest the network connection up and running
-------------------------------------------------------------------------------------------------
thanks to Guy Ellis Rocks

http://guyellisrocks.com/hardware/hyper-v-with-vista-x64-and-ubuntu-linux-desktop-x64/

1) shut down Guest OS
2) close guest vm
3) On Hyper-V, under settings for Guest OS,
add a Legacy Network Adapter and set that to my point to your Virtual Network.
Leave MAC address at Dynamic
and uncheck the "Enable virtual Lan identification" check box.
4) power up Guest OS
5) test internet


 

Tuesday, July 14, 2009

*********************************************
Find Orphaned records - on n columns
*********************************************

Example below has two tables: GrantProjectDates  & GrantProjectDollars

related key columns:  GrantId, CountryCode, ProjectId

The tables are loaded from teo excel worksheets , so there are lots of holes in the data,
so ading foreign keys on the related key columns is not helpful,

each table has an IdentiyColumn "id"
 


*********************************************
Orphaned GrantProjectDates 
*********************************************

select * from GrantProjectDates where id in (
select id from (
select da.Id, da.GrantId, da.excelRow, da.CountryCode, da.ProjectId, do.GrantId, do.CountryCode, do.ProjectId
FROM GrantProjectDates da
left join GrantProjectDollars do
on da.GrantId = do.GrantId
and da.CountryCode = do.CountryCode
and da.ProjectId = do.ProjectId
where do.GrantId is null
or do.CountryCode is null
or do.ProjectId is null))
 and Obsolete = false
order by id

*********************************************
Conversely,  Orphaned GrantProjectDollars
*********************************************
select * from GrantProjectDollars where id in (
select id from (
select do.Id, do.GrantId, do.excelRow, do.CountryCode, do.ProjectId, da.GrantId, da.CountryCode, da.ProjectId
FROM GrantProjectDollars do
left join GrantProjectDates da
on do.GrantId = da.GrantId
and do.CountryCode = da.CountryCode
and do.ProjectId = da.ProjectId
where da.GrantId is null
or da.CountryCode is null
or da.ProjectId is null))
 and Obsolete = false

 

Sunday, June 28, 2009

click-once deployment, xenocode postbuild
> (http://www.xenocode.com/products/postbuild-for-net/) and tortoise svn
> to start with.

Tuesday, May 05, 2009

        protected void Button1_Click(object sender, EventArgs e)

        {

            string executePath = System.Configuration.ConfigurationSettings.AppSettings["executePath"];

            ExecuteCommandSync(executePath);

 

            string resultfilePath = System.Configuration.ConfigurationSettings.AppSettings["filePath"];

 

            this.Label1.Text = System.IO.File.ReadAllText(resultfilePath);

 

        }

        public void ExecuteCommandSync(string executePath)

        {

            try

            {

                System.Diagnostics.Process p = new System.Diagnostics.Process(); // Redirect the output stream of the child process.

                p.StartInfo.UseShellExecute = false;

                p.StartInfo.RedirectStandardOutput = true;

                p.StartInfo.FileName = executePath;

                p.Start(); // Do not wait for the child process to exit before // reading to the end of its redirected stream. // p.WaitForExit(); // Read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();

                p.WaitForExit();

            }

            catch (Exception ex)

            {

                System.Diagnostics.Debug.WriteLine(ex.ToString());

            }

 

        }

Tuesday, April 07, 2009

Mission:  From C#, P/Invoke C++ with callbacks to C#

//-----------------------------------------------------------------------

// inside unmanaged C# code

//-----------------------------------------------------------------------

//-----------------------------------------------------------------------

//delegates - define a signatures for unmanaged c++ code to call

//-----------------------------------------------------------------------

public delegate void MessageReceivedDelegate(

   int param1,

   string messageString,

   int param3,

   int param4,

   int param5);

 

 

public delegate void ExceptionParsedDelegate(

  string exceptionMessage);

 

//-----------------------------------------------------------------------

// P/invoke mapping with pointers to delegated methods

//-----------------------------------------------------------------------

[DllImport("my.dll"

   , CallingConvention = CallingConvention.StdCall)]

public static extern void an_unmanaged_function(

   string aa,

    int bb,

    string cc,

    string dd,

    int ee,

    int ff,

    MessageReceivedDelegate call,

    ExceptionParsedDelegate exception);

 

 

//-----------------------------------------------------------------------

// perform P/invoke

//-----------------------------------------------------------------------

an_unmanaged_function(  

aa

,bb

,cc

,dd

,ee

,ff

,new MessageReceivedDelegate(OnMessageReceived)

,new ExceptionParsedDelegate(OnExceptionReceived));

 

//-----------------------------------------------------------------------

// delegated methods (called inside unmanaged c++ code)

//-----------------------------------------------------------------------

public void OnExceptionReceived(

   string exceptionMessage)

{

 

    //handle exceptionMessage

}

protected void OnMessageParsed(myMessage theMesssage)

{

    //handle theMesssage

}

 

//-----------------------------------------------------------------------

// inside unmanaged c++ code ("my.dll")

//-----------------------------------------------------------------------

 

//define c++ delegate signatures

 

typedef void (__stdcall *callbackDelegatePointer)(

       int param1,

       char message[2100],

       int param3,

       int param4,

       int param5);

typedef void (__stdcall *exceptionDelegatePointer)(

       char* exceptionMessage);

 

//allow p/invoke by delcaring method “extern "C"”

extern "C" __declspec(dllexport)

void __stdcall an_unmanaged_function(

       char *aa,

       int   bb,

       char *cc,

       char *dd,

       int   ee,

       int   ff,

       callbackDelegatePointer onMessageReceived,

       exceptionDelegatePointer onException)

 

//call delegates

onMessageReceived(param1, message, param3, param4, param5);

             

onException("Hello Exception");

 

 

 

 

Mission:  Show elapsed time on a WinfForm in C#

thanks to Mahesh Chand

original article:  http://www.c-sharpcorner.com/UploadFile/mahesh/WorkingwithTimerControlinCSharp11302005054911AM/WorkingwithTimerControlinCSharp.aspx

1) add stop & start buttons and a timer control on a web form

2) put code behind the buttons (below), that consumes the StopWatch class (below)

    public partial class Form1 : Form
    {
        static void Main()
        {
            Application.Run(new Form1());
        }
        public Form1()
        {
            InitializeComponent();
        }

        StopWatch stopWatch = new StopWatch();

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            stopWatch.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            stopWatch.Stop();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lblElapsedTime.Text = stopWatch.GetElapsedTimeString();
        }
    }

    public class StopWatch
    {

        private DateTime startTime;
        private DateTime stopTime;
        private DateTime currentTime;
        private bool running = false;


        public void Start()
        {
            this.startTime = DateTime.Now;
            this.running = true;
        }


        public void Stop()
        {
            this.stopTime = DateTime.Now;
            this.running = false;
        }


        // elaspsed time in milliseconds
        public string GetElapsedTimeString()
        {
            TimeSpan interval;

            if (!running)
                return ""; //interval = DateTime.Now - startTime;
            else
            {
                this.currentTime = DateTime.Now;
                interval = currentTime - startTime;
            }

            int days = interval.Days;
            double hours = interval.Hours;
            double mins = interval.Minutes;
            double secs = interval.Seconds;
            string x = "";
            if (days != 0)
            {
                x += days.ToString() + ":";
            }
            if (hours != 0)
            {
                x += hours.ToString("00") + ":";
            }
            x += mins.ToString("00") + ":";
            x += secs.ToString("00");

            return x;
        }
        public double GetElapsedMilliseconds()
        {
            TimeSpan interval;

            if (running)
                interval = DateTime.Now - startTime;
            else
                interval = stopTime - startTime;

            return interval.TotalMilliseconds;
        }


        // elaspsed time in seconds
        public double GetElapsedTimeSecs()
        {
            TimeSpan interval;

            if (running)
                interval = DateTime.Now - startTime;
            else
                interval = stopTime - startTime;

            return interval.TotalSeconds;
        }
    }

Wednesday, February 18, 2009

 
As .Net Developers we often need to change web.config/app.config settings.  We also need to share web.config/app.config without clobbering each others settings via Visual Source Safe (VSS).
 
There are two kinds of config changes.
 
1.      Changes that you do not want other developers to inherit
a.      Connection string changes or settings values
                                                                                        i.    that do not change the config structure
                                                                                       ii.    that need to vary between developers
 
·         You should:
1.      Point to each config files with Windows Explorer
2.      Uncheck the ReadOnly propery check box to make the file Readable
3.      proceed with your Visual Studio changes to each config files
(OBSERVE that the file will not show as “checked out” from VSS)
4.      be careful when you get the latest of everyting from VSS that you do not overwrite your config files changes
 
2.      New Connection strings or new settings
                                            i.    that do change the config structure
                                           ii.    that every developer needs in their version of config
 
·         for each config file(s) You should:
·     select each config file(s) in Visual Studio Project Explorer
·         right Mouse click -> Get Latest Version
·         overwriting your Readable config file
·         proceed with your Visual Studio changes to config file
·         save the config file
·         test your config file
·         checkin config file
·     email everyone to get latest VSS config structure changes!