• Beth Massi - Sharing the goodness that is VB

    More LightSwitch How Do I Videos Released Today

    • 1 Comments

    I’m back at it with three more “How Do I” videos on Visual Studio LightSwitch. This continues the series I started last week.

    Video #8 shows off the impressive validation framework that Prem wrote about and some of the slickness around validating sets of data on the client and the middle-tier. If you missed the first 5 videos here they are:

    This series of videos build upon each other as we create a sample application for order entry. It’s looking pretty good now! You can access all the videos from the LightSwitch Developer Center Learn page. In the next set of videos I’ll show you how create and sort lookup data, how to create a single screen for both updating and new records, and lots more goodies.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Validating Collections of Entities (Sets of Data) in LightSwitch

    • 6 Comments

    One of the many challenging things in building n-tier applications is designing a validation system that allows running rules on both the client and the server and sending messages and displaying them back on the client. I’ve built a couple application frameworks in my time and so I know how tricky this can be. I’ve been spending time digging into the validation framework for LightSwitch and I have to say I’m impressed. LightSwitch makes it easy to write business rules in one place and run them in the appropriate tiers. Prem wrote a great article detailing the validation framework that he posted on the LightSwitch Team Blog yesterday that I highly recommend you read first:

    Overview of Data Validation in LightSwitch Applications.

    Most validation rules you write are rules that you want to run on both the client and the server (middle-tier) and LightSwitch does a great job of handling that for you. For instance when you put a validation rule on an entity property this rule will run first on the client. If there is an error the data must be corrected before it can be saved to the middle-tier. This gives the user an immediate response but also makes the application scale better because you aren’t unnecessarily bothering the middle-tier. Once the validation passes on the client, it is run again on the middle-tier. This is best practice when building middle-tiers - don’t ever assume data coming in is valid.

    Validating sets (or collections) of data can get tricky. You usually want to validate the set on the client first but then you have to do it again on the middle-tier, not only because you don’t trust the client, but also because the set of data can change in a multi-user environment. You need to take the change set of data coming in from the client, merge it with the set of data stored in the database, and then proceed with validation. Dealing with change sets and merging yourself can get pretty tricky sometimes. What I didn’t realize at first is that LightSwitch also handles this for you.

    Example – Preventing Duplicates

    Let’s take an example that I was working on this week. I have the canonical OrderHeader --< OrderDetails >—Product data model. I want a rule that makes sure no duplicate products are chosen across OrderDetail line items on any given order. So if a user enters the same product twice on an order, validation should fail. Here I have an orders screen that lets me edit all the orders for a selected customer. For each order I should not be allowed to enter the same product more than once:

    image

    Where Do the Rules Go?

    You can write rules in xxx_Validate methods for entity properties (fields) and the entity itself. From the Entity Designer select the property name then click the arrow next to the “Write Code” button to drop down the list of available methods. The property methods will display for the selected property. The entity methods are under “General Methods”. In my example if you select the Product property and drop down the list of methods you see two validation methods Product_Validate and OrderDetails_Validate.

    image

    The Property Methods change as you select an entity property (field) in the designer but the General Methods are always displayed for the entity you are working with. Property _Validate methods run both on the client and then again on the middle-tier. Entity _Validate methods run on the server, these are called DataService validations.

    In my order entry scenario I was first tempted to write code in the DataService on the OrderHeader entity and check the collection of OrderDetails there. When I select the OrderHeader entity in the Entity Designer, click the arrow next to the “Write Code” button, and select OrderHeaders_Validate, a method stub is generated for me in the ApplicationDataService class. This is where I was thinking I could validate my set of OrderDetails and return an error if there were duplicates.

    Public Class ApplicationDataService
    
        Private Sub OrderHeaders_Validate(ByVal entity As OrderHeader, ByVal results As EntitySetValidationResultsBuilder)
            Dim isValid = False
            'Write code to validate entity.OrderDetails collection
            '....
            If Not isValid Then
                results.AddPropertyError("There are duplicated products on the order")
            End If
        End Sub
    End Class

    However I quickly realized that this wouldn’t work because the OrderHeader entity would need to be changed for this validation to fire. If a user is editing a current order’s line items (OrderDetails) then only the validation for the OrderDetail would fire, not OrderHeader. Another issue with putting my rule in the ApplicationDataService class is the user would have to click save before the rule would fire and we’d have an unnecessary round-trip to the middle-tier. We want to be able to check this set for problems on the client first. Another issue is if I found an error then only a general validation message on the order would be presented to the user. They would have to stare at the screen to figure out the problem.

    I think the reason why I went this route in the first place is because I was thinking I needed to merge the change set coming from the client with the set of data in the database and then validate that. It turns out that LightSwitch handles this for you. When you are validating a set of data (entity collection) on the client, you are validating what is on the user’s screen. When the validation runs on the server you are validating the merged set of data. NICE!

    (Note that you can still access the change set via the DataWorkspace object but we’ll dive into that in a future post. )

    The Right Way to Write this Rule

    Since LightSwitch is doing all the heavy-lifting for me this rule gets a whole lot easier to implement. Since we’re checking duplicate products on each OrderDetail we need to put the code in the Product_Validate method of the OrderDetail entity (see screenshot above). Now we can write a simple LINQ query to check for duplicates.

    Public Class OrderDetail
    
        Private Sub Product_Validate(ByVal results As EntityValidationResultsBuilder)
    
            If Me.Product IsNot Nothing Then
    
                'Look at all the OrderDetails that: 
                '   1) have a product specified (detail.Product IsNot Nothing)
                '   2) have the same product ID as this entity (detail.Product.Id = Me.Product.Id)
                '   3) is not this entity (detail IsNot Me)
                Dim dupes = From detail In Me.OrderHeader.OrderDetails
                              Where detail.Product IsNot Nothing AndAlso
                                    detail.Product.Id = Me.Product.Id AndAlso
                                    detail IsNot Me
    
                'If Count is greater than zero then we found a duplicate
                If dupes.Count > 0 Then
                    results.AddPropertyError(Me.Product.ProductName + " is a duplicate product")
                End If
             End If
        End Sub
    End Class

    This validation will fire for every line item we add or update on the order. It will first fire on the client and Me.OrderHeader.OrderDetails will be the collection of line items being displayed on the screen. If this rule passes validation on the client then it will fire on the middle-tier and the Me.OrderHeader.OrderDetails will be the collection of line items that were sent from the client merged with the data on the server. This means that if another user has modified the line items on the order we can still validate this set of data properly. Also notice when we specify the error message, it is attached to the Product property on the OrderDetail entity so when the user clicks the message in the validation summary at the top of the screen, the proper row in the grid is highlighted for them.

    image

    Stay tuned for more How Do I videos on writing business rules.

    UPDATE: Here's a video I did on writing business rules: How Do I: Write business rules for validation and calculated fields in a LightSwitch Application?

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Visual Studio LightSwitch How Do I Videos

    • 15 Comments

    I’ve done my fair share of How Do I videos over the years, particularly on Visual Basic and related technologies. And even though I really don’t like hearing the sound of my own voice (who is that? ;)) I do love teaching. I also love doing How Do I videos for LightSwitch because the tool really lends itself well to short 5-10 minute videos. I’ll be working on more of them this week and will release them weekly. For now, enjoy the first 5 that we released yesterday on the LightSwitch Developer Center.

    These videos are meant to be watched in order because each one builds on the last one. If you are familiar with the old Windows Forms Over Data series I did a few years ago, the application will be familiar to you because we build out the same tables and fields for a simple order management system in this series. It’s amazing how much farther along we get in this series building the application with LightSwitch instead.

    In the next few videos I’m going to tackle Custom Validation, Master-Detail forms, Lookup Tables, and some more advanced Queries.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    LightSwitch Public Beta 1 Now Available!

    • 0 Comments

    We’ve just released the public Beta 1 of Visual Studio LightSwitch! Yay! Check out Jason Zander’s post LightSwitch Beta1 Now Available, Building Your First App.

    To get started, visit the LightSwitch Developer Center:

    image

    Here you can access the download, watch step-by-step “How Do I” videos, read tutorials, and get access to the Training Kit to help get you started learning LightSwitch. The home page also features other goodies like LightSwitch blogs and Channel 9 interviews.

    You also should notice new “Library”, “Learn” and “Forums” tabs at the top of the page that you can explore:

    image

    Our new Learn page has How Do I videos that we’ll be releasing each week, as well as links to important learning resources like Code Samples, featured library articles, and the Training Kit. Stay tuned into this page as we build up more learning content!

    So please download the Beta 1, explore the LightSwitch Developer Center and give us your feedback and ask questions in the forums.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    LightSwitch Beta 1 Available to MSDN Subscribers Today, General Public on Monday

    • 18 Comments

    We just released Visual Studio LightSwitch Beta 1 to MSDN subscribers. Public availability will be this Monday, August 23rd but if you are an MSDN subscriber visit your subscriptions page to get access to the download now. Otherwise check the the LightSwitch Developer Center on Monday for the public download.

    Here are some resources to help get you started -- we have a lot more for you on Monday via the Dev Center so stay tuned!

    We're looking forward to your feedback, please visit the forums.

    I have to say I have been having a ball creating How Do I videos for LightSwitch this week and exploring and learning the product. We're planning on a re-vamp of the LightSwitch Dev Center on Monday and the videos (plus a lot of other content) will be available at that time with links to the public download when available.

    Cant wait!

  • Beth Massi - Sharing the goodness that is VB

    Channel 9 Interview: Visual Studio LightSwitch - Beyond the Basics

    • 0 Comments

    Check it out, the LightSwitch team just posted another Channel 9 video. In this one we go a little deeper into how to customize screens and extend LightSwitch. We also talk a little bit about the architecture on which LightSwitch applications are built:

    In this interview with Joe Binder, a Program Manager on the LightSwitch team, we discuss the LightSwitch application framework architecture and how a LightSwitch application is built on top of well-known technologies like Silverlight, MVVM, RIA Services, and Entity Framework. Joe shows us how to modify the behavior of a screen and how it exposes the commanding pattern in an easy-to-use way. He also shows us how to extend the UI with our own custom Silverlight controls, as well as how to connect our own data sources using RIA Services.

    Channel 9 Interview: Visual Studio LightSwitch - Beyond the Basics

    If you missed it, for an introduction to LightSwitch please see this interview as well:
    Jay Schmelzer: Introducing Visual Studio LightSwitch

    For more information on LightSwitch, please head on over to the Visual Studio LightSwitch Developer Center and please feel free to ask questions in the Visual Studio LightSwitch Forums.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    New Videos and More Rolling out on LightSwitch Developer Center

    • 0 Comments

    A new video just rolled out on the LightSwitch Developer Center on MSDN in a section that is all about helping you discover the range of possibilities that you can do with the product that were done by Orville McDonald, Visual Studio Product Manager:

    Connect to Multiple Data Sources

    More of these types of informational videos will roll out here until Beta 1 is released. But what’s the LightSwitch product  team members doing? Let me tell you!

    We’ve got a lot of great content in store as well, including deeper Channel 9 Videos on how to extend LightSwitch (watch this feed) and “How Do I” step-by-step videos and “Getting Started” tutorials on how to actually use the product (watch the dev center). We’ve also got a great line-up of team bloggers on the LightSwitch Team Blog who have started diving into the architecture of LightSwitch in response to the community asking some great questions on the Internet and in the LightSwitch forums.

    The LightSwitch Developer Center will collect content from all these sources plus more. It will be your one-stop-shop for everything you need to get up to speed on LightSwitch including a link to the Beta 1 download on August 23rd.

    I’m very excited to be part of this product team and even more excited to be learning LightSwitch and creating great content for you on MSDN.

    Stay tuned!

  • Beth Massi - Sharing the goodness that is VB

    Rapid Business Application Development with Visual Studio LightSwitch

    • 8 Comments

    logo This morning Jason Zander announced an exciting new product that the Visual Studio BizApps team here at Microsoft has been building – Visual Studio LightSwitch!

    I am so excited to be able to finally talk about this product! It’s great to be part of a team that works on so many Visual Studio tools (like our Office and SharePoint tools) but LightSwitch is definitely near and dear to my heart because of the types of applications you build with it – data-centric business applications. In the 15 years prior to joining Microsoft, I’ve built a variety of business applications and application frameworks so I’m really excited to be working with this part of our team and ramping up on LightSwitch. I'll definitely be helping with articles, How Do I videos and team interviews as we journey through the Beta to ship cycle.

    LightSwitch makes it easy to create data-centric applications for the desktop and the cloud. You can connect to multiple data sources (i.e. SQL, SharePoint, Azure, WCF RIA Services, etc.) to create feature-rich Silverlight applications on a solid .NET architecture without having to know the depths of Entity Framework or Silverlight or n-tier design. The LightSwitch application framework handles this for you. It also provides so many features that all business applications have in common right out of the box - like an entire application shell, data validations and search. There are also many screen and control templates to choose from as well as a whole set of partners building additional controls, themes, templates, and plug-ins that we will make available right from the LightSwitch development environment via Visual Studio Gallery.

    The idea is you just concentrate on defining entities and screens and the business rules and workflows. The only code you write is the code only you could write – code related to your business domain. And you can use either VB or C# to do that.

    I’m just learning all about this myself but it will sure be a fun ride and I’m excited to jump into it and help you all learn too along the way. The Beta 1 will be available on August 23rd from the LightSwitch Developer Center and we’ll have a lot more tutorials & walkthroughs for you then.

    For now check out some of our online resources we launched today and stay tuned to these channels for more info. We’ll be rolling out more videos on the Developer Center each week:

    Also check out some of the buzz from today’s announcement:

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Localized Online Samples Available for Visual Studio 2010

    • 3 Comments

    Product teams have been releasing samples online on Code Gallery since Visual Studio has been released. This allows us to get samples out the door outside of the normal VS ship-cycle. So what you see “in-box” (a.k.a on the install disk) is only a subset of samples that we release. If you have an internet connection (which you probably do if you are reading this ;-)) then you can access additional online samples from the Help -> Samples menu in Visual Studio 2010:

    image

    This will open a page in the embedded browser that allows you to either navigate to the online samples page on MSDN or the in-box samples ZIP file on disk.

    image

    Depending on your locale, MSDN will direct you to the right page for your country (if available) where you can pick from a variety of language and technology samples. When you select one, it will take you to the Code Gallery download page for that sample for that locale. Even though Code Gallery itself isn’t localized, we added pages to each of the sets of samples that are localized. When you click on the download link on the localized page, that will take you to the localized samples where all comments and readme's have been translated.

    For instance, if you select Développement Office dans Visual Studio 2010 on the Exemples de code Visual Studio 2010 page you are taken to Exemples Office 2010 – the French version of the Office samples description page on Code Gallery. If you select Téléchargements link on that page then that will take you to the correct release - Exemples de Office développement pour VS 2010 RTM.

    image

    You can also select the different localized releases from the right-hand side of any release page. Please note that the product teams are continuously adding more samples so you may see more samples in the English releases until the localization teams can schedule more translations.

    We really hope this makes the samples more accessible to our international audience. And if you notice any mistakes in these pages let me know and I’ll pass them onto the localization teams – I only know a little bit of Italian and Spanish and it’s not very good ;-)

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Multi-line Lambdas in Visual Basic – When is Enough, Enough?

    • 1 Comments

    Now that I’ve been writing code for a while with the latest version of Visual Basic in Visual Studio 2010, I’m at the point where I’ve seen the fun new language features in a variety of applications and samples. One of these fun new features is multi-line and statement lambdas. I favor lambdas anytime I need to write a short code block to do work on another thread or to avoid manually creating a delegate.

    For example, say I have a WPF application that listens for a change in network availability and updates its UI based on the status of the network connection. Because the notification comes in on a background thread we have to make sure we marshal any UI work onto the UI thread using the Dispatcher. In previous versions of Visual Basic we would have to write the code using delegates and the AddressOf operator:

    Example #1

    Public Class Window2
        Private Delegate Sub UpdateUIHandler(ByVal isNetworkAvailable As Boolean)
    
        Sub New()
            ' This call is required by the designer.
            InitializeComponent()
    
            ' Add any initialization after the InitializeComponent() call.
            AddHandler My.Computer.Network.NetworkAvailabilityChanged, _
                AddressOf Network_NetworkAvailabilityChanged
        End Sub
    
        Private Sub Network_NetworkAvailabilityChanged(ByVal sender As Object, _
                                    ByVal e As Devices.NetworkAvailableEventArgs)
            Try
                Dim d As UpdateUIHandler = AddressOf UpdateUI
                Dispatcher.Invoke(d, e.IsNetworkAvailable)
    
            Catch ex As Exception
                Debug.WriteLine(ex.ToString)
            End Try
        End Sub
    
        Private Sub UpdateUI(ByVal isNetworkAvailable As Boolean)
            If isNetworkAvailable Then
                Me.Style = CType(Me.Resources("Connected"), Style)
            Else
                Me.Style = CType(Me.Resources("Disconnected"), Style)
            End If
        End Sub
    End Class 

    This is a perfect opportunity to use a multi-line statement lambda in Visual Basic 2010 instead. When working with the Dispatcher we can avoid having to set up the delegate manually and defining a separate Sub. (Note that since we are only passing in a single boolean parameter we could have used the Action delegate instead of defining our own, but we still would have to separate the implementation from the Invoke call.) Instead you can supply the Sub as a parameter to the Invoke method directly. Notice how this makes our code more concise.

    Example #2 – Use a statement lambda instead of defining a delegate

    Public Class Window2
    
        Sub New()
            ' This call is required by the designer.
            InitializeComponent()
    
            ' Add any initialization after the InitializeComponent() call.
            AddHandler My.Computer.Network.NetworkAvailabilityChanged, 
                AddressOf Network_NetworkAvailabilityChanged
        End Sub
    
        Private Sub Network_NetworkAvailabilityChanged(ByVal sender As Object, 
                                    ByVal e As Devices.NetworkAvailableEventArgs)
            Try
                Dispatcher.Invoke(Sub()
                                      If e.IsNetworkAvailable Then
                                          Me.Style = CType(Me.Resources("Connected"), Style)
                                      Else
                                          Me.Style = CType(Me.Resources("Disconnected"), Style)
                                      End If
                                  End Sub)
    
            Catch ex As Exception
                Debug.WriteLine(ex.ToString)
            End Try
        End Sub
    End Class

    We can actually go even further here and provide another statement lambda directly in the AddHandler as well. This avoids having to declare the event handler method separately. Notice the “nesting” of lambdas here:

    Example #3 – Use another statement lambda to define the event hander “in-line"

    Public Class Window1
    
        Sub New()
            ' This call is required by the designer.
            InitializeComponent()
    
            AddHandler My.Computer.Network.NetworkAvailabilityChanged,
                Sub(sender As Object, e As Devices.NetworkAvailableEventArgs)
                    Try
                        Dispatcher.Invoke(Sub()
                                              If e.IsNetworkAvailable Then
                                                  Me.Style =
                                                      CType(Me.Resources("Connected"), Style)
                                              Else
                                                  Me.Style =
                                                      CType(Me.Resources("Disconnected"), Style)
                                              End If
                                          End Sub)
                    Catch ex As Exception
                        Debug.WriteLine(ex.ToString) 
                    End Try
                End Sub
        End Sub
    End Class 

    At first it may seem a tad confusing because it’s new syntax but I do prefer the code in example #3 because it eliminates all the extra methods we had to write before and puts everything we need right in one place. But what if we had 3 or 5 or 10 other events to add handlers to in the constructor? What if the event handlers had lengthy code or code that called other methods? Would using lambdas help or hurt readability? When is enough, enough?

    Here’s an example of some confusing uses of lambdas doing very simple tasks -- just printing out integers to the console. I got this sample right from the VB compiler test team, it compiles and runs but is this readable to you?

     Dim i = Sub()
                Const c1 = 2
                Const c3 = 3
                Const c2 = 3
                Console.WriteLine(c1)
                Dim y = Sub()
                            Console.WriteLine(c2)
                        End Sub
                Dim z = Function() Function()
                                       Return c3
                                   End Function
                Dim a = Sub()
                            Dim j = Function()
                                       Const c4 = 2
                                       Return c4
                                    End Function
                           Console.WriteLine(j.Invoke)
                           Console.WriteLine(z.Invoke.Invoke)
                        End Sub
                 a.Invoke()
                 y.Invoke()
            End Sub
    Dispatcher.Invoke(i)

    EWW. Thanks guys.

    One of my rules of thumb with any code design is “keep it simple, stupid” (another one is “if it ain’t broke don’t fix it”). Every situation is different but I tend to try to keep methods, LINQ statements, and lambdas short (20 lines or less) and readable. So if the lambda is starting to detract from readability it’s probably better to start breaking things up, or think about a different approach.

    This reminds me of a scene in one of my favorite movies of all time “L.A. Story” with Steve Martin. He’s waiting for his wife played by Marilu Henner to get ready to go out to dinner. When she’s almost ready, standing next to a mirror, she tells him that the first thing she see’s when she looks in the mirror must come off because it’s way too distracting. Mind you, she’s wearing a pretty obnoxious yellow and black dress with gigantic earrings. She whirls around to the mirror, looks, and the earrings come off!

    Try doing that with your code. Close your eyes, open them, and the first thing you see will probably be the code that’s too complicated and should be refactored. ;-) Using lambdas can really clean up your code, just know when to say enough is enough.

    Enjoy!

Page 1 of 45 (449 items) 12345»