Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » Building and using a Class Library in Silverlight 2.0

Building and using a Class Library in Silverlight 2.0

This step by step tutorial shows how to build a class library (DLL) for Silverlight 2.0 using Visual Studio 2008 and C# and how to use it in a client application. First part of this tutorial creates a class library and second part creates a Silverlight Web application that consumes the class library.

Author Rank:
Technologies: .NET 3.0 and 3.5, Database, Silverlight, XAML,Visual C# .NET
Total downloads : 100
Total page views :  6388
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ClassLibraryInSilverlight.zip
 
ArticleAd
Become a Sponsor




This step by step tutorial shows how to build a class library (DLL) for Silverlight 2.0 using Visual Studio 2008 and C# and how to use it in a client application. First part of this tutorial creates a class library and second part creates a Silverlight Web application that consumes the class library.

Part 1. Create a Silverlight Class Library

In the first part, we will create a class library for Silverlight. This library will have some mathematical function including random number generator, addition, power, and square root.

Step 1. Create a Silverlight Class Library Project

Select New Project menu item in Visual Studio 2008 and select Visual C# or Visual Basic .NET in the left side project types and Silverlight Class Library in the right side templates. At the bottom of the dialog, enter your class library name and click OK button. I give my class library name SilverlightMathLibrary as you can see in Figure 1.

Figure 1. Create a Silverlight Class Library project

Clicking OK button will create a class library for you and bring you in the code editor and class called Class1.  First thing I do is change class name from Class1 to McMathLibrary.

    public class McMathLibrary

    {

        public string AddString(string firstString, string secondString)

        {

            return firstString + ", " + secondString;

        }

    }

Step 2. Adding Class Library Methods 

Now, there are two ways to add class library properties and methods – by hand or using the Visual Studio 2008 designer. If you are an expert programmer, you can start adding your code to the class by hand. But if you are not an expert programmer, designer is a big help.

Here is an example of me adding a method AddString to the class library by hand.

namespace SilverlightMathLibrary

{

    public class Class1

    {

        public string AddString(string firstString, string secondString)

        {

            return firstString + ", " + secondString;

        }

    }

}

 

Now let’s see how we can use the designer.

First, you need to click on View Class Diagram button in the Solution Explorer. See Figure 2.


Figure 2. View Class Diagram

This option creates a ClassDiagram.cd file and opens it in the class diagram designer as you can see in Figure 3. If you right click on the class name, you will see options to add methods, properties, fields, events and other class members. You will also see options to refactor the class, set intellisense options, show base and derived classes, and so on.

Figure 3. Class Diagram options

If you click on Add Method menu item, you will see Figure 4. I type a method name RandomNumber .

Figure 4. Add Method

 

As soon you are done editing, you will see the class members grid and methods, properties, fields, and events. If you do not see the grid by default, right click on the method name and select Class Details meni item.

If you expand RandonNumber, you can add parameters to it. I add two int type parameters to the method as seen in Figure 5.

Figure 5. Add Method Parameters

This option adds the following code to your class.

public int RandomNumber(int min, int max)

{

}

Now , I add random number generator code to the RandomNumber method, which looks like following.

public int RandomNumber(int min, int max)

{

    Random random = new Random();

    return random.Next(min, max);

}

Personally, I like typing and found it faster than using the designer to generate code for me. I add one more method called RandomString to the library with two parameters – int and bool. This method generates a random string for the given size and if lowercase value is true, generates the string in lowercase.

public string RandomString(int size, bool lowerCase)

{

    StringBuilder builder = new StringBuilder();

    Random random = new Random();

    char ch;

    for (int i = 0; i < size; i++)

    {

        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));

        builder.Append(ch);

    }

    if (lowerCase)

        return builder.ToString().ToLower();

    return builder.ToString();

}

Step 3. Adding Class Library Properties 

Similarly, if you select Add Property option, you will see property name and related type and modifiers as shown in Figure 6.

Figure 6. Add a Property

Here is the code generated for the property.

public string LibraryName

{

    get

    {

        throw new System.NotImplementedException();

    }

    set

    {

    }

}

I change the above code with the following code to implement the fully functional property.

protected string libName = "McMathLibrary";

 

public string LibraryName

{

    get

    {

        return libName;

    }

    set

    {

        libName = value;

    }

}

Step 4. Build the Project

Now you just build your project and your class library is ready to use.

Part 2. Create a Silverlight Class Library Consumer Application

This second part of this tutorial shows how to create a Silverlight consumer application to consume the class library we created in the earlier step.  

Right click on the solution and add a new project by selecting Add >> New Project from the menu. On the Add New Project page (see Figure 7), select Visual C# in the left side pane and Silverlight Application in the right side pane, give name of the project to ConsumerApp and click OK.

Figure 7. Create a Silverlight Application

Now, we need to add reference to the class library we just created in the earlier step.

Select ConsumerApp project and right click on the References folder in the Solution Explorer. Now select Add Reference and choose SilverlightMathLibrary from the Projects tab (See Figure 8). Alternatively, you can go to the Browse tab and browse the SilverlightMathLibrary.dll from the folder where you created the class library on your machine.

Figure 8. Add a Reference to SilverlightMathLibrary

Now, open Page.xaml and add a TextBox and two button controls and add the click event handlers for both of the buttons.  The below code adds a TextBox and two Button controls and their click event handlers.

<Grid x:Name="LayoutRoot" Background="White">

        <StackPanel Margin="20,10,0,0" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top" >

            <TextBox x:Name="OutputTextBox" Width="200" Height="30"></TextBox>

            <Button x:Name="StringButton" Width="100" Height="30" Content="Generate String"

                    Click="StringButton_Click" >               

            </Button>

            <Button x:Name="NumberButton" Width="100" Height="30" Content="Generate Number"

                    Click="NumberButton_Click" >              

            </Button>

        </StackPanel>

    </Grid>

Next, open the code behind of Page.xaml and add reference to the SilverlightMathLibrary by adding the following line at the top of the class.

 

using SilverlightMathLibrary;

Now your library is ready to use. If you type following code, you will see available methods and properties and their syntaxes in the Intellisense.

Figure 9.

On StringButton and NumberButton click event handlers, I call RandomString and RandomNumber methods of the class library to generate a random string and random number and display the result in the TextBox.

private void StringButton_Click(object sender, RoutedEventArgs e)

{

    McMathLibrary mcLib = new McMathLibrary();

    OutputTextBox.Text = mcLib.RandomString(5, false).ToString();

}

 

private void NumberButton_Click(object sender, RoutedEventArgs e)

{

    McMathLibrary mcLib = new McMathLibrary();

    OutputTextBox.Text = mcLib.RandomNumber(100, 1000).ToString();

}

Now let’s build and run the application.

When I click on Generate String button, the output looks like Figure 10 and when I click on Generate Number, the output looks like Figure 11.

Figure 10.

 

 

Figure 11.

 

Summary

In this step by step tutorial, we learned how to create a class library (DLL) for Silverlight 2.0 using Visual Studio 2008 and C# and how to use it from a Silverlight consumer application.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software consultant, architect, author, MCP, MVP, and founder of C# Corner. He has over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries including Microsoft, Unisys, Barclay’s, Centocor (J&J), McGraw-Hill, Excelon, PMI, and University of Pennsylvania Hospital. Since year 2000, he is been working with, ASP.NET, SQL Server, C# and .NET. His latest experience and interest is Silverlight, WPF, WCF, XAML and .NET 3.5. If you need any consulting in ASP.NET, AJAX, WPF, WCF, or XAML, contact him at mahesh AT c-sharpcorner DOT com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ClassLibraryInSilverlight.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
how can i use C# class library in silverlightirfan5/21/2009
hello
        i have a C# class library which i have implemented 2 year ago called (business layer) now I want to use in Silverlight project how can i do this,

Regards
Reply | Email | Delete | Modify | 
 
 
Re: how can i use C# class library in silverlightMahesh5/26/2009
Umm .. I am not sure if your library will work in a Silverlight project. Keep in mind, Silverlight is a client side (in browser) based application. There is no server side code execution.

I would try Add Reference and use Browse to see if you can add the reference to your library?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved