Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Secure BlackBox 8
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » Class Library in Silverlight 2.0

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:
Total page views :  2106
Total downloads :  12
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ClassLibraryInSilverlight.zip
 
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
 About the author
 
Praveen Moosad
I have over 12 years of IT industry experience with Microsoft technologies. I hold Masters degree in Computer Science and Applications and Bachelor’s degree in Mathematics. I am responsible for content publishing, product development, and migration of existing contents. I am also responsible for hiring new team members and managing the existing team. I have been awarded MVP for the year 2008 and 2009.
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.
NEW! ANTS Performance Profiler 6.0 out now!
Attach to running process... SQL profiling... I/O profiling... Command-line profiling... Silverlight profiling... Zero overhead mode... Line-Level Timings... Find out more
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.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Aurigma Image Uploader
Aurigma Image Uploader is a versatile upload solution for a wide range of websites. Whether it's a social networking site, photo sharing service, or content management system, Aurigma can do a heavy lifting. Multiple file upload, pre-upload photo resize, etc – all your uploading users will praise you for that!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
ASP.Net 4 Hosting is here
Become a Sponsor
 Comments
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.5.15
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.