Tuesday, March 20, 2012

VB.NET - Office (Word, Excel...) - RPC Server Error

In my application I would seem to randomly get errors that would say something like:


  • The server threw an exception. (Exception from HRESULT ... (RPC_E_SERVERFAULT))
  • The RPC server is unavailable. (Exception from HRESULT ...)

I could not discover the root of the problem nor a solution. I found out this issue is typically caused by Microsoft Word (or whichever Office application) not closing correctly. If you interrupt it while running a process and then try to open a specific file again an error may occur.  Furthermore this happens when you open multiple instances of Word opening, closing, and running at the same time.  The instances of Word will attempt to "piggyback" off one another. When one instance closes but another attempts to run a process, the error is generated.

To solve this issue at the root of the problem you will need to make sure you are instantiating instances of word that are isolated from each other.

If you have done this, another possible source of the error is that you need to enable a template or document that was disabled.

To correct this you need to enable the file that is causing the problem because it has become disabled.  Open Microsoft Word (or other Office application), click the office button, click "Word Options". Then under "Add-Ins", click the "Manage" dropdown list and select "Disabled Items". Click "go". Select any items that are disabled and then click "Enable".

Try running your application again and it should work now.

If not, the RPC error is being caused by something else now.

C# - Maintain Position on DataGridView After Column Sort



The following code handles the situation when the user is in a DataGridView and they sort a column while scrolled over.   By default, if the user sorts the column it will snap the user back over to the left. This code will allow the user to maintain the position they are in.  First whenever the scroll event is activated, a modular level variable stores the stop position of the horizontal scroll bar.  Whenever a user sorts a column in the grid the horizontal scroll bar position is set to the modular level variable that was set in the prior event.



int  _cintHorizontalStop;
private void Grid_Scrolled(object sender, ScrollEventArgs e)
{
     
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
     {
          
 _cintHorizontalStop = e.NewValue;
     }
}
private void Grid_Sorted(object sender, EventArgs e)
{
     datagridview1.
HorizontalScrollingOffset =  _cintHorizontalStop ;
}

Wednesday, March 14, 2012

VB.NET - Maintain Position on DataGridView After Column Sort

The following code handles the situation when the user is in a DataGridView and they sort a column while scrolled over.   By default, if the user sorts the column it will snap the user back over to the left. This code will allow the user to maintain the position they are in.  First whenever the scroll event is activated, a modular level variable stores the stop position of the horizontal scroll bar.  Whenever a user sorts a column in the grid the horizontal scroll bar position is set to the modular level variable that was set in the prior event.

Private _cintHorizontalStop  As Integer '<-- modular level variable



Private Sub datagridview1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles  datagridview1 .Scroll
        Try
            If e.ScrollOrientation = ScrollOrientation.HorizontalScroll Then
                  _cintHorizontalStop   = e.NewValue
            End If
        Catch ex As Exception
            ErrorHandlerMuni(ex)
        End Try
    End Sub


    Private Sub  datagridview1 _Sorted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  datagridview1 .Sorted
        Try
            gridDGV.HorizontalScrollingOffset = _cintHorizontalStop  
        Catch ex As Exception
            ErrorHandlerMuni(ex)
        End Try
    End Sub

Tuesday, March 13, 2012

VB.NET - String Incrementer (For Loops With Excel)


If you need a function that will increment a string, in particular to put in a loop that goes through columns in excel, here is what you are looking for.


I’m using it to increment a string (my purpose is to move through the columns in excel a -> b ; b -> c ; and so on.  But then what is also does, it will go from z -> aa ; so it can be used to loop through columns that go past the column z.





''' <summary>
    ''' jefz - function is to be used to increment a string character.  When the string reaches Z it will start
    ''' counting again from AA. Primary purpose is to be used as a counter for referencing excel cells going across
    ''' the worksheet.
    '''
    ''' Ex:  A   ->  B
    '''      M   ->  N
    '''      Z   ->  AA
    '''      AM  ->  AN
    '''      AZ  ->  BA
    '''      ZZ  ->  AAA
    ''' </summary>
    ''' <param name="strString">letter to start incrementing (must be in lowercase)</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function IncrementString(ByRef strString As String) As String

        Dim intLenString As Integer
        Dim strChar As String
        Dim intI As Integer

        intLenString = Len(strString)

        ' Start at far right
        For intI = intLenString To 0 Step -1

            ' If we reach the far left then add an A and exit
            If intI = 0 Then
                strString = "a" & strString
                Exit For
            End If

            ' Consider next character
            strChar = Mid(strString, intI, 1)
            If strChar = "z" Then
                ' If we find Z then increment this to A
                ' and increment the character after this (in next loop iteration)
                strString = Microsoft.VisualBasic.Left$(strString, intI - 1) & "a" & Mid(strString, intI + 1, intLenString)

            Else
                ' Increment this non-Z and exit
                strString = Microsoft.VisualBasic.Left$(strString, intI - 1) & Chr(Asc(strChar) + 1) & Mid(strString, intI + 1, intLenString)
                Exit For
            End If

        Next intI

        IncrementString = strString
    End Function

Monday, March 12, 2012

VB.NET - Changing Application Icon

If you want to change the icon for your application, the first thing everybody will want to do is go into the properties of the project and change the icon associated with the program under the 'Application' tab. This is good except to also get the new icon to appear on each of the forms and in the task bar of windows, you will need to go to the properties window for each of the forms you want to associate the icon with. Within the properties window the form, go to the 'Icon' property and also set the icon there.  You should now get the icon to show on the upper left of the form as well as in the task bar.

Monday, March 5, 2012

VB.NET - Check to see if "X" Button was Clicked

If you want to be able to check if the red "X" button was clicked on the form, you must add this code to the code of the main form:





Private Const WM_SYSCOMMAND As Int32 = &H112
    Private Const SC_CLOSE As Int32 = &HF060
    '*Do not try to step into this procedure, once you're in, you're usually stuck.
    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = WM_SYSCOMMAND Then
            Select Case m.WParam.ToInt32()
                Case SC_CLOSE
                    'MsgBox("Form gets closed.")
                    cGenBlnClickedX = True
            End Select

        End If
        MyBase.WndProc(m)
    End Sub



I use this code with my DataGridView validation.  I have row validation with my DataGridView, however if the user clicks the "X" button I do not want my grid to go through validation so I have the following code inside of a function to check to see if validation is needed when entering the RowValidating event handler:


If cGenBlnClickedX = True Then
                Exit Function
            End If





*Note about this code - when stepping through code this will appear to show up at random times.  You cannot step line by line your way out of it.  There are a few tricks to getting around this. 1) the easiest thing to do is instead of stepping line by line, "step out" of the function and you will continue on as usual. 2) when debugging, comment this code out and then put it back in when done debugging. 3) you can go to the line of code you were on before you stepped into this code.  Go to the line of code after it and "run to cursor"