Silverlight and what to do with Application or User Settings or INI files

Some people ofter forget about this (even me Confused smile ) So that;’s why I’m posting about this.

In my work (at Artinsoft) we are currently performing a lot of Winforms and VB6 
migration to Silverlight. And a common problem is “What can I do with the user settings!!!”.

In VB6 you had your INI files and in Winforms you probably used something like the App settings.
But when you move to Silverlight what can you do!.
You need a set of initial values and you probably wont want to “burn” those inicial values in your XAP file.
It would be nicer if those values can just be set in the Web.Config file.

So a common way to solve this, is develop a simple helper class. This helper class will use a service that will
collect your initial ini files or appsettings values and store them in your Isolated Storage.
You can even use some kind of basic cryptography if you feel that your date is sensitive.

And then you can use the helpful IsolatedStorageSettings class. For example see this code,
that I borrowed from this post: http://wildermuth.com/2008/10/21/Using_Isolated_Storage_Settings_in_Silverlight_2

const string FAVCOLORNAME = "favoriteColor";
public Color? FavoriteColor
{
  get
  {
    if (IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] != null)
    {
      Color? colorSetting =         IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] as Color?;
      if (colorSetting != null) return colorSetting;
    }

    // If we can't find a favorite color, return a null color
    return new Color?();
  }
  set
  {
    IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] = value;
  }
}

As you can see is very easy to save and recover simple settings from the Silverlight Isolated Storage

Dynamically change WCF Endpoint

23. March 2011 11:33 by Mrojas in General  //  Tags: , , , , , , , , ,   //   Comments (0)

Specially if you are working with Silverlight and Azure you will end up in situation where you would
like to redirect your WCF Endpoint dinamically ( I don’t think you can guess the GUID that Azure will generate
for your staging enviroment).

 

Out of the box the silverlight behaviour is that the WCF endpoints are hardcoded in a config file called
ServicesClient.config embedded in the .xap file.

This can be problematic at least for Azure deployment infraestructure because you can deploy to different sites:
Staging and Production.
Each of this Web Sites will have differente URLs.For example phonebook.cloudapp.net or asdf-asdf-asdf-dasxxx.cloudapp.net

So an easy workaround is:

In WCF when a channel is created in code you can specify the endpoint,
so we only need to created different endpoints depending of the site where the the .xap file was download.

The proposed changes will be:

For example if you create services in your App.xaml.cs method Application_Startup
Then you can change your code for something like:

string url = "http://" + HtmlPage.Document.DocumentUri.Host + "/MyService.svc";
EndpointAddress endpoint = new EndpointAddress(url);
var service = new MyService(new ChannelFactory<IMyService>("*").CreateChannel(endpoint)));

This will allow you to just deploy your application to either Staging or Production environment
in Azure with no more code or config file changes.

Silverlight: Error HRESULT E_FAIL has been returned from a call to a COM component

23. March 2011 05:05 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

While developing some user controls in Silverlight I have come with a situation,
for example when dragging a Chart control in the Visual Studio 2010 designer where I get something like:

Error HRESULT E_FAIL has been returned from a call to a COM component

I have been looking for a solution but have not found anything yet.
The only workaround has been:  
a) Close all windows. Do a Clean and a Rebuild or Close Visual Studio and open it again.

Huge amounts of data WCF \ Silverlight

18. March 2011 04:03 by Mrojas in General  //  Tags: , , , , , , ,   //   Comments (0)

 

Today I found this excellent post:
http://smehrozalam.wordpress.com/2009/01/29/retrieving-huge-amount-of-data-from-wcf-service-in-silverlight-application/ 
and I was the key to solve a problem I had with a WCF service.

I had made some changes to an application to send a text file to the server
for batch processing, everything was working fine until I started sending big files.

I just received one of those obnoxious Not Found error.
So what could I do? Well as any respectable WCF developer would I started tracing the WCF messages with Fiddler, and I found this:

If you cannot read it from the image the message was:

DeserializationFailed… The formatter threw an exception while trying to deserialize the message:
There was an error while trying to deserialize parameter :_xxxxxx.
The InnerException message was 'There was an error deserializing the object of type System.String.
The maximum string content length quota (8192) has been exceeded while reading XML data.
This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas
object used when creating the XML reader.

I was a little confused but thanks to that post I was able to just add:

          <binaryMessageEncoding maxWritePoolSize="16" maxSessionSize="8192">
            <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                                   maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          </binaryMessageEncoding>
 
 

And got everything working again!

Problems Debugging Silverlight with VS 2008

31. January 2011 10:58 by Mrojas in General  //  Tags: , ,   //   Comments (0)

If for any reason you have to debug and develop Silverlight VS 2008,
and you encounter a problem that when you start debugger it reports
something as if the version you have is not supported then first do this:

Open regedit and check:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Silverlight\Components\Debugging\Value

A Version value of 4.0.50917.0 means that you have the Silverlight 4 Developer and you need to:

1. erase this entry.

2. Uninstall Silverlight 4 Tool

3. Reinstall Silverlight 3 Tools for Visual Studio 2008.

Restoring simple lookup capabilities to Silverlight ListBox

27. January 2011 04:09 by Mrojas in General  //  Tags: , , , , , , ,   //   Comments (0)

VB6 and WinForms ListBox has the built in capability to provide a simple data look up. But the Silverlight ListBox does not.
So if you have a list with items:

Apple 
Airplane 
Blueberry 
Bee 
Car 
Zoo 
Animal Planet

And your current item is Apple when you press A the next current item will be Airplane

Apple 
Airplane 
Blueberry 
Bee 
Car 
Zoo 
Animal Planet

And the next time you press A the next current item will be Animal Planet

Apple 
Airplane 
Blueberry 
Bee 
Car 
Zoo 
Animal Planet

And the next time you press A the next current item will be Apple again

Ok to do in Silverlight you need to add a event handler. You can create a user control and this event handler and replace your listbox for your custom listbox or just add this event handler for the listboxes that need it. The code you need is the following:

void listbox1_KeyDown(object sender, KeyEventArgs e)
{
    String selectedText = this.listbox1.SelectedItem.ToString();
    String keyAsString = e.Key.ToString();
    int maxItems = listbox1.Items.Count;
    if (!String.IsNullOrEmpty(selectedText) && 
        !String.IsNullOrEmpty(keyAsString) && keyAsString.Length == 1 && 
         maxItems > 1)
    {   
        
        int currentIndex = this.listbox1.SelectedIndex;
        int nextIndex    = (currentIndex + 1) % maxItems;
        while (currentIndex != nextIndex)
        {
            if (this.listbox1.Items[nextIndex].ToString().ToUpper().StartsWith(keyAsString))
            {
                this.listbox1.SelectedIndex = nextIndex;
                return;
            }   
            nextIndex    = (nextIndex + 1) % maxItems;   
        }
        //NOTE: theres is a slight different behaviour because for example in 
        //winforms if your only had an item that started with A and press A the selectionIndex
        //will not change but a SelectedIndexChanged event (equivalent to SelectionChanged in Silverlight)
        //and this is not the Silverlight behaviour
    }
    
}

Custom tool warning: Cannot import wsdl:portType

25. November 2010 05:04 by Mrojas in General  //  Tags: , , ,   //   Comments (0)

During a Silverlight migration project from VB6 I was trying to add a WCF reference,
everything seemed to work in the wizard but no code was generated.

After reviewing the Warning messages, i found that some said:

Custom tool warning: Cannot import wsdl:portType

What I did to solve this issue?

1. Right click on your service reference

2. Select Configure Service reference

3. Uncheck the option that says Reuse types in referenced assemblies.

image

4. Press OK

After that VS generated the code and I could use the WCF service.

IIS 6 Metabase and IIS 6 Configuration Compatibility

11. November 2010 04:38 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

 

I have a silverlight application that I was trying to publish from Visual Studio to my local IIS and I got this problem:

For the record I have Windows 7.

image

 

So you can write on the Search program and Files “ Turn Windows Features on or off”

 

image

 

And then select

 

image

Set Fixed port for ASP.NET project. Good for Silverlight and Azure projects

11. November 2010 02:57 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

If you are doing Silverlight development, one thing that can be cumbersome is keeping in sync
your development and production settings. Specially if you are using WCF services because you have
to make sure that your ServiceClient.config file has the right values.

What I usually do is this.

1. First set fixed ports for my application. See http://blogs.msdn.com/b/webdevelopertips/archive/2008/11/07/tip-21-did-you-know-how-to-set-a-fixed-port-for-the-developer-web-server.aspx

2. Modify my hosts file in C:\Windows\System32\drivers\etc adding an entry like:

#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
 127.0.0.1       localhost
 127.0.0.1       productionserver.cloudapp.net  

 In this way all you have to change is your hosts file and you keep the same settings for development and for production

Handling Orientation in Silverlight for Symbian

2. November 2010 05:10 by Mrojas in General  //  Tags: , ,   //   Comments (0)

 

One obvious thing in modern symbian mobiles, is how to detect orientation.
I am currently porting some Silverlight 1.0 samples like GrandPiano to Silverlight for Symbian and I was wondering
how can I detect the phone orientation. Well I just analysed the Bing demo and find out that is kind of simple.

What you need is something like this:

public static readonly DependencyProperty OrientationProperty = 
DependencyProperty.Register("Orientation", typeof(Orientation), typeof(Page),
new PropertyMetadata((Orientation)0, new PropertyChangedCallback(OrientationPropertyChanged))); private static void OrientationPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { (sender as GrandPiano).UpdateOrientation(); } private void UpdateOrientation() { base.Width = (this.Orientation == Orientation.Vertical) ? DeviceVerticalSize.Width : DeviceVerticalSize.Height; base.Height = (this.Orientation == Orientation.Vertical) ? DeviceVerticalSize.Height : DeviceVerticalSize.Width; base.Clip = new RectangleGeometry { Rect = new Rect(new Point(), new Size(base.Width, base.Height)) }; } // Properties public Orientation Orientation { get { return (Orientation)base.GetValue(OrientationProperty); } set { base.SetValue(OrientationProperty, value); } }

Silverlight Symbian: Silverlight Content on this website cannot be displayed on this device

1. November 2010 06:10 by Mrojas in General  //  Tags: , ,   //   Comments (0)

When I wrote my first application for Silverlight on Symbian, I kept getting this annoying
message I really didnt get why was it.

Finally I downloaded the Bing Xap file and looked at it. And it seams it was just something simple.

<?xml version="1.0" encoding="utf-8"?>
<Deployment 
xmlns=http://schemas.microsoft.com/client/2007/deployment
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
ExternalCallersFromCrossDomain="ScriptableOnly"
EntryPointAssembly="BingNokia"
EntryPointType="BingNokia.App"

RuntimeVersion="2.0.31005.0"

>
  <Deployment.Parts>
    <AssemblyPart x:Name="BingNokia" Source="BingNokia.dll" />
    <AssemblyPart x:Name="Microsoft.Windows.Controls.WatermarkedTextBox" Source="Microsoft.Windows.Controls.WatermarkedTextBox.dll" />
    <AssemblyPart x:Name="Mvc" Source="Mvc.dll" />
    <AssemblyPart x:Name="System.Xml.Linq" Source="System.Xml.Linq.dll" />
  </Deployment.Parts>
</Deployment>

My runtime version was wrong.

<Deployment 
xmlns=http://schemas.microsoft.com/client/2007/deployment
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
EntryPointAssembly="NokiaTest1"
EntryPointType="NokiaTest1.App"
RuntimeVersion="3.0.40818.0"> <Deployment.Parts> <AssemblyPart x:Name="NokiaTest1" Source="NokiaTest1.dll" /> </Deployment.Parts> </Deployment>

I still dont how to customize my AppManifest file
I suppose that behaviour is due to the fact that I have Silverlight 3 installed in my machine.
So what I did is that I compiled my application. Then renamed my .xap for .zip. Extracted my AppManifest.xml and modified it
changing the runtime version and copied it back to my .xap file. And voila!

Starting a Project for the Cloud

27. October 2010 08:43 by Mrojas in General  //  Tags: , , , , ,   //   Comments (0)

 

If you dont have Windows Azure Tools installed

1. Open Visual Studio 2010

2. On the File Menu, Click new, and then click Project. This opens the New Project dialog

3. In the New Project dialog under Installed Templates, expand the Visual C# node

4. In project type click Cloud. A project that says Enable Windows Azure Tools appears

5. In Name type for example EnableTools and click OK

6. A project with a web page will appear. Click the Download Windows Azure Tools button. Close Visual Studio. Download and installed them.

image

Once you have Windows Azure Toolsl installed

 

1. Open Visual Studio 2010

2. On the File Menu, Click new, and then click Project. This opens the New Project dialog

3. In the New Project dialog under Installed Templates, expand the Visual C# node

4. In project type click Cloud. A project that says Windows Azure Cloud Service appears

image

5. In Name Type for example Phonebook  and click ok. The New Cloud Service Project is shown

 

If you are developing a Silverlight application with some services select the WCF Service Web Role. Rename it to something appropriate. In this example will be Phonebook.Web and Press OK

image

Your solution explorer will look like this:

image

Now you can developing your application. We already have an Silverlight application (that was migrated from VB6 to Silverlight) and some existing Silverlight Class libraries and Server Class Libraries (Class Libraries compiled with the full 4.0 Framework that will be used in the Server Project Phonebook.Web).

To add your Silverlight app. Right Click your server project (Phonebook.Web), then Properties and in Properties go to Silverlight Application and add Phonebook_Silverlight

When everything compiles Go to the Visual Studio Menu Bar, then Debug and then Start Without Debugging. That starts the local development environment on your computer.

image

You can now start testing and finish development of your application.

There is something you myst notice. Everytime you start the Cloud Service, the Azure test environment starts. By default it will start in http:\\localhost:81 but there was a previous Development Fabric it will start in http:\\localhost:81. This is important for Silverlight applications because you must configure your service end point to a particular port. Make sure that your ServiceReferences.ClientConfig file is in sync with the port that your DevelopmentFabric is using

Notes for Azure development:

Sometimes during development it might happen that you get more than one instance of the Development Fabric. This will affect your silverlight apps that rely on WFC services because each new instance starts on a new port. You can use the CSRun tool to stop all instances.

If you have installed the Windows® Azure™ SDK to the default location, the CSRun tool can be found at C:\Program Files\Windows Azure SDK\v1.0\bin\csrun.exe.Then run C:\Program Files\Windows Azure SDK\v1.2\bin\csrun.exe /devfabric:shutdown

 

Publishing your Application

1. Navigate to Azure : https://windows.azure.com/Cloud/Provisioning/Default.aspx

2. On the page that says My Projects. When you are starting you will only see one project line. Click on it

image

3. Click on New Service

image

4. Click on Hosted Services

image

5. In the Create Service page, specify the service properties. In this example we will use Phonebook.Web for service label and a short description and press next.

image

6. Now your hosted service needs a public url. You must check availability. In this example we will use phonebook. Hosted Affinity tries to group your services and storages in the same area. We have a SQL Azure database that is hosted in North Central US, so we will create a new AffinityGroup and call it PhonebookGroup. Press Create

image

7. After Creation your Service is ready, and you can start the deployment.

image

 

8. In Visual Studio 2010 Right click your Cloud Service. And Select Publish…

image

 

9. The Publish Cloud Service Dialog appears. From the Credentials drop down list select <Add>

image

10. From the Create or select an existing certificate select <Create>.
10.1 In our example we will enter a FriendlyName for the new certificate of PhoneBook.

image


10.2 Click the “Copy the full path” link in the dialog. Then Open your browser and navigate to https://windows.azure.com/cloud/provisioning/ and click on your project

 

image

10.3 Now click on account.And in the Account page click on Manage My API Certificates

image

10.4 Click the Choose file and paste the full path you had copied before and then click upload

image

the installed certificate will be shown below.

image

10.5 Now navigate to AppFabric by clicking AppFabric on the left hand side. This will show your subscription ID. Select it and copy it. You have to pasted on the dialog box in Visual Studio on the textbox that says above it “Copy the subscription ID”

image

and name those Credentials PhonebookAccount and press  OK

 

 

 

 

 

 

 

 

 

11 You need a storage account. If you have not created one. Then you have to follow these steps:

11.1 Open your browser and navigate to https://windows.azure.com/cloud/provisioning/ and click on your project.

 

image

11.2 Now click on New Service

image

11.3 Now click on Storage Account

image

11.4 The Create Service Page is show. Enter a Service label and Description and Click Next

image

 

 

 

11.5 Select a name for the public URL, check its availability. And select Affinity.And press Create

image

12. Press OK on the Publish Cloud Service Dialog

 

image

13. Visual studio will upload your application to the cloud

image

While your application is in staging the only problem might be that the published URL changed and that might be conflictive for your ServiceReferences.ClientConfig.

Once your application is on Staging you can switch it to Production and your are ready for business.

Create a Database in SQL Azure

26. October 2010 06:28 by Mrojas in General  //  Tags: , , , , , ,   //   Comments (0)

One of the first steps to put your database in Windows Azure is to put your data on the cloud.

1. The first step is to log in to Azure

1.a) Go to https://windows.azure.com/Cloud/Provisioning/Default.aspx 

1.b)Type your user name and password.

1.c) When your are logged in go to SQL Azure option on the left hand menu.

1.d) You will see a list of your projects. Click on the project.

image

2. You must accept Azure Terms of Use

image

3. Now create a server. You must indicate an administrator username and password. Azure will set the server name.
Press the Create Server button and continue.

image 

4. Now let’s create a new database.Press the Create Database Button

image

5. Just type your database name, edition and size. Editions can be Web or Business.
At this moment Size for Web Edition is 1GB or 5GB and for Business is 10GB, 20GB, 30GB, 40GB and 50GB.
Prices varies according to the options that you select.
For my purposes I will select a Web Edition of 1GB

image

6. You should be able to see your new database in the Databases list.

image

7. Configure Firewall settings so you can connect to the new database.

image

7.1 Press the Allow Microsoft Services access to this server checkbox.
That will add a Rule Name that allows access from 0.0.0.0 to 0.0.0.0.
Select the rule and press Edit. You must can type something like 0.0.0.0 to 255.255.255.255 to allow access to all IP Address.

Moving your data to SQL Azure

The easiest way to upload a SQL Server database to SQL Azure is to use
the SQL Azure Migration Wizard this is a great tool that you can download from
CodePlex http://sqlazuremw.codeplex.com/

1. Download the tool. In my case I installed it in D:\SQLAzureTools. Run SQLAzureMW.exe

image

2. Select SQL Database and press Next

image

3. Select your database and press connect. That will add your database to a list. Click on your database name and press Next

image

4. Select the tables and other object that you will move to your SQL Azure database

image

5. Press Next a Summary is presented with all options

image

 

 

 

6. The wizard will generate a BCP file and a script for your tables.

image

You can connect to run your scripts with the following command:

> sqlcmd -S tcp:<servername>.database.windows.net -U <username>@<servername> -P <password> –d <database>

Depending on your configuration you might have problems with BCP. In general you need something like:

To export data:

bcp PhoneBook out c:\temp\Phonebook-c.dat –S <Server> –T –c

-T  means a trusted connection and native format

To import data

bcp Phonebook.dbo.Phonebook in c:\temp\Phonebook-c.dat -c -U <username>@<servername> -P <Password> -S tcp:<servername>.database.windows.net -c

 

 

 

 

 

 

After importing your data, you are set to keep on developing your applications on Azure

NOTE:

If you dont know the schema name connect to your database and run something like:

SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']' AS SchemaTable FROM sys.tables

Silverlight for Nokia!! WOW! Just about time

25. October 2010 03:45 by Mrojas in General  //  Tags: , ,   //   Comments (0)

I am a big fan of mobile applications and recently due to our migration activities
(we now offer migrations from VB6 and WinForms to Silverlight)
have been involved with Silverlight programming.

I have done some mobile application development activities
in J2EE and flash and I am now very happy with Silverlight.

What makes me even happier is that I am a Symbian fan and I can now
start developing applications for my Nokia phone with silverlight.

Dont miss it!: http://www.silverlight.net/getstarted/devices/symbian/

 

 

What is the ClientBin folder?

16. October 2010 16:25 by Mrojas in General  //  Tags: ,   //   Comments (0)
Silverlight applications are packaged as .xap files. Those files must be keep in your web application. The default directory that is used for that is the ClientBin folder. So if you have silverlight applications associated to your web project their .xap files should go there.

Categories