How do I use Refelection to get names and values of an object

 

Function GetWODataAsMessage(WO AsInteger) AsString

‘#1446
SetContext()

Dim result = (From w In context.WorkOrders Where w.WO = WO Select w).FirstOrDefault

If result IsNothing Then

Return String.Concat(“WO, “, WO, ” was not found”)

EndIf

Dim msg = String.Concat(“Information for W-“, WO)

ForEach prop In result.GetType().GetProperties

If prop.CanRead Then

SelectCase prop.PropertyType

CaseGetType(Byte()), GetType(Business.EBC.EntityModel.Product)

‘Do Nothing

‘Case GetType(Business.EBC.EntityModel.Product)

‘ ‘Do Nothing

Case Else

Dim Tabs = String.Concat(vbTab, vbTab)

If prop.Name.Length < 4 Then

Tabs = String.Concat(vbTab, vbTab, vbTab)

ElseIf prop.Name.Length > 16 Then

Tabs = vbTab

EndIf

‘, prop.PropertyType ‘Testing only

msg = String.Concat(msg, vbCrLf, prop.Name, Tabs, prop.GetValue(result, Nothing))

End Select

EndIf

Next

Return msg

End Function

How do I … modify the appearance of a Windows.Forms.TableLayoutPanel at run-time

http://social.msdn.microsoft.com/Forums/en-US/vbpowerpacks/thread/ad57487d-d7e0-4131-a388-cc3815809033/

The following adjusts the column width

Me.TableLayoutPanel1.ColumnStyles(0).Width = 10.0

The following gets the actual control. Making this invisible, leaves the table cell in place, same size.

Me.LayoutPanelGraph.GetControlFromPosition(colIndex, rowIndex).Visible = False

In my own code this is seen in SRS.Windows.Forms.ListBoxFilter

LINQ and Entity Framework with DbContext – Convert Anonymous type to Strongly Typed – Bind to ListBox

[ Personally I have a sample of this in EFSample1.sln ]
To convert anonymous type to strongly typed, you can add a class that does what you want, then Select New … with {.ID = …}
This allows you to say get data from more than one table and still have a strongly typed output. Will not be updateable.

To fill a ListBox use

Imports System.Linq ‘if namespace not already imported

See http://wp.me/p17IS4-9S

Dim result = …GetEmployees
ListBox.DataSource = result.ToList

To save on setting the DisplayMember use .ToString in the class

Public Class EmployeeList
Property ID As Integer
Property FullName As String

Overrides Function ToString() As String
Return FullName
End Function

End Class

Public Class EmployeeEF

Private context As New EFWinFormsDBContext.TestEFIEntities

Function GetEmployees() As System.Linq.IQueryable(Of EmployeeList)

Dim result = From emp As Employee In context.Employees Join con As Contact In context.Contacts On emp.EmployeeID Equals con.ID Order By con.FullName
Select New EmployeeList With {.ID = emp.EmployeeID, .FullName = con.FullName}

Return result

End Function

End Class

How do I … create a Custom DataGridViewColumn and DataGridViewCell

Uses may include:

  • Storing extra data in a cell
  • Controlling SortMode for all columns
Public Class DataGridViewPlanColumn
    Inherits DataGridViewTextBoxColumn

    Sub New()
        Me.CellTemplate = New DataGridViewPlanCell
        Me.SortMode = DataGridViewColumnSortMode.NotSortable
    End Sub

End Class

Public Class DataGridViewPlanCell
    Inherits DataGridViewTextBoxCell

    Property WO As Nullable(Of Integer)
End Class

How do I … use Reflection to build a project that will inspect/analyse other assemblies

For instance:

  • My preference is that TableAdapters are not in the component tray of forms, but ideally in a DAL, or if not that good then in a using part of the forms code. I have always struggled to find these. I want a Reflection utility that will find these

Key reflection code snippets to do this are:

How do I … use reflection to load an Assembly at runtime

Dim asm = System.Reflection.Assembly.LoadFrom(AssemblyFileName)

or

Dim asm = System.Reflection.Assembly.GetExecutingAssembly

How do I … loop around forms of a Loaded assembly

ForEach t1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

Me.ListBox1.Items.Add(String.Concat(t1.Name))

Next

How do I … loop around forms and GetFields

For Each f1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

For Each prop In f1.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).Where(Function(f) f.Name.ToLower.Contains(FieldName))

Me.ListBox1.Items.Add(String.Concat(f1.Name, “: “, prop.Name, “: “, prop.FieldType.Name))

Next

Next

 

How do I .. use Reflection to get the values of an Enum at runtime

Thanks to:
http://www.vb-helper.com/howto_net_list_enum.html

Module Module1

Sub Main()

ForEach field As System.Reflection.FieldInfoInGetType(TestEnum).GetFields.Where(Function(f) f.IsLiteral)
  ‘Console.WriteLine(field.Name + vbTab + CInt(field.GetValue(Nothing)).ToString)
  Console.WriteLine(CInt(field.GetValue(Nothing)).ToString + ” “ + field.Name)
Next
Console.ReadLine()

End Sub

End Module

Public Enum TestEnum
  Cheese = 1
Wallace
Grommit
Wheelbarrows
End Enum

LocalReport set-up and publish

How do I … keep reports in a sub-directory

May be set in code or in ReportViewer control

Dim report as New LocalReport()
report.ReportPath = “Reports\ReportName.rdlc”

How do I … fix Local reports that work in Visual Studio not when published

The errors you may get include:

  • An error occurred during local report processing copy
    The report definition for report ‘..\some_path_to_report\<reportname>.rdlc’ has not been specified
    Could not find file ‘C:\inetpub\wwwroot\some_path_to_report\tse.rdlc’.

When reports are added their default Build Action is Embedded Resource.
To fix this change to Content and choose a copy policy, probably Copy if Newer

How do I … use a report in a referenced project

Add the report as a “Linked” file ( Add existing item > Add as Link )(probably) at the same directory level as in the referenced project
Then on these linked files choose the necesary options as above

How do I … directly printing a project report.rdlc in VB.Net without previewing first

Also see next blog entry

Steps

  1. Imports System
    Imports System.IO
    Imports System.Data
    Imports System.Text
    Imports System.Drawing
    Imports System.Drawing.Imaging
    Imports System.Drawing.Printing
    Imports System.Collections.Generic
    Imports System.Windows.Forms
    Imports Microsoft.Reporting.WinForms
  2. Load data as usual
  3. Dim report as New LocalReport
    report.ReportPath = “<ReportName>.rdlc”
    or
    report.ReportPath = “Reports\<ReportName>.rdlc
    report.DataSources.Add(New ReportDataSource(“dtRouteCardWO”, CType(Me.DsRouteCard1.RouteCardWO, DataTable)))
    Export(report)
    Print()
  4.     Private Sub Export(ByVal report As LocalReport)
            ‘MsgBox(“Start of Export”)   ‘Reaches this line on EBC Rise TS
            ‘then before “End of Export” get “Error occurred during local report processing”        Dim deviceInfo = “<DeviceInfo>” & _
                “<OutputFormat>EMF</OutputFormat>” & _
                “<PageWidth>8.3in</PageWidth>” & _
                “<PageHeight>11.7in</PageHeight>” & _
                “<MarginTop>0.25in</MarginTop>” & _
                “<MarginLeft>0.25in</MarginLeft>” & _
                “<MarginRight>0.25in</MarginRight>” & _
                “<MarginBottom>0.25in</MarginBottom>” & _
                “</DeviceInfo>”
            Dim warnings As Warning() = Nothing
            m_streams = New List(Of Stream)()

            ‘See my blog. For this to work the Build Action must be changed from Embedded Resource to Content and a Copy policy chosen
            ‘For this to work from a different project. Add this file as a link in that project and then do above on linked file.
            report.Render(“Image”, deviceInfo, AddressOf CreateStream, warnings)
            For Each stream As Stream In m_streams
                stream.Position = 0
            Next

            ‘MsgBox(“End of Export”)
        End Sub

  5.     Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As System.Text.Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
            Dim stream As Stream = New MemoryStream()
            m_streams.Add(stream)
            Return stream
        End Function
  6.     Private m_currentPageIndex As Integer
        Private m_streams As IList(Of Stream)
  7.     ‘ Handler for PrintPageEvents
        Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
            Dim pageImage As New Metafile(m_streams(m_currentPageIndex))        ‘ Adjust rectangular area with printer margins.
            Dim adjustedRect As New Rectangle(ev.PageBounds.Left – CInt(ev.PageSettings.HardMarginX), _
                                              ev.PageBounds.Top – CInt(ev.PageSettings.HardMarginY), _
                                              ev.PageBounds.Width, _
                                              ev.PageBounds.Height)

            ‘ Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect)

            ‘ Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect)

            ‘ Prepare for the next page. Make sure we haven’t hit the end.
            m_currentPageIndex += 1
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
            ev.HasMorePages = False ‘#1074 srs fudge. Routecard was on 2 pages, should always be 1
        End Sub

        Private Sub Print()
            ‘MsgBox(“Start of Print”)
            If m_streams Is Nothing OrElse m_streams.Count = 0 Then
                Throw New Exception(“Error: no stream to print.”)
            End If
            Dim printDoc As New PrintDocument()
            If Not printDoc.PrinterSettings.IsValid Then
                Throw New Exception(“Error: cannot find the default printer.”)
            Else
                AddHandler printDoc.PrintPage, AddressOf PrintPage
                m_currentPageIndex = 0
                printDoc.Print()
            End If
            ‘MsgBox(“End of Print”)
        End Sub

  8.     Public Shadows Sub Dispose() Implements IDisposable.Dispose
            If m_streams IsNot Nothing Then
                For Each stream As Stream In m_streams
                    stream.Close()
                Next
                m_streams = Nothing
            End If
        End Sub

Troubleshooting

  1. An error occurred during local report processing copy
    The report definition for report ‘..\some_path_to_report\<reportname>.rdlc’ has not been specified
    Could not find file ‘C:\inetpub\wwwroot\some_path_to_report\tse.rdlc’.
  2. Could not find file ‘C:\inetpub\wwwroot\some_path_to_report\tse.rdlc’.

VB.Net or SSRS code for Ordinal Numbers

Easily found on web. See example in SRS.ReportingServices.Functions and also in my invoice report.
With acknowledgement to:
http://www.jigsawboys.com/2010/03/04/ordinal-number-in-reporting-services/

Public Function FormatOrdinal(day as Integer) As String
  SELECT CASE (day Mod 100)
    CASE 11,12
    CASE 13
      Return day.ToString() + “th”
  END SELECT

  SELECT CASE day Mod 10
    Case 1
      Return day.ToString() + “st”
    Case 2
      Return day.ToString() + “nd”
    Case 3
      Return day.ToString() + “rd”
    Case Else
      Return day.ToString() + “th”
  END SELECT
End Function

Good luck!

SSRS Adding Code and also custom assemblies to reports

How to add Code to SSRS reports

  1. Right click on report > Code > Type code as Visual Basic function
  2. In expressions within a data region use Code.<functionname> e.g. =Code.OrdinalFunction(4)

Code for Ordinal Number readily avialable on web. Example use in SRS.ReportingServices.Functions and also in my invoice report

How to add custom assemblies to SSRS reports

  1. Create a class library project in Visual Studio VB.Net or C#
  2. Use a meaningful assembly name e.g. <initials>.ReportingServices.Functions
  3. Add a class and methods to this class. Make the methods shared
  4. Compile to create a dll
  5. Copy the dll to the equivalent location of:
    C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies
    You may not need the (x86) and you may be on a lower or higher version than 9.0
  6. In VS BIDS report right click > report properties > References > Add the reference
  7. In expressions in a report use full Namespace.ClassName.FunctionName(variables)

Next deploying the assembly to the report server

  1. Copy your DLL to the following location or equivalent:
    C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\bin

Good luck. Acknowledgments to:

http://www.devx.com/codemag/Article/33656/0/page/3