Results 1 to 5 of 5

Thread: Customizing My.Namespace

  1. #1

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Customizing My.Namespace

    The following focuses on one idea for reducing the amount of code you type, centralizing code used often in development of solutions and to expose functionality within the .NET Framework that is rarely used but when needed, is needed now.

    One of the most common thing we do with users is to communicate with them using dialogs such as MsgBox which works great for most of the time yet can fall short say if you need ask a question and want the NO button as the default button which means you need the MessageBox class. The problem with the MessageBox is that by the time you are finished constructing a dialog it is a long line of code and you need to repeat it over and over again or place the code in a module and go from there.

    One possible method to assist in the above is to extend My Namespace.

    MSDN http://msdn.microsoft.com/en-us/library/bb531245.aspx
    The My namespace in Visual Basic exposes properties and methods that enable you to easily take advantage of the power of the .NET Framework. The My namespace simplifies common programming problems, often reducing a difficult task to a single line of code. Additionally, the My namespace is fully extensible so that you can customize the behavior of My and add new services to its hierarchy to adapt to specific application needs. This topic discusses both how to customize existing members of the My namespace and how to add your own custom classes to the My namespace.

    So instead of the following
    Code:
    If Windows.Forms.MessageBox.Show("Your question", "Question", _
                                     Windows.Forms.MessageBoxButtons.YesNo, _
                                     Windows.Forms.MessageBoxIcon.Question, _
                                     MessageBoxDefaultButton.Button2) = _
                                     Windows.Forms.DialogResult.Yes Then
    End If
    By extending My Namespace we could have this.
    Code:
    If My.Dialogs.Question("Your question", "question") Then
    
    End If
    Another tedious message to display is when an exception has to be displayed to users (personally I have a class which handles unhandled exceptions coupled with a replacement for globally handling unhandled exceptions). Take the following example which shows a personal message coupled with the text from the exception.
    Code:
    Try
       DirectCast(sender, ListBox).Items.Add("Ha Ha")
    Catch ex As Exception
       MsgBox(String.Format("I goofed up{0}{1}", _
                            Environment.NewLine, ex.Message))
    End Try
    Again using an extension to My namespace we could wrap this up and also format the dialog as shown below.
    Code:
    Try
       DirectCast(sender, ListBox).Items.Add("Ha Ha")
    Catch ex As Exception
       My.Dialogs.ExceptionDialog("I goofed up", "Oooops", ex)
    End Try
    Another extension included checks against a list to see if the current user is either a tester or developer. When I develop solutions I will place information on the UI but will hide the information from testers and users. A clear and simple example, the design of the solution dictates that the user is prompted Yes/No to leave the application yet I do not want to be asked so the following is used which is an extension of Windows.Forms which uses an extension to My Namespace.

    Code:
    <Runtime.CompilerServices.Extension()> _
    Sub CloseThisForm(ByRef sender As Windows.Forms.Form)
       If My.CurrentUser.IsTester Then
          If My.Dialogs.Question("Close?") Then
             sender.Close()
          End If
       Else
          sender.Close()
       End If
    End Sub
    In the close button of the main form (handling the form’s control box not handled here)
    Code:
    Me.CloseThisForm()
    Another example, you need to display the system up time.
    Code:
    My.Dialogs.InformationDialog(My.Computer _
                                 .SystemUpTime.ToString, "System up time")
    Console.WriteLine(My.Computer.SystemUpTime.ToString)
    Ouputs 08:52:41.7990000
    Or broken down by hour and minutes
    Code:
    Dim UpTime = My.Computer.SystemUpTime
    Console.WriteLine("{0}:{1}", UpTime.Hours, UpTime.Minutes)
    Outputs 8:54
    For me an extension of My Namespace deals with my database, IBM-DB2 where I target a solution for a specific version of IBM Client Access to be pro-active and stop database access before an exception is raised. The following is not included in the attached project.

    Code:
    If My.iSeries.CorrectVersionInstalled Then
        Console.WriteLine("Perform data operations against DB2")
    Else
        Console.WriteLine(My.iSeries.ExceptionMessage)
    End If
    To see if Client Access is installed
    Code:
    My.iSeries.AssemblyExists

    What version is installed
    Code:
    My.iSeries.InstalledVersion
    Any ways the attached project should help you with My.Dialogs for simplifying showing messages to users and also assist with creating your own partial classes and new classes under My.Namespace.
    • Attached project is VS2008, code should work fine in VS2005 although I have not tested under VS2005 so it might need some tweaking.
    • There are more dialogs than discussed here in the attached zip file
    Attached Files Attached Files
    Last edited by kareninstructor; Oct 21st, 2010 at 07:55 AM.

  2. #2

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Customizing My.Namespace

    Perhaps you have some functionality which seems right for My.Computer such as returning a list of installed versions of the Microsoft Framework or simple return the current user’s My Document folder. Both of these are actually easy to write code when needed but at least for me are longer than I want to type. Any ways the attached demonstration project shows demos the following.

    My.Computer.Printers
    Returns a list of all known printers on the current computer

    My.Computer.DefaultPrinterName
    Returns the default printer for the current user

    My.Computer.WindowsFolder
    Install folder for MS-Windows

    My.Computer.MyDocumentsFolder
    Current user's My Document folder

    My.Computer.RuntimeVersions
    List of installed Frameworks

    My.Computer.InternetExplorerInstalled
    Is Microsoft Internet Explorer installed on the current computer

    My.Computer.InternetExplorerExecutable
    Path and executable to fire up IE perhaps with a file

    There are a few other properties added and all the above are demo'd.

    Any ways let's say this is food for thought.
    Attached Images Attached Images  
    Attached Files Attached Files

  3. #3
    Addicted Member vb_ftw's Avatar
    Join Date
    Dec 2010
    Posts
    139

    Re: Customizing My.Namespace

    this is really nice...framework versions is great
    nice job...keep it up

  4. #4

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Customizing My.Namespace

    There are times when a developer wants to change the button labels of a MsgBox or MessageBox regardless of whether this is not the best method to go since the better method is to create a form and adorn it with buttons which set the dialog result. The attached project has three functions callable under a custom My Namespace My.Dialogs. The code to change the button text is from another developer, his name and location of the original code is within the code.

    Display an exceptions style dialog with Ooooops as the single button text
    Code:
          Try
             DirectCast(sender, ListBox).SelectedIndex = 0
          Catch ex As Exception
             Dim Message As String = String.Format("Encountered the following{0}{1}", _
                                                   Environment.NewLine, ex.Message)
             My.Dialogs.ExceptionDialog(Message, "Error", "Ooooops")
          End Try
    Setting button text on the fly for asking a question which returns a Boolean. The text for the buttons is obtained from two TextBoxs. In the function Question there is a check to see if the button text length is greater than 10 and if so truncated which can easily be taken out.
    Code:
          If My.Dialogs.Question("Your Question", "My Title", txtYes.Text, txtNo.Text) Then
             ActiveControl = txtYes
          Else
             ActiveControl = txtNo
          End If
    Ask the user if they want to close a form, with a tad bit of humor.
    Code:
       Private Sub frmMainForm_FormClosing( _
          ByVal sender As Object, _
          ByVal e As System.Windows _
             .Forms.FormClosingEventArgs) Handles Me.FormClosing
    
          e.Cancel = Not _
          My.Dialogs.RedNeckQuestion("Do ja wantta leave dis program", "Da Question")
    
       End Sub
    Attached Files Attached Files

  5. #5

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    My.Culture

    The following provides a new addition for current culture. Feel free to add or remove functions to this class.

    I focused more on date/time but added other elements in too.

    See attached VS2010 project for full source and demo

    Current function list

    AbbreviatedDayNames
    Returns a string array of day names abbreviated

    AbbreviatedMonthNames
    Returns a string array of month names abbreviated

    CurrentDayName
    Returns the name of the current day

    CurrencySymbol
    Returns the char for the currency symbol

    CultureList
    Returns a list suitable for finding specific cultures

    DateSeparator
    Returns the char used to work with date parts

    DayNames
    Returns a string array of fulll day names

    TimeSepartor
    Returns the char used to work with time

    MonthNames
    Returns a string array of full month names

    Source
    Code:
    Namespace My
        <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> _
        Partial Friend Class _Culture
            Public Function DateSeparator() As String
                Return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator
            End Function
            ''' <summary>
            ''' Return the Time Separator for current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function TimeSepartor() As String
                Return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator
            End Function
            ''' <summary>
            ''' Return CurrencySymbol for current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function CurrencySymbol() As String
                Return System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol
            End Function
            ''' <summary>
            ''' Return a string array of Abbreviated Day Names for current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function AbbreviatedDayNames() As String()
                Return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames
            End Function
            Public Function AbbreviatedMonthNames() As String()
                Return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames
            End Function
            ''' <summary>
            ''' Returns a string array of day names for the current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function DayNames() As String()
                Return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames
            End Function
            ''' <summary>
            ''' Returns a string array of month names for the current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function MonthNames() As String()
                Return (From M In System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames Where Not String.IsNullOrEmpty(M)).ToArray
            End Function
            ''' <summary>
            ''' Returns the current month long name for the current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function CurrentMonthName() As String
                Return System.Text.RegularExpressions.Regex.Replace(Now.ToString("y"), "[^A-Za-z\.]", "")
            End Function
            Public Function CultureList() As Globalization.CultureInfo()
                Return (From T In Globalization.CultureInfo.GetCultures(Globalization.CultureTypes.SpecificCultures) Order By T.EnglishName).ToArray
            End Function
            ''' <summary>
            ''' Returns the current long day name for the current culture
            ''' </summary>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public Function CurrentDayName() As String
                Return Now.DayOfWeek.ToString
            End Function
        End Class
        <Global.Microsoft.VisualBasic.HideModuleName()> _
        Friend Module KSG_Culture
            Private instance As New ThreadSafeObjectProvider(Of _Culture)
            ReadOnly Property Culture() As _Culture
                Get
                    Return instance.GetInstance()
                End Get
            End Property
        End Module
    End Namespace
    Attached Images Attached Images  
    Attached Files Attached Files

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width