Creating and Using Silverlight web.config app settings (Web.config Configuration Applicatioin Settings) or app.config application settings configuration file for Silverlight

Post Summary:

This posts explains how to create and use something similar to a silverlight  web.config, App.config and appsettings (or app settings) configuration file for silverlight application. This is based on re-using serviceReference.clientconfig as an appconfig configuration file.

The Problem:

A) configuration application settings (like the one in web.config, appsettings or app settings application configuration file):
This is probably very common. Your silverlight application might well need to have some configuration settings that you can change their values without having to re-build and re-deploy the whole application because of a small change in a connection string or appSetting value. Again, AppSettings in good old web.config files in ASP.net applications were the best solution in this case.

B) WCF Address (EndPoint address value) change after building:
Another reason for wanting to have a configuration file in a silverlight application: Have you ever wanted to change the WCF service address (endpoint address) in your silverlight application after deployment. Imagine that you built a silverlight application and deployed it on your test server. The application was tested and confirmed issues and bug free. Now you want to re-deploy the application to the Live server but the WCF service address (end point address) is different which is probably quite common. It might also be that the address is the same but the port on which the WCF service is listening is different. In this case, you will need to change the value of the WCF endpoint address and re-build. So what happened to configuration files! They are a standard now in all Microsoft environments.

Problem Summary: The problem is there is no clear web.config file in silverlight as the whole code is compiled into a (.xap) file which any html or aspx page can call.

Solution:

In my silverlight application, I had a connection string value that I need to use in my silverlight application (pass it to the webservice). Hence, I wanted the flexibility to change the WCF endpoint address and the connection string configuration value (or any other application setting). I started looking for a solution but I found that most work arounds were either t0o long or too complicated. As always, I like simple things and I don’t like over complications. I have to say though that most if not all work arounds that I found were useful for me to come up with this solution. I am not sure but I believe (and hope) the following solution is unique as I have searched for quite a while to find anyone suggesting this idea but I couldn’t find any.

Solution part 1: The simplest way for adding application settings to a silverlight application.

Now since ServiceReferences.ClientConfig is just an xml configuration file, you can actually edit it in visual studio and simply add your application settings.

Your file will look something like this:

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name=”xrmServiceBasicHttp” maxBufferSize=”2147483647″
                    maxReceivedMessageSize=”2147483647″>
                    <security mode=”None”>
                        <transport>
                            <extendedProtectionPolicy policyEnforcement=”Never” />
                        </transport>
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address=”http://localhost:1234/MyWCFService.svc” binding=”basicHttpBinding”
                bindingConfiguration=”xrmServiceBasicHttp” contract=”XrmService.IXrmService”
                name=”xrmServiceBasicHttp” />
        </client>
    </system.serviceModel>
<appSettings>
<add key=”ConnectionString” value=”data source=ABC01;initial catalog=DB01;integrated security=SSPI;persist security info=False;packet size=4096″ />  
</appSettings>
</configuration>

Now that you have added your application setting (connection string) to your ServiceReferences.ClientConfig, you need to use it in your silverlight code behind (.xaml.cs) file.

Remember, ServiceReferences.ClientConfig is just an XML file (already said that many times!). Hence, you can write a very simple and straight forward function that parses your ServiceReferences.ClientConfig xml file and returns the appSetting value of your application setting.
A function to return an AppSetting value from your clientconfig file can look something like this:

private string getAppSetting(string strKey)
        {
            string strValue = string.Empty;
            XmlReaderSettings settings = new XmlReaderSettings();           
            settings.XmlResolver = new XmlXapResolver();
            XmlReader reader = XmlReader.Create(“ServiceReferences.ClientConfig”);
            reader.MoveToContent();
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == “add”)
                {
                    if (reader.HasAttributes)
                    {
                        strValue = reader.GetAttribute(“key”);
                        if (!string.IsNullOrEmpty(strValue) && strValue == strKey)
                        {
                            strValue = reader.GetAttribute(“value”);
                            return strValue;
                        }
                    }
                }
            }
            return strValue
}

Finally in your code, to retrieve the AppSetting value for the appSetting key (ConnectionString) that you created, you can just call the above function like this:

client.SetConnectionStringAsync(getAppSetting(“ConnectionString”));

And One last thing, remember when you create the WCF service client object, don’t explicitly call the WCF service address, as it is already in your ClientConfig file.

So, just call the end Point Configuration Name (endPointConfigurationName) that you want to use. Just like this:

MyServiceClient client = new MyServiceClient(“MyServiceBasicHttp”);

———-

Solution part 2: Changing WCF address and endpoint values in “ServiceReferences.ClientConfig”.

Anyway, the first thing we need to do is to understand that “ServiceReferences.ClientConfig” that all silverlight applications have and use if they are connecting to a WCF sercvice, is just a simple XML file. Actually, not only an XML file but also a configuration file for the application.

You also need to know that the silverlight xap (*.xap) file that silverlight generates is a simple compressed (zipped) file. For this reason, you actually can rename the file to (something.zip) from (something.xap) and then you can access its content. The content of the xap file includes AppManifes.xaml, your application dlls and most importantly “ServiceReferences.ClientConfig”.

Now, when I tried to unzip it, change the content of one of its files and then re-zip it and rename it back to (something.xap), this has corrupted it. My application failed. I am not sure why. This was the case despite the fact that most posts about unpacking, unzipping and re-packaging the .xap file works.

What actually works is the following:
Rename the something.xap file to something.zip file. Open the zip file without unzipping (just double click on it) and then copy the file you want to edit, which in our case is the “ServiceReferences.ClientConfig” and paste it in a different location. Edit it and make all the changes you need to it and then copy it and paste back into the something.zip file. Replace the exisitng file there. Now go to something.zip and rename it back to something.xap.

Whatever change you have made should now work.

———–

I hope this helps. I really think it is an effective way to get your AppSetting values.

If you got any questions, please comment below (Kindly don’t use the contact page for questions on posts please)

Also, please let me know (via a comment below) if you want a copy of this application code.

Problems with Deploying WCF services on IIS 7.0 (or IIS 6, IIS) and other deployment options and scenarios (visual studio .NET and Windows Activation Services)

There are 3 main ways to deploy Windows Communication Foundation – WCF services to consume:

1- IIS
2- Windows Activation Service a.k.a WAS
3- Visual Studio .NET for development and dev testing purposes as part of a visual studio solution.

For full details about Windows Communciation Foundation deployment scenarios, categories and structure please refer to this MSDN article: http://msdn.microsoft.com/en-us/library/cc512374.aspx

This post is focusing on issues and problems faced with WCF running on IIS.

Recently, I had a working WCF service that I wanted to deploy on one of my client’s web servers. The webserver is a simple Windows 2008 web server with obviously web server role turned on.

After publishing the WCF service, I logged on the web server’s IIS 7 management console and started creating the webservice as a separate website. Please note that you may be able to create the web service as a web application under the default website or any website if you want (haven’t tried it before but should work). But do NOT do this if your default website is a Microsoft Dynamics CRM application server. Reason being that if you do add a webservice under Microsoft Dynamics CRM website, you will probably cause problems and major issues with authentication, client policies, cross domains, etc, etc..

So, I created my WCF service as a new website. tryied to browse to the service .svc file (webservice.svc for example) but I got an error 404, no https handler avaialble to process this request. Error details says: “The page you requested has a file name extension that is not recognized, and is not allowed.”

Looking in my handler mappings, I found out that there is no resource Dlls or managed code, to handle responses for *.svc request type. Normally you should have one of three *.svc mappings:
1- svc-Integrated handling *.svc – handler is System.ServiceModel.Activation.HttpHandler
2- svc-ISAPI-2.0-64 handling *.svc – handler this time is IsapiModule
3- svc-ISAPI-2.0 handling *.svc – handler is also IsapiModule.

If you dont have these handler mappings (although you normally should), make sure you add them manually. If you try to add them and can’t find any of the modules: IsapiModule or System.ServiceModel.Activation.HttpHandler, then go to Modules and make sure these two modules are enabled and avaialble.

This fixed my issue. But, you may have another problem:

– Make sure that in windows features, you have both WCF options under .Net framework are ticked. So go to Control Panel –> Programs and Features –> Turn Windows Features ON/Off –> Features –> Add Features –> .NET Framework X.X Features. Make sure that .Net framework says it is installed, and make sure that the WCF Activation node underneath it is selected (checkbox ticked) and both options under WCF Activation are also checked. These are:
* HTTP Activation
* Non-HTTP Activation
Both options need to be selected (checked box ticked).

– Make sure that the website is running as ASP .NET 2.0

– If you are still having problems, try Registering WCF From The Command Prompt . You can do this by running the following command from a command prompt (In Windows 7 you need to run command prompt as administrator – right click on shortcut and then click run as administrator).
To register WCF from the command prompt, use the following commands:

Navigate to WCF folder:

cd %SYSTEMROOT%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

Where %SYSTEMROOT% is usually by default C:/Windows/

Then run this command:
ServiceModelReg.exe /i /x

Alternatively just run the following command:
%SYSTEMROOT%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe /i /x
– If this still doesn’t work, please try the steps listed in this blog post: http://bloggingabout.net/blogs/jpsmit/archive/2007/01/17/wcf-http-404-when-hosted-in-iis.aspx

I haven’t tried any of these steps before but some people found it useful.
All solutions are provided as is with no guarantees.

Please write a comment with any questions or experience you have with deploying WCF on IIS 7
Hope this helps.

Thanks.

Introduction to LLBLGenPro – All you need to know to get started with LLBLGen Pro – Hello World! LLBLGen Pro

In one of my latest projects, I found the client extensively using LLBL Gen Pro which I have never used before. After few hours of playing around with it, I managed to find my way round it just enough to the level that I need to get the basic functionality working.

Hence, for this reason, I thought I will write a post to show the basic and first steps for using LLBL Gen Pro to be used as an introduction by anyone who is, like me few weeks ago, was completely new to LLBLGen Pro.

As it is always the case in most of my posts, I focus on the basic start up functionality straight to the point but if you need further detailed instructions and guides on LLBL Gen Pro then I definitely suggest you start with the online documentation and especially the concepts article. http://www.llblgen.com/documentation/2.6/Concepts/concepts_entitylistview.htm

For the full LLBL Gen Pro 2.6 Documentation, go to their online user documentation at: http://www.llblgen.com/documentation/2.6/hh_start.htm

The main feature of LLBLGen Pro is that it automatically creates a data layer for any application to use. The data layer provides full access and complete data management DML And DDL features for you allowing complete control of the specified Database.

LLBLGen Pro generates this Data layer for a variety of database types including full support for the following data bases: Firebird, IBM DB2, MS Access, My SQL, Oracle 8,9,10 and 11, Sybase, PostgreSQL and of course almost all Microsoft SQL Server version such as SQL Server 7, SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server Express and MSDE drive. wow! You literally don’t need to write any code, it’s a full data layer created for you to access any database from any of the above types.

LLBLGen Pro generates the code as a .NET project built in your chosen development language (C# or VB.NET). LLBLGen Pro accesses your database using servername and login id and password in case of DB specific Authentication or just windows authentication if your database allows that. It will then generate the code along with the web.config that already has the connection string to your Database.

Now to use LLBLGen Pro you need to do the following:

First thing to do is obviously to install LLBLGen Pro and add the license file to its installation folder. Next is to run the application from the start menu.

Once LLBLGen is loaded, you need to create a new project. Go to File –> New project. Fill in the details as follows:

Name: Project name, Create: User, Location: Location where to create the LLBLGen project file.

Select the database driver (database type), database server name and  Authentication type, then hit Connect.

Once connected to the server, you will get the list of available catalogs (DataBases) within this database server.

Select your chosen Database(s) (you can select more than one) and then click Create.

Once you have done that, the project is now created and saved at the selected location.

Next step is to go and add the tables, views and stored procedures. To do this, right click on Entities and click on add new entities mapped on tables. To add views, right click on Entities and add entities mapped on views, and so on.

Once you have added all your tables and views, they will be all created as Entities. i.e. converted to classes in LLBLGen Pro generated code.

Now you got the project ready for generating the code, there are much more detailed configuration that you can do if you want to create complex code, but for most straight forward data layers, this project configuration is enough.

Now go to Project –> Generate, and you will get the code generation screen. This is where you need to specify the details about the generated code and the project holding it.

The Generate Project Window has 3 tabs. For simplicity and straight forward, not complicated, first project, you only need to fill in the General Settings details. They are the main and most used settings. You can use more complex ones later if you want to.

Target Language: Language to generate the LLBLGen Pro code in (I only tried C#).

Target Platform: Which .NET framework (.NET 3.5 for latest)

Root namespace: Namespace for the generated project

Template Group: Choose self servicing. This is the default and straight forward option in my view.

Destination Root folder: Folder where all generated code files will be created.

Everything is ready now, Click Generate!

Done.

The generated code can be found at the destination root folder specified in the previous step. You will see that the generated code is of type class library. Now go to your solution and add the generated project (Right click on solution –> add existing Project –> new LLBL generated project).

Next and final step in this LONG post is to just add another project that you want to use to work with the data layer that LLBLGen Pro has just created for you as a new project.

Using LLBLGen Pro classes is easy and straight forward but this is the subject of another post, if anyone is interested?!

Please comment if you want me to blog on using LLBLGen Pro generated code basics and introduction.

Problem Running WCF on Visual Studio 2008 and Windows 7 – could not find host – page timeout

This post is about a problem that I have had recently with visual studio .Net 2008, WCF and Windows 7.

I have a working WCF service (add to the solution by another person) which I am trying to run from within my visual studio 2008. Normally, you should go to your project, right click on it and click on add service reference. You should then search for services within the solution and add the WCF service which is in the same solution. This will even work if it is in a different solution as long as the WCF service is in a Visual Studio solution that is currently open.

When I try to search for this service and add it, I got timeout error, error downloading service information and if I try to run the service itself by navigating to it from Visual studio, the wcfservice.svc file itself does not open. It comes out with could not find host, page cannot be displayed and timeout errors.

After spending sometime trying to find out what is causing it, I found out that I have miraculously forgot to run Visual studio 2008 as Administrator. Basically, when you want to run visual studio 2008, you need to right click on its shortcut icon (in the task bar in windows 7) and click on Run As Administrator. This way, you will be running Visual studio as an administrator. Even if you are an administrator on the machine, you will not be running visual studio as admin if you just click on it to open.

I know this issue sounds simple and not a lot of people will have that but, I believe the post might be helpful to someone. I can’t recall having this problem on Windows server 2003, windows server 2008, windows vista or even winsows XP! It’s only happening on this development machine which was built for me using Windows 7.

If you want to stop having to right click on the shortcut icon and click on run as administrator everytime, there is a simple way to make an application to run as administrator by default permanently. Go to visual studio .net shortcut on the start menu (or the other application that you want it to always run as administrator), right click on the visual studio application icon, and click on properties. In the application properties, click on compatibility tab and then check the privilege level option that says “Run this program as administrator”.

This should get you to always run visual studio or any other application always as an administrator.

Please comment if you found this post useful.