Intro to iPhone Programming

Posted in IPhone App Programming on April 30th, 2011 by Admin

A nice video tutorial, that gives an introduction to iPhone programming.

iPhoneDevelopmentBits

Tags: , ,

Update: ELCImagePickerController

Posted in IPhone App Programming on April 30th, 2011 by Admin

I recently spent some  time with ELCImagePickerController.  For those of you who’ve worked with UIImagePickerController, you might have noticed one of its major drawbacks: you can only select one photo at a time.  ELCImagePickerController solves this issue by cloning the UI of UIImagePickerController, but with the added bonus of allowing you to select multiple assets.  Collin Ruffenach (@cruffenach), who authored the the first version of the picker, has done an awesome job of making ELCImagePickerController look, feel, and behave like a native image picker.  For this post I’m going to go through some recent improvements I made to ELCImagePickerController and pass along some lessons learned from working with the AssetsLibrary Framework.

This is my first foray into the AssetsLibrary Framework which was introduced with iOS 4.0.  If you’re not already familiar with the framework, I highly suggest checking out both of these posts:

Asset Libraries and Blocks in iOS 4

Cloning UIImagePickerController using the Assets Library Framework

These should give you a solid picture of how to work with ALAssetLibrary, ALAssetGroup, and ALAsset.

One of the obvious changes I’ve made to the project is a reorganization of the code.  Classes are broken out for clarity as you can see here:

Old Tree:

New Tree:

I’ve also renamed several classes to avoid confusion w/ Apple’s and ELC’s respective classes.

On major change to the project is how you present the new ELCImagePickerController.  This is mainly due to an issue we uncovered with a redundant call to [super init] which was causing a substantial memory leak.  Here’s the new way of showing the image picker:

ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName:@"ELCAlbumPickerController" bundle:[NSBundle mainBundle]];ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
 
[albumController setParent:elcPicker];
 
[elcPicker setDelegate:self];
 
ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
 
[app.viewController presentModalViewController:elcPicker animated:YES];
 
[elcPicker release];
 
[albumController release];

One interesting optimization I was able to make was on the loading of large albums which was previously taking several seconds.  Since ALAssetGroup uses a block to enumerate assets, I just fire off a reloadTable call after a short delay:

// Show partial list while full list loads
 
[self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:.5];

Then when the block is finished enumerating, it’ll call reloadTable as well.  On an album with roughly 1500 photos, it was pretty tough to reach the bottom of the tableview before the block finished enumerating.  So this is a pretty decent solution to the issue.  Originally, I experimented with lazy loading the assets as the user scrolled through the table, but ultimately wasn’t able to get the performance I wanted out of it.

This release of ELCImagePickerController should perform faster, and with a smaller memory footprint than before.  I hope you enjoy it.

You can follow me on twitter @matt_tuzzolo or get in touch with us at http://www.elctech.com

ps. for an extra bonus, check out [ELCAsset toggleSelection];


iPhone Programming Tutorials

Tags: ,

Calculating Lifetime Value For Freemium Gamers: Calculating retention rates

Posted in IPhone App Programming on April 29th, 2011 by Admin

Matt Tubergen heads Recharge Studios, a wholly owned subsidiary of W3i that invests in the development and marketing/distribution of freemium mobile games.  W3i is a market leader in distributing and monetizing apps with over 500 million apps distributed for W3i clients. Recharge Studios is actively seeking new investment opportunities, if you have a great idea for a game contact us.

In last week’s post we worked towards identifying ways to calculate the Revenue per Daily Active User as part of our Lifetime Value equation. This week, we look at ways to identify another variable in that equation: retention.

What is retention?

Retention is a key metric that speaks to how many users stick with your app day to day after initially being acquired. When attempting to calculate retention rates there are a variety of different ways to drill into the data and group users. Those groups of users, or vintages, may refer to the day they were acquired, the method in which they were acquired (offerwall, organic, advertising etc.)Or the source from which they were acquired (specific publisher source).

Calculating retention rates for mobile apps

Retention is calculated as an average of active users over time. We first have to calculate the daily retention rate on the first day a user is acquired, retention rates are 100%. Let’s say on day 1 100 users are acquired. On day two, 50 of those users are still active, making the retention rate on day two 50%. Now if only 25 of those users return on day three, the third day retention rate for that vintage would be 25%. To calculate the average retention rate for the entire application, we then take an average of all the daily retention rates for the period. . If we want to look at a more formulaic approach we could justify the following:

Retention Rate = Rate X (1 – Attrition Rate), so Day 1 it is (1 – Attrition Rate) and Day 2 it is (x% X (1-Attrition Rate))

For the sake of calculation, we used large, rounded numbers, often times when calculating the retention you’ll work with a larger data set and have a lower average.

Developers can also dive deep to understand specific retention rates by different user groups/vintages. By segregating by vintage, developers can start to identify different trends that will ultimately help make strategic decisions on user acquisition strategies. Consider the following:

User Group1 = Week 1 Users Acquired

Revenues1 = Week 1 Revenues Earned

Rev/User1 = User Group1 Rev/User for Week 1

 

User Group2 = Week 2 Users Acquired

Revenues1 = Revenues earned by this group in their Week 1

Rev/User1 = User Group1 Rev/User for Week 1

Note on retention rates

This post looks to identify, simply, how to calculate retention but its worth noting that projecting or forecasting retention rates may also come into play. Additionally, there are different ways to look at and interpret the data depending on what kind of information you’re trying to gain from your users.

Next week we’ll bring it all together to look at calculating lifetime value.

Do you have a question about freemium gaming or a topic you’d like us to explore? Let us know in the comments or catch us on twitter @rechargestudios or @w3i.

Freemium Game Blogs are published in partnership with the series on W3i’s corporate blog.


Mobile Orchard

Tags: , , , , , ,

Just Posted: Stephan T. Lavavej’s Advanced STL, 4 of n

Posted in C++ on April 28th, 2011 by Admin

The 4th part digs into rvalue references, perfect forwarding and associative containers.The 4th part of this series digs into rvalue references, perfect forwarding and associative containers.

Advanced STL covers the gory details of the STL’s implementation -> you will therefore need to be versed in the basics of STL, competent in C++ (of course), and be able to pay attention! Stephan is a great teacher and we are so happy to have him on Channel 9—the only place you’ll find this level of technical detail regarding the internals of the STL. There are no books. There are no websites. This is Stephan taking us into what is uncharted territory for most, even those with a more advanced STL skill set.

[Watch Part 4 in Channel 9]

 

See the previous chapters on this Advanced STL series:

Part 1 -> shared_ptr and friends
Part 2 -> Algorithm optimization
Part 3 -> STL’s comprehensive correctness checks

 

New to STL? Watch the STL Introductory Series.


Visual C++ Team Blog

Tags: , , , ,

WebMatrix Series #1: How to configure Visual Basic Templates in WebMatrix

Posted in Visual Basic on April 28th, 2011 by Admin

Microsoft WebMatrix is an exciting new product that makes the creation of custom ASP.NET Web sites possible without all the complexity of the full Visual Studio environment. Another advantage of Microsoft WebMatrix is the ability to easily purchase the proven applications from the Web Gallery. WebMatrix supports Web site development in both C# and Visual Basic. Unfortunately, the Visual Basic developers face an additional challenge of configuring the VB templates because Microsoft WebMatrix by default only has the C# templates configured.

In this walkthrough, I will demonstrate how to configure the Visual Basic templates in Microsoft WebMatrix.

Before you begin you need to download the code containing the VB templates. Also ensure that you have the administrator rights for the machine, as in this walkthrough you will be required to make changes to the “C:\Program Files\Microsoft WebMatrix\templates\” folder.

In this walkthrough we will cover the following topics:

  1. How to download and install the Visual Basic templates into a WebMatrix site.
  2. How to create the metadata files similar to the as the C# templates folder structure.
  3. How to create zip files of the VB templates.
  4. How to compute the SHA1 checksum for each of the VB templates.
  5. How to modify the TemplateFeed.xml file in the “Microsoft WebMatrix\templates” folder to include the VB templates.
  6. How to copy the updated VB template zip files and updated TemplateFeed.xml file into the “WebMatrix\templates” folder.

You can configure the Visual Basic Templates in WebMatrix in the two simple steps as follows:

Step 1: Download and Install the Visual Basic Templates
Step 2: Configure the Visual Basic Templates

Step 1: Download and Install the Visual Basic Templates

To download and install the Visual Basic Templates, follow these steps:

  1. Launch the WebMatrix application. The Quick Start – Microsoft WebMatrix dialog box is displayed.
  2. Select the “Site From Template” option. The Site from Template page is displayed.
  3. All these templates available are C# site templates. To access the Visual Basic templates you will have to download the code for the VB templates.
    Note: If the C# templates are of Version 1.0 and you just want to install the additional VB 1.0 templates, then download the
    code containing the VB templates and follow the directions in the “ReadMe.txt” file available in the downloaded code. In order to configure the updated or new templates that may have been added, you need to follow the steps in this walkthrough to create a new “Site From Template” page to include those new templates.
  4. Select the “Starter Site” template.
    Note: The Visual Basic templates were released later as a NuGet package. NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools. Since NuGet is an extension, it must be run from the Administration page in WebMatrix as shown in the following image:
  5. Select the “ASP.NET Web Pages Administration” option.
    Note: Selecting this option for the first time will lead to prompts to create a site administration password. Follow the prompts to create the site administration password. Log onto the site administration page with the newly created password. The Packages page will be displayed.
  6. Enter “VB” in the search text box. The VB site templates will appear in the list to be downloaded and installed.
  7. Download and install each of the above templates.
    Note: After installing each template, by default they will appear in the “My Documents\My Web Sites\{Site Name}\Microsoft Templates\” folder.

Step 2: Configure the Visual Basic Templates

To use any of the templates, that you had installed in the previous step, to create the Visual Basic sites, you have to create an “Empty Site” and then copy the contents of one of these Microsoft Templates folders to the root of the Empty Web site. To create the “Empty Site” follow these steps:

  1. Launch the WebMatrix application. The Quick Start – Microsoft WebMatrix dialog box is displayed.
  2. Select the “Site From Template” option. The Site from Template page is displayed.
  3. Select the “Empty Site” template.
  4. To create the same folder structure and metadata files as the C# templates, create a “temp” working folder where you have the update rights.
  5. Copy the “Microsoft WebMatrix\templates” folder into this temp folder.
  6. Then copy the Microsoft Templates folder with the downloaded VB templates into your temp folder.
  7. In the “temp\Microsoft Templates” folder, remove the spaces from the folder names and delete the License.rtf and README.txt files.
    Note: You will now have only four sub-folders- BakeryVB, CalendarB, PhotoGalleryVB, and StarterSiteVB in the “temp\ Microsoft Templates” folder.
  8. Within each of these folders, create a folder named the same without the VB suffix and copy all the files into that folder.
    For example: You will have a “temp\Microsoft Templates\BakeryVB\Bakery” folder that contains all the files that were in “temp\Microsoft Templates\BakeryVB” folder.
  9. Extract the “parameters.xml” and “manifest.xml” files from the root of the corresponding C# template zip files and place them in the corresponding “temp\Microsoft Templates\{site}VB\{site}” folder.
    For example: “temp\Microsoft Templates\BakeryVB\” folder will now have the parameters.xml and manifest.xml files from the \temp\templates\Bakery.zip file.
  10. Your final folder/file structure will look like as given on the Listing 1 site.
  11. To create zip files for each template with a VB suffix so they can co-exist in the templates folder along with the C# templates, create separate zip files of the contents of each of the “temp\Microsoft Templates\{site}VB\” folders.
    Note: Create the zip files such that the manifest.xml and parameters.xml and {site} folder are at the root of the zip file. Name these zip files the same as their parent folder with the zip extension.
    For example: “temp\Microsoft Templates\BakeryVB\” folder will contain a BakeryVB.zip file that contains exactly the contents of the “temp\Microsoft Templates\BakeryVB” folder.
  12. Your final folder/file structure will look like as given on the Listing 2 site.
  13. To compute the SHA1 checksum for each of the VB template files, download and extract the File Checksum Integrity Verifier (FCIV.exe) utility available from Microsoft here. And then place it in a location such that it can be available for use from any folder.
  14. Open a DOS Command window, navigate to the “My Documents\temp” folder and enter the following command:

    fciv -add “Microsoft Templates” -r -type *.zip

  15. Note all the SHA1 values that are generated for each of the zip files that you created.
  16. To modify the TemplateFeed.xml file in the “Microsoft WebMatrix\templates” folder to include the VB templates, make a backup copy of the file TemplateFeed.xml file located in the “temp\templates” folder.
  17. Use notepad or your favorite editor to update the TemplateFeed.xml file with the four new application sections, one for each of the VB template zip files.
  18. Copy all the C# code and modify it with the following code:

    <entry type=”application”>
        <productId>BakeryVB</productId>
        <title resourceName=”Entry_BakeryVB_Title”>Bakery VB</title>
        <version>1.0</version>
        <summary resourceName=”Entry_BakeryVB_Summary”>
    Sample web site in VB showing a list of products that can be ordered.</summary>
        <id>http://www.microsoft.com/web/webstack/bakery</id>
        <updated>2010-3-24T18:30:02Z</updated>
        <published>2010-03-24T18:30:02Z</published>
        <longSummary resourceName=”Entry_BakeryVB_LongSummary”>
    Sample web site in VB showing a list of products that can be ordered.</longSummary>
        <link href=”http://microsoft.com/web/webstack/bakery” />
        <images>
          <icon>http://go.microsoft.com/fwlink/?LinkId=195175</icon>
        </images>
        <keywords>
          <keywordId>Templates</keywordId>
        </keywords>
        <author>
          <name>Microsoft</name>
          <uri>http://www.microsoft.com/</uri>
        </author>
        <installers>
          <installer>
            <id>1</id>
            <languageId>en</languageId>
            <installerFile>
              <fileSize>50</fileSize>
              <installerURL>file://%ProgramFiles%\Microsoft WebMatrix\templates\BakeryVB.zip</installerURL>
              <sha1>d40bbb4eb23bda648a95c0841e7d762d57d6c372</sha1>
            </installerFile>
            <msDeploy />
          </installer>
        </installers>
      </entry>

    Note: If you have downloaded the earlier, then you can copy the TemplateFeed.xml from that code. That code contains the updated TemplateFeed.xml file.

  19. Take a backup of the existing TemplateFeed.xml file from the “Program Files\Microsoft WebMatrix\templates” location.
  20. Copy the updated VB template zip files and updated TemplateFeed.xml file into the “WebMatrix\templates” folder. Now the Site from Template page in WebMatrix should display the Visual Basic templates.

Summary

That’s it! You have now successfully configured the Visual Basic templates in the Microsoft WebMatrix. Now you will be able to create Visual Basic sites based on the site templates as easily as it is done with the C# sites.

You can find the full source code for the application here.


The Visual Basic Team

Tags: , , , , ,

Silverlight 4 Firestarter Series #2: How to migrate an ASP.NET Web Forms Application to Silverlight

Posted in Visual Basic on April 26th, 2011 by Admin

In this walkthrough, I will demonstrate how to convert an existing ASP.NET/jQuery application that consumes data from a Windows Communication Foundation (WCF) service to Silverlight.

Here are some topics that we will cover:

  1. How to use the Visual Studio 2010 Silverlight Designer
  2. XAML and Silverlight control concepts
  3. How WCF services can be integrated into Silverlight applications
  4. Silverlight data binding techniques
  5. How to make asynchronous calls to services
  6. How to work with cross domain services
  7. Similarities between ASP.NET and Silverlight applications

Before you begin you need to download the offline kit from the Firestarter Labs, to use the existing applications.

You can migrate an ASP.NET Web Forms application to Silverlight in three simple steps as follows:

Step 1: Explore the ASP.NET Web Forms application
Step 2: Migrate the ASP.NET application to Silverlight
Step 3: Call a WCF Service and Bind data

Step 1: Explore the ASP.NET Web Forms application

Let’s take a look at the code that we’ll be migrating. To start exploring the ASP.NET Web Forms application, follow the following steps:

  1. Open Visual Studio 2010, and from the File menu and select Open Project. The Open Project dialog box is displayed.
  2. Open the following Visual Studio Solution file from the downloaded offline kit:
    “Firestarter\Labs – ASP.NET\Source\Starting Point\VB\CustomerViewer.sln”
  3. The following projects are available in the application:
    • CustomerService.Model – This project contains the entities and data repository classes that are used to access the AdventureWorks LT database.
    • CustomersService – This project is a WCF service application that displays the entities to various applications.
    • CustomerViewer – This is a Windows Forms project that takes data from a WCF service.
    • CustomerViewer.Web – This is an ASP.NET Web Forms project that uses jQuery to make RESTful calls to a WCF service.
  4. In Solution Explorer, right-click CustomerService.svc in the CustomersService project.
  5. From the popup menu select View in Browser. This will start a local WCF server and show a test page.
  6. Go back to Visual Studio application.
  7. In Solution Explorer, right-click the CustomerViewer project.
  8. From the popup menu select Set as StartUp Project.
  9. Press F5 to run the application. The first time the application runs there will be short delay before data is loaded.
  10. Select a customer from the drop-down list. The details of the customer are displayed in the form, allowing the data to be updated or deleted using the AJAX techniques.
  11. Go back to Visual Studio application.
  12. To see the Entity Framework 4 model, in Solution Explorer, double-click the AdventureWorksLT.edmx file in the CustomerService.Model project. The entity model contains a Customer object that is used by the ASP.NET application.
  13. From the Repository folder, open the CustomerRepository.vb page and review the code that interacts with the entity model. The RepositoryBase class is responsible for all communication with Entity Framework and acts as a reusable repository layer in the application.
  14. Open the ICustomerService.vb page. The methods in the page are used to load the customer objects and handle the update and delete operations. Some of the operations support RESTful calls.
    Note: The ASP.NET project currently uses a WCF service proxy object as well as jQuery to communicate with the different service operations. These service calls are forwarded to the CustomerRepository class. The WCF services work well in environments where data must be exposed to different types of clients without requiring a specific technology or framework. This application uses WCF services to promote data re use, allow different types of clients to consume data, and provide a standards compliant way to access the data.
  15. In the CustomerViewer.Web project, right-click Default.aspx. From the popup menu select View Code. Review the code and note the following:
    • A WCF service proxy is used to call a service that supplies customer data
    • If an error occurs loading customer data, a script is sent to the client and used to display an alert
  16. Open the Default.aspx page and note the following:
    • A stylesheet named Default.css is used to add CSS styles into the page
    • A script named Default.js is loaded by the page
    • div tags are used to arrange HTML controls in the page
  17. Open the Default.js page review the jQuery code and note the following features:
    • jQuery selectors are used to locate controls in the DOM and access their values
    • jQuery AJAX functions such as getJSON are used to communicate with a cross domain WCF service

Step 2: Migrate the ASP.NET application to Silverlight

Now let’s migrate the application to Silverlight. We’ll create a new Silverlight project, work with XAML, create a WCF service proxy to interact with the service, and design a user interface that mirrors the existing ASP.NET user interface.

  1. To add a new Silverlight Application, right-click the application name and add a new project. The Add New Project dialog box is displayed.
  2. Browse to the Silverlight node and select the Silverlight Application template.
  3. Enter the name for the project as SilverlightCustomerViewer and click OK. The New Silverlight Application dialog box is displayed.
  4. Select <New Web Project> from the drop-down list options and confirm that the New Web project name is displayed as SilverlightCustomerViewer.Web. This project will be used to host the Silverlight application in a web page.
  5. Click OK to proceed. The MainPage.xaml page of the SilverlightCustomerViewer project is displayed.
  6. Replace the <UserControl> tag with the following code:

    <UserControl x:Class=”SilverlightCustomerViewer.MainPage”

     xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″

     xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

    mc:Ignorable=”d”

    d:DesignHeight=”545″ d:DesignWidth=”550″ Width=”545″ Height=”550″>

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

    </Grid>

    </UserControl>

    Note: The d:DesignHeight and d:DesignWidth attributes control the size of the design surface in the design mode. However, they don’t have any effect at runtime. The Height and Width attributes constrain the size of the Silverlight screen at runtime. If you don’t define the Height and Width attributes, Silverlight will automatically fill the entire area of its container.

  7. From the toolbox, drag and drop 9 TextBlock controls, 1 ComboBox control, 5 TextBox controls and 2 Button controls to the designer surface and arrange them as the following:

    Note: The TextBlock control is similar to the Label control in ASP.NET. The Silverlight Toolkit provides the Label control that can be used in Silverlight applications. You can download the Silverlight Toolkit from
    here.
  8. Change the Text property of each TextBlock control such that it matches the user interface as shown above.
  9. Set the Content property of the first Button control to “Update” and the Content property of the second Button Control to “Delete”.
  10. Select the ComboBox control, and change the name of the control to a value of CustomersComboBox as shown in the following image:
  11. Change the DisplayMemberPath property of the ComboBox control to a value of FullName.
    Note: The DisplayMemberPath is used to define the property that will be displayed is the ComboBox when it binds to a collection of Customer objects.
  12. Change the names of the update and delete buttons in the interface to “Update” and “Delete” respectively using the Properties window.
  13. To simulate an HTML frameset tag, from the toolbox drag and drop a Rectangle control to the designer surface.
  14. Right-click the Rectangle control, and from the popup menu select Order, and then select Send to Back.
  15. Resize and arrange the Rectangle control as shown in the following figure:
  16. From the toolbox, drag and drop a Border control to the design surface.
  17. Select the Border control and change its Background property to “White” and its BorderBrush property to “White”.
  18. From the Toolbox, drag and drop a TextBlock control into the Border control.
  19. Select the TextBlock control and change the Text property to a value of Customer Details.
  20. Right-click the Customer Details TextBlock and from the popup menu select Reset Layout, and then select Size.
  21. The user interface should look like the following:  

Step 3: Call a WCF Service and Bind Data

Now let’s create a WCF service proxy that can be used to call an existing WCF service. We’ll also use a clientaccesspolicy.xml file to handle cross domain issues and bind data to controls.

  1. Right-click on the SilverlightCustomerViewer project and then select Add Service Reference. Add Service Reference dialog box is displayed.
  2. Click Discover to browse and locate the WCF services.
  3. To expand the CustomerService.svc service, click on the icon next to CustomerService.svc service. Drill down to browse to the ICustomerService contract. Click the contract name and ensure that it has several service operations available.
  4. Enter the namespace as CustomerService.Proxies.
  5. To create the WCF service proxy, click OK.
  6. Add a new Customer class to the SilverlightCustomerViewer project.
  7. Add the following namespace of the new class:

    Namespace CustomerService.Proxies

    Note: This namespace is added so as to match the namespace of the new class with that of the namespace generated by the WCF proxy.

  8. To display the FullName property in the ComboBox control , add the following code in the Customer class:

    Partial Public Class Customer

        Public ReadOnly Property FullName() As String

            Get

                Return FirstName & ” “ & LastName

            End Get

        End Property

    End Class

  9. To import the proxy namespace, open the MainPage.xaml.vb page and add the following code:

    Imports CustomerService.Proxies

  10. To hook the Loaded event to an event handler, add the following code within the constructor:

    AddHandler Loaded, AddressOf MainPage_Loaded

  11. To use the WSF service proxy and make an asynchronous data request, add a MainPage_Loaded method with the following code:

    Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)

           Dim proxy = New CustomerServiceClient()

           AddHandler proxy.GetCustomersCompleted, AddressOf proxy_GetCustomersCompleted

           proxy.GetCustomersAsync()

    End Sub

  12. Add the following method and associated code to handle the asynchronous callback, which will be made when the data from the WCF service is returned to the Silverlight application:

    Private Sub proxy_GetCustomersCompleted(ByVal sender As Object, ByVal e As GetCustomersCompletedEventArgs)

           CustomersComboBox.ItemsSource = e.Result

    End Sub

    Note: Once the WCF service proxy returns data it can be accessed through the GetCustomersCompletedEventArgs object’s Result property which is typed as an ObservableCollection of Customer. This collection is assigned to the ItemsSource property of the ComboBox.

  13. Open the MainPage.xaml page.
  14. Select the TextBlock control next to Customer ID and select Properties from the menu.
  15. Remove the text from the Text property and click on the click the icon next to the property and from the popup menu select Apply Data Binding. The Data Binding property dialog box is displayed.
  16. Click ElementName and then select CustomersComboBox to set the ComboBox as the data binding source as shown in the following figure:
  17. Click Path area and select SelectedItem from the properties as shown in the following figure:
  18. In the XAML editor, locate the TextBlock control modified in the previous step and change the Text property value to the following:

    Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.CustomerID }”

  19. Similarly add data bindings to all of the TextBox controls in the designer surface. For this you’ll have to modify the Text property of each control within the XAML as done in the previous step to specify the appropriate property of the SelectedItem to bind to. To set the properties for each TextBox, add the following XAML code:

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”158,225,0,0″ VerticalAlignment=”Top” Width=”219″ Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.FirstName,Mode=TwoWay}” />

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”158,270,0,0″ VerticalAlignment=”Top” Width=”219″ Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.LastName,Mode=TwoWay}” />

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”158,316,0,0″ VerticalAlignment=”Top” Width=”219″ Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.CompanyName,Mode=TwoWay}”/>

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”158,366,0,0″ VerticalAlignment=”Top” Width=”219″ Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.EmailAddress,Mode=TwoWay}” />

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”158,416,0,0″ VerticalAlignment=”Top” Width=”219″ Text=”{Binding ElementName=CustomersComboBox, Path=SelectedItem.Phone,Mode=TwoWay}” />

    Note: Each TextBox binding has Mode=TwoWay added to it. This allows any change made to a TextBox control to be propagated back to the bound property automatically.

  20. Right-click the SilverlightCustomerViewer.Web project and select Set as StartUp Project.
  21. To set the html page in the project as the startup page, right-click the appropriate file and select Set As Start Page.
  22. Press F5 to compile and run the application.
    Note: An error will occur once the Silverlight application loads. This is due to a cross domain call that is being made from Silverlight to the WCF service. This service uses a different port than the Silverlight host Web project, which causes this cross domain exception to be thrown.
  23. To fix this cross domain issue, rename the existing clientaccesspolicy.exclude file in the CustomersService project to clientaccesspolicy.xml.
  24. Press F5 to compile and run the application again. Now the data loads in the ComboBox control.
  25. Select a customer from the drop-down list. The data from it is bound to the appropriate TextBlock and TextBox controls.
  26. Go back to Visual Studio application to add the Click event handlers.
  27. To add the event handler for the Update button, add the following code in the Update button’s click event handler:

    Dim proxy = New CustomerServiceClient()

    Dim cust = TryCast(CustomersComboBox.SelectedItem, Customer)

    cust.ChangeTracker.State = ObjectState.Modified

    AddHandler proxy.SaveCustomerCompleted, Sub(s, args)

           Dim opStatus = args.Result

           Dim msg As String = If(opStatus.Status, “Customer Updated!”, “Unable to update Customer: “ & opStatus.Message)

           MessageBox.Show(msg)

    End Sub

    proxy.SaveCustomerAsync(cust)

  28. To add the event handler for the Delete button, add the following code in the Delete button’s click event handler:

    Dim proxy = New CustomerServiceClient()

    Dim cust = TryCast(CustomersComboBox.SelectedItem, Customer)

    cust.ChangeTracker.State = ObjectState.Deleted

    AddHandler proxy.SaveCustomerCompleted, Sub(s, args)

           Dim opStatus As OperationStatus = args.Result

           If opStatus.Status Then

                  CType(CustomersComboBox.ItemsSource, ObservableCollection(Of Customer)).Remove(cust)

                  MessageBox.Show(“Customer deleted!”)

           Else

                  MessageBox.Show(“Unable to delete Customer: “ & opStatus.Message)

           End If

    End Sub

    proxy.SaveCustomerAsync(cust)

  29. Run the application and test the update and delete functionality.

Summary

In this walkthrough you have examined an existing ASP.NET Web Forms application and supporting data access and service layers. You have now successfully migrated the existing functionality from the ASP.Net Web Forms application to Silverlight.

You can find the full source code for the application here.


The Visual Basic Team

Tags: , , , , , ,

AT&T activates more iPhones, Apple awarded patents, and more in this week’s mobile news

Posted in IPhone App Programming on April 26th, 2011 by Admin

Apple reaches 37.9 million users in the Unithed States, 59% more than Android.

AT&T activating more phones than Verizon.

United States Patent and Trademark Office has awarded Apple patents for the iPhone 4.

iOS 4 keeps a log of your location and stores it in a hidden file on your iPhone or iPad.

Reuters says iPhone 5 to arrive in September.


Mobile Orchard

Tags: , , , , , , , , , ,

The Visual C++ Weekly Vol. 1 Issue 17 (Apr 23, 2011)

Posted in C++ on April 25th, 2011 by Admin

Read in this issue:

  • [Herb Sutter] Session Announcement: C++ and the GPU… and Beyond
  • [Kate Gregory] Application Restart and Recovery on Windows 7
  • [Channel 9] Boris Jabes on Game Development and Other Demons
  • [ConcRT blog] The Concurrency Runtime and Visual C++ 2010: Rvalue References
  • [Anthony Williams] Picking Patterns for Parallel Programs (slides from ACCU 2011)
  • [Channel 9] DirectCompute Expert Roundtable Discussion
  • [Channel 9] Parallel Programming: Tasks and Continuations
  • [CodeProject] An MFC/GDI+ LCD Control


Visual C++ Team Blog

Tags: , , , ,

Struct, Union and Class

Posted in C++ on April 25th, 2011 by Admin

Data-encapsulation is key to the functionality of many high level or later generation programming languages such as C++ and Java. It is simply a means of creating “containers” called objects, and holding multiple variables of varying data types called member variables inside of those containers. C++ offers three methods of data-encapsulation; struct, union and class. This is where C++ become object oriented.
C++ Home

Tags: , ,

Silverlight 4 Firestarter Series #3: How to work with Panels, XAML, and Controls in Silverlight

Posted in Visual Basic on April 24th, 2011 by Admin

I am back with details on how to work with Panels, XAML, and Controls in Silverlight. In this walkthrough, we will see how to work with Panels, XAML, and Controls to create a Data-Driven Silverlight Interface.

During this walkthrough we will cover the following topics:

  1. How to use the Visual Studio 2010 Silverlight Designer, Cider
  2. How to work with XAML, Panels, and Controls
  3. The difference between a Grid and a StackPanel
  4. How to add controls and XML Namespaces
  5. How to create a UserControl

Before you begin, you need to download the offline kit from the Firestarter Labs to use the existing applications.

To work with Panels, XAML, and Controls follow these three simple steps:

Step 1: Create a Data-Driven Interface
Step 2: Create a Form Entry to edit the Interface Details
Step 3: Add a Menu using the StackPanel

Step 1: Create a Data-Driven Interface

In this step, we will see how to work with XAML, work with controls by adding a DataGrid, and work with the visual editor, known as the Cider editor, in Visual Studio. To create a Data-Driven Interface, follow these steps:

  1. Open Visual Studio 2010, and from the File menu, select Open Project. The Open Project dialog box is displayed.
  2. Open the following Visual Studio Solution file from the downloaded offline kit:
    “Firestarter\Labs – XAML and Controls\Source\Starting Point\VB\ PanelsControlsLab.sln”
  3. Open the MainPage.xaml page.
  4. To define rows in the grid, add the following XAML code in the “LayoutRoot” grid tag:

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

         <Grid.RowDefinitions>

             <RowDefinition Height=”Auto”/>

             <RowDefinition Height=”Auto” />

         </Grid.RowDefinitions>

    </Grid>

  5. To add an application title, add a TextBlock control to the design view.
  6. Specify the row placement by using the Grid.Row attribute inside the TextBlock tag, as shown in the following XAML code:

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

        <Grid.RowDefinitions>

            <RowDefinition Height=”Auto”/>

            <RowDefinition Height=”Auto” />

        </Grid.RowDefinitions>

        <TextBlock Height=”Auto” Width=”Auto” Grid.Row=”0″>

             Contact Details

        </TextBlock>

    </Grid>

    Note: The rows are indexed from the top of the panel to the bottom, beginning with zero.

  7. Drag and drop the DataGrid control from the Toolbox onto the design view below the header.
    Note: An xmlns (XML Namespace) declaration is automatically added in the XAML code. This addition is necessary if you want to use the DataGrid because it is part of the Silverlight Toolkit and not of the native runtime.

    xmlns:sdk=”http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk”>

  8. Add data to the DataGrid control. To populate the DataGrid control with the Sample Data Collection generated from the Expression Blend, add the following XAML code. By setting the Height and the Width to “Auto”, the grid dynamically resizes itself based on the size of the content:

    <UserControl.Resources>

           <DataTemplate x:Key=”ImageTemplate”>

                  <StackPanel>

                         <Image Source=”{Binding Image}” HorizontalAlignment=”Left” Height=”64″ Width=”64″/>

                  </StackPanel>

           </DataTemplate>

    </UserControl.Resources>

     

    <Grid x:Name=”LayoutRoot” Background=”White” DataContext=”{Binding Source={StaticResource Contacts}}”>

           <Grid.RowDefinitions>

               <RowDefinition Height=”Auto”/>

               <RowDefinition Height=”Auto” />

           </Grid.RowDefinitions>

           <TextBlock Height=”Auto” Width=”Auto” Grid.Row=”0″ FontSize=”24″ HorizontalAlignment=”Left” VerticalAlignment=”Top” Margin=”8,8,0,0″>Contact Details</TextBlock>

            <sdk:DataGrid AutoGenerateColumns=”False” Grid.Row=”1″ Height=”Auto”

                          Width=”Auto” HorizontalAlignment=”Left” Margin=”0,16,0,0″

                          x:Name=”ContactsDataGrid” VerticalAlignment=”Top” ItemsSource=”{Binding Collection}”>

                  <sdk:DataGrid.Columns>

                         <sdk:DataGridTextColumn Binding=”{Binding Name}” Header=”Name”/>

                         <sdk:DataGridTemplateColumn CellTemplate=”{StaticResource ImageTemplate}” Header=”Image”/>

                         <sdk:DataGridTextColumn Binding=”{Binding Address}” Header=”Address”/>

                         <sdk:DataGridTextColumn Binding=”{Binding Email}” Header=”Email”/>

                         <sdk:DataGridTextColumn Binding=”{Binding PhoneNumber}” Header=”PhoneNumber”/>

                         <sdk:DataGridTextColumn Binding=”{Binding WebSite}” Header=”WebSite”/>

                  </sdk:DataGrid.Columns>

            </sdk:DataGrid>

    </Grid>

  9. The user interface should look like the following:

Step 2: Create a Form Entry to Edit the Interface Details

Now let’s create a form entry to edit the interface details. In this step, we will see how to create a new UserControl and create a data entry form. To create a new UserControl, follow these steps:

  1. To add a new UserControl, right-click the PanelsControlsLab project, select add, and then select New Item. The Add New Item dialog box opens.
  2. Browse to the “Silverlight” node, and select the “Silverlight User Control” template.
  3. Enter the name of the UserControl as “EditContacts.xaml”, and click “Add”.
  4. Create the form entries for each field in the DataGrid (Name, Image, Address, Email, Phone number, and Website). To create all the fields and edit the Text property of each field, add the following XAML code:

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”12,16,0,0″ Name=”textBox1″ VerticalAlignment=”Top” Width=”348″ Text=”Name” />

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”12,46,0,0″ Name=”textBox2″ VerticalAlignment=”Top” Width=”348″ Text=”Image Location”/>

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”12,74,0,0″ Name=”textBox3″ VerticalAlignment=”Top” Width=”348″ Text=”Address”/>

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”12,104,0,0″ Name=”textBox4″ VerticalAlignment=”Top” Width=”348″ Text=”Email”/>

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”10,134,0,0″ Name=”textBox5″ VerticalAlignment=”Top” Width=”350″ Text=”Phone Number”/>

    <TextBox Height=”23″ HorizontalAlignment=”Left” Margin=”10,164,0,0″ Name=”textBox6″ VerticalAlignment=”Top” Width=”350″ Text=”Website”/>


  5. Build the project, so that the UserControl can appear in the Toolbox.
  6. Open the MainPage.xaml page.
  7. Open the Toolbox. You will be able to see EditContacts (PanelControlsLab) as a new control in the Toolbox.

    Note: The EditContacts (PanelControlsLab) control will not appear in the Toolbox list, if you are currently working on the EditContacts.xaml page.
  8. Drag and drop the EditContacts (PanelControlsLab) control onto the design view.
  9. A new xmlns (XML Namespace) declaration is automatically added in the XAML code. This represents the current project, and lets the runtime know where to find the control.

    xmlns:my=”clr-namespace:PanelsControlsLab”

  10. At the top of the page, add a button to enable the user to open the Add Contact interface. To add the button, drag and drop the ToggleButton control onto the design view.
    Note: If you cannot see the ToggleButton control in the Toolbox, add it by clicking the Toolbox and clicking Choose Items from the popup menu. The Choose Items dialog box will be displayed. Select the ToogleButton checkbox and click OK. The ToogleButton control will get added to the Toolbox.
  11. Change the Content property of the ToggleButton control to “Add new contact”.
  12. Change the Visibility property of the EditContacts (PanelControlsLab) control to “Collapsed”. The property is set to Collapsed so that the EditContacts UserControl is visible only when the ToggleButton is checked and doesn’t open by default.
  13. Add the event handlers for the Checked and UnChecked events of the ToggleButton to hide and show the EditContacts (PanelControlsLab) control, respectively. To add the event handlers, open the Main.Page.vb page and add the following code:

    Namespace PanelsControlsLab

    Partial Public Class MainPage

                  Inherits UserControl

                  Public Sub New()

                         InitializeComponent()

                  End Sub

     

                  Private Sub AddContactButton_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)

                         Me.AddContactPanel.Visibility = System.Windows.Visibility.Visible

                  End Sub

     

                  Private Sub AddContactButton_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)

                         Me.AddContactPanel.Visibility = System.Windows.Visibility.Collapsed

                  End Sub

           End Class

    End Namespace

    Note: There’s a shortcut to add an Event Handler. Select Checked in the Events property of the CheckBox control. Double-click the event to automatically generate the event handler (AddContactButton_Checked) for the CheckBox. Repeat this step for the UnChecked event and the AddContactButton_UnChecked event handler will be generated. In the AddContactButton_Checked handler, set the visibility of the EditContacts (PanelControlsLab) control to System.Windows.Visibility.Visible and in the AddContactButton_UnChecked handler, set it to System.Windows.Visibility.Collapsed.

  14. Open the EditContacts.xaml page.
  15. Drag and drop a Button control from the Toolbox onto the design view.
  16. Change the Text property of the Button control to “Add Contact”. This button will add the data entered in these fields into the DataGrid.
  17. To add the border to the Edit Contacts window, add the following XAML code:

    <Border BorderThickness=”1″ Height=”227″ HorizontalAlignment=”Left” Name=”border1″ VerticalAlignment=”Top” Width=”372″>

        <Border.BorderBrush>

            <LinearGradientBrush EndPoint=”1,0.5″ StartPoint=”0,0.5″>

                <GradientStop Color=”Black” Offset=”0″ />

                <GradientStop Color=”#FF443B3B” Offset=”1″ />

            </LinearGradientBrush>

        </Border.BorderBrush>

    </Border>

  18. The user interface will look like the following:

Step 3: Add a Menu using the StackPanel

Now let’s add a menu using the StackPanel. In the StackPanel, the contained elements can be organized either vertically or horizontally by changing the Orientation property appropriately. In this case, we are going to add two more menu items (edit contacts and help) along with the Add new contact button and align the StackPanel horizontally. To add the menu items, follow these steps:

  1. Add a ToggleButton control for editing the contacts and a Button control for opening the help page. Place the items next to the Add new contact button. Set the margins and HorizontalAlignment of each button.
  2. Create a StackPanel and move the three controls inside the panel. To create a StackPanel, add the following XAML code:

    <StackPanel HorizontalAlignment=”Right” Margin=”0,8,8,11″ Orientation=”Horizontal”>

          <ToggleButton x:Name=”AddContactButton” Content=”Add new contact” Checked=”AddContactButton_Checked” Unchecked=”AddContactButton_Unchecked” Height=”24″ Margin=”0,0,5,0″ />

          <ToggleButton x:Name=”EditContactButton” Content=”Edit contact” Checked=”AddContactButton_Checked” Unchecked=”AddContactButton_Unchecked” Height=”24″ Margin=”0,0,5,0″ />

           <Button x:Name=”HelpButton” Content=”Help”/>

    </StackPanel>

  3. The menu will look like the following:

Summary

In this walkthrough, you have learned how to create a Data-Driven Silverlight Interface using Panels, XAML, and Controls . You have now successfully added a data entry form to the existing project and created a menu using the StackPanel.

You can find the full source code for the application here.


The Visual Basic Team

Tags: , , , , , ,