Monday, May 02, 2005

[itsdifferent] My - Feature in Visual Basic 2005


My Feature in Visual Basic 2005
By Thiru Thangarathinam
 

One of the new features introduced with Visual Basic 2005 is the My namespace. My namespace is aimed at making the common development tasks very easy to perform. Also with the My namespace, the code you write will be much easier to understand and maintain when a new developer looks at it for the first time. For example, prior to .NET, if you want to perform simple file I/O, you need to find your way through the plethora of classes in the System.IO namespace and then figure out the right class that will suit your needs. Now with the introduction of My namespace, all you need to do is to leverage the My.Computer.FileSystem and this will provide you with all the methods needed to perform common file I/O tasks. By this way, developers can easily locate the right classes and methods to perform some common boilerplate code such as invoking Web services referenced by the application, retrieving information about the logged on user, the computer, the application and so on. In this article, we will understand the My namespace support provided by Visual Basic 2005 by looking at the various operations available through the My namespace. Along the way, we will also see some of the new features introduced with the My namespace by looking at examples.

Introduction

The name My might seem odd to some of you at first look, but the My namespace was primarily created to make it easier to execute common code patterns that developers use in .NET applications. By using My, you now have the ability to easily access computer, application, and user information, as well as obtain access to forms, and Web services by writing just a single line of code. It is important to note that the My namespace goes beyond providing speedy access to commonly performed tasks. In some cases, the classes in the My namespace provide more functionality than you easily find by simply searching through the various namespaces that make up the .NET Framework base class library. My also forced Microsoft to think of computer, application, and user as complete entities, and ask questions like "What should you be able to do with a computer?". As a result, the My namespace classes contains methods like Ping that allows you to ping a computer on the network in a single line of code. Functionalities like these, which were only available through the COM libraries or the Win 32 API, are now easily accessible and available through My. My also makes retrieving of settings and resources required by your application a breezy experience.

My Namespace

Note that My doesn't move or replicate the functionality from other namespaces in the .NET base class library, My just provides shortcuts and/or helper functions for access to the functionality. My feature provides rapid access to the classes and methods through the following My classes:

Object Description
My.Application Allows you to access the application information and its services
My.Computer Allows you to access the host computer and its resources, services, and so on
My.Forms Allows you to access all the forms in the current project
My.Log Allows you to access the application log
My.Request Allows you to access the current Web request
My.Resources Allows you to access the resource elements
My.Response Allows you to access the current Web response
My.Settings Allows you to access the user and application level settings
My.User Allows you to access the security context of the logged on user
My.WebServices Allows you to access the XML Web services referenced by the current project

Based on the functionality provided by the My classes, you can classify them in following categories.

  • Easy access of default object instances through My.Forms and My.Namespaces - You can use this approach, for example, to invoke the Web service referenced in your project just by using a single line of code.
  • Easy access to resources and settings through the use of My.Resources and My.Settings classes
  • Performing common tasks using a single line of code through the use of classes such as My.Application, My.Computer, My.Log, and My.User.
  • Easy access to the Request and Response objects in a Web page.

Now that you have seen the My shortcuts, let's look at how My actually reduces code. We will discuss each of the above categories in detail in the next few sections.

Invoking Default Object Instances without creating an Instance of the Class

You can use the My feature to create an instance of a Form or a referenced Web service in the project without even having to create an instance of the class. The My.Forms and My.WebServices objects provide access to forms, data sources, and XML Web services used by your application. They are available through a collection of default instances of each of these objects. One of the advantages of this approach is that the default instance of the class is provided by the runtime and you do not need to declare it and instantiate it using the Dim and New statements. For example, with the previous versions of Visual Basic 2005, you would do something like the following to display a form.

Dim testForm As New Form1
testForm.Show

Now with Visual Basic 2005, you can accomplish the above using a single line of code.

'With My.Forms, you have access to all of the forms in the current project
My.Forms.Form1.Show

The My.Forms object returns a collection of default instances for every Form class that exists in your project. Similarly, My.WebServices provides a default instance of the proxy class for every Web service that you have created a reference to in your application.

Use of My.WebServices

Similar to the My.Forms, the My.WebServices object provides an instance of each Web service referenced by the current project. Each instance is instantiated on demand. You can access these Web services through the properties of the My.WebServices object. Note that the My.WebServices object exposes only the Web services associated with the current project. It does not provide access to Web services declared in referenced assemblies. To access a Web service provided by the referenced assembly, you must use the qualified name of the Web service, in the form <AssemblyName>.WebServiceName.

Now that you have a general understanding of My.WebServices, let us look at an example to understand this.

For the purposes of this example, create a new ASP.NET Web Service named MyExampleWebService. Once the project is created, add a new Web Service named HelloService.asmx. When you create a Web Service through Visual Studio, it will automatically add a test method named HelloWorld, which will look like the following.

<WebMethod()> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

For reasons of brevity, we will just utilize the above HelloWorld method as opposed to creating a new Web method from scratch. Now let us code to access this Web service from a Windows application. To this end, create a new Windows Forms application in Visual Basic 2005 named MyFeature using Visual Studio 2005. Once the project is created, add a new Windows Form named MyWebServiceExample.vb to the project. After that, add a Web Reference to the MyExampleWebService using the Project->Add Web Reference menu. After that, add a command button named btnInvoke to the form and modify its Click event to look as shown below.

Private Sub btnInvoke_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnInvoke.Click
    MessageBox.Show(My.WebServices.HelloService.HelloWorld())
End Sub

Note how the Web service method HelloWorld is invoked in the above code. The call to My.WebServices will return the reference to all the Web Services referenced in the current project. In this case, since the HelloService is already referenced in the current project, you are able to invoke its HelloWorld method without even having to create an instance of the Web service class.

When you first access one of the My.WebServices object's properties, it creates a new instance of the Web service and stores it. Subsequent accesses of that property return that instance of the Web service. You can dispose of a Web service by assigning Nothing to the property for that Web service. The property setter assigns Nothing to the stored value. If you assign any value other than Nothing to the property, the setter throws an ArgumentException exception. You can test whether a property of the My.WebServices object stores an instance of the Web service by using the Is or IsNot operator. You can use those operators to check if the value of the property is Nothing.

Easy Access to Resources and Settings

The My.Resources object provides access to the application's resources and allows you to dynamically retrieve resources for your application. For example, you can access the application's culture-specific resource files from the My.Resources object. The following example sets the icon of the form to the icon named TestFormIcon stored in the application's resource file.

Sub AssignFormIcon()
    Me.Icon = My.Resources.TestFormIcon
End Sub

Similarly, the My.Settings object provides access to the application's settings and allows you to dynamically store and retrieve property settings and other information for your application.

Performing frequently executed Tasks through My Namespace

The three central objects in My namespace that provide access to information and commonly used functionality are My.Application Object, My.Computer Object, and My.User Object. You can use these objects to access information that is related to the current application, the computer that the application is installed on, or the current user of the application, respectively. In the following sections, you will see these classes in action.

Use of My.Application

The properties exposed by the My.Application object return data that is associated only with the current application or the assembly. Note that some members are only available for Windows Forms or console applications and not for Web applications. Also you can't use My.Application to modify system level information from your code. You can only use My to retrieve information about your system such as available memory and so on.

To demonstrate this, add a new Windows form named MyApplicationFeature.vb to our MyFeature project and add a command button and a list box to the form. In the Click event of the command button, add the code shown below.

Private Sub btnGetApplication_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGetApplication.Click
    lstInfo.Items.Add("Assembly Name : " & My.Application.Info.AssemblyName )
    lstInfo.Items.Add("Directory Path : " & _
        My.Application.Info.DirectoryPath)
    lstInfo.Items.Add("Culture : " & My.Application.Culture.ToString())
    lstInfo.Items.Add ("Main Form : " & My.Application.MainForm.Name)
End Sub

In the above lines of code, you are displaying information such as assembly name, directory path, culture, and the form name and so on through the My.Application classes. Running the form will produce the output shown below.

Use of My.Computer

The My.Computer object provides properties for manipulating computer components, such as audio, the clock, the keyboard, the file system, and so on. Note that the properties exposed by the My.Computer object return information about the computer where the application is deployed, as determined at run time. Typically, these data differ from what was available on the development computer. Also it is important to note that some members such as the My.Computer.Audio object are only available for non-server applications.

For the purposes of this example, add a new Windows form named MyComputerFeature.vb to our MyFeature project. Once the form is added, add a command button and a list box control to the form. Modify the click event of the command button to look as shown below:

Private Sub btnGetComputer_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGetComputer.Click
    lstInfo.Items.Add("Computer Name : " & My.Computer.Name)
    lstInfo.Items.Add("Is Network Available : " & _
        My.Computer.Network.IsAvailable)
    lstInfo.Items.Add("Available Physcical Memory : " & _
         My.Computer.Info.AvailablePhysicalMemory)
    lstInfo.Items.Add("Available Virtual Memory : " & _
        My.Computer.Info.AvailableVirtualMemory)
    lstInfo.Items.Add("OS Full Name : " & My.Computer.Info.OSFullName)
    lstInfo.Items.Add("Device Name : " & My.Computer.Screen.DeviceName)
End Sub

As similar to our previous example, this example also retrieves various information about the computer such as name, available physical memory, available virtual memory and so on using the My.Computer classes and displays them in the list box.

The above screenshot shows the output produced by the form. In addition to displaying the computer information, you can also use the My.Computer.Network object to ping a specific computer in the network. To accomplish this, you utilize the Ping method as shown below.

MessageBox.Show(My.Computer.Network.Ping("thiru-server3").ToString())

The Ping method returns true or false depending on if the remote server is available or not.

Use of My feature in a Web Page

In addition to leveraging some of the above-mentioned My features, the most frequent use of My feature in a Web page involves the use of My feature to access the Response and Request objects in a Web page. To demonstrate this, let us create an ASP.NET Web Site named MyFeature using Visual Basic 2005 as the language in Visual Studio 2005. Once the Web site is created, create a new Web page MyExample.aspx. Modify the code in the Web page to look as shown below.

<%@ Page Language="VB" %>
<script runat="server">
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        My.Response.Write("Is user authenticated : " & _
            My.User.IsAuthenticated().ToString() + "<br>")
        My.Response.Write("Current Logged on User Name : " & _
             My.User.Name + "<br>")
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml " >
<head runat="server">
    <title>Use of My Feature</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

The above code is very simple and straightforward. In the Page_Load event, you utilize the My.Response object to write to the browser the details of the currently logged on user. Also the information about the logged on user is retrieved from the My.User object.

If you enable Integrated Windows Authentication on the MyFeature Web site using IIS Manager, here is the output you will get upon requesting the page through the browser.

As demonstrated by the above example, the My feature can also be very handy in developing ASP.NET Web forms with Visual Basic 2005.

Is My Feature available for C# Programmers?

If you are a C# programmer, you might be wondering if you can take advantage of the My feature from C#. The answer to that question depends on the kind of features you want to use from C#. Because most of the functionality contained in My is implemented by types defined in the Microsoft.VisualBasic.dll assembly (which is referenced by default in all of the VB projects). As with any other .NET assembly, you can also reference the Microsoft.VisualBasic.dll assembly from your C# application and start using it. However, the top level glue that brings all the My pieces together is something that's compiler-specific and available only for the VB compiler. Because of this, the C# users won't see this and as a result only some of the My features are available to the C# programmers.

There are two reasons why the top level My feature is compiler-specific:

  • The types exposed through the My feature in a particular project are dependent on the type of the project. For example, a Web service project will have a different My namespace than a WinForms project will. Because of this the top-level definition of My is tightly integrated into the actual building of the project.
  • Also pieces of the My namespace (such as My.Forms) are dependent on objects that are actually a part of the project itself. Thus, the compiler has to specially generate those pieces of the My namespace at compile time.

To summarize, as a C# programmer, there is nothing that prevents you from leveraging the My feature from C# applications except for the fact you need to be aware of the above restrictions imposed by the compiler-specific attributes of the My feature.

Extending My Feature

So far, you have seen how to leverage the existing classes under the My namespace. Now, let us take a look at how to add a completely new object under the My namespace. Suppose you have a global names list and you want to build a class to provide quick access to that name list through a GetNames() method. You can accomplish by creating a NameList class under the My namespace and then exposing the GetNames method as a Shared method.

To demonstrate this, let us add a Web Form named MyExtensionExample.aspx to our existing MyFeature Web site. While adding the Web form, remember to check the Place code in separate file check box in the Add New Item dialog box. This will ensure the creation of a code-behind file named MyExtensionExample.aspx.vb. Once the Web form is added, add a GridView control named NamesView to the Web form. After that modify the code-behind file of the MyExtensionExample.aspx file to look as follows:

Partial Class MyExtensionExample_aspx
    Inherits System.Web.UI.Page
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        NamesView.DataSource = My.NameList.GetNames()
        NamesView.DataBind()
    End Sub
End Class

Namespace My
    Public Class NameList
        Public Sub New()
        End Sub

        Public Shared Function GetNames() As _
             System.Collections.Specialized.StringCollection

            Dim namesList As New _
                System.Collections.Specialized.StringCollection()
            namesList.Add("Peter")
             namesList.Add("John")
            namesList.Add("Charles")
            namesList.Add("Jim")
            Return namesList

        End Function
    End Class
End Namespace

As you can see from the above code, we have extended the My namespace by adding our own class named NameList to it. The NameList class exposes a shared method named GetNames, which returns a collection of names in the form of a StringCollection object.

Inside the Page_Load event, we simply bind the output of the GetNames() method to the GridView control using the following lines of code.

NamesView.DataSource = My.NameList.GetNames()

In the above line of code, note how the GetNames method of the NameList class is invoked through the My feature. Here is the output produced by the page.

That's all there is to adding your own class under the My namespace and making it available through the My feature. The ability to expose your own classes through the My feature can be very handy and useful in scenarios especially when you have a lot of helper classes (that allow you to execute frequently performed tasks using a common method) that you want to make them available to your developers in a easy-to-use manner.

My Feature in Different Types of .NET Projects

You will notice, depending on the type of project you are working on, that My will not behave exactly the same because it is project sensitive. For example, in an ASP.NET application My will not provide information that does not make sense in that runtime environment. This holds true for Windows Forms applications, Console applications, ASP.NET Web applications, and so on. For example, in a Windows Forms application, the My namespace will not expose objects such as Request and Response since it is not applicable in a Windows forms application.

Conclusion

In this article, we demonstrated the different classes and features available through the My namespace. By providing a speed-dial that allows you to more quickly and effectively utilize .NET framework functionalities in your application, the My feature provides huge productivity improvements to .NET developers, specifically for Visual Basic developers.

Source of article : 15 Seconds!

--
Het Waghela
http://hetwaghela.blogspot.com
http://spaces.msn.com/members/hetwaghela

The person who sends out positive thoughts activates the world around him positively and draws back to himself positive results.



Note: This Group is not a Job Searching Group, so please co-operate and dont transfer any kind of job related material across this Group.AnyOne doing so can be banned from the Group
Thanx , Group Co-Ordinators




Yahoo! Groups Links


--
--
Regards...
/*******************************
itsDifferent
http://its-Different.blogspot.com
http://groups.yahoo.com/group/itsdifferent/join
http://groups.msn.com/its-Different/join
http://groups-beta.google.com/group/itsdifferent
*******************************/

No comments: