Tag Archives: .NET

Using Google’s LibPhoneNumber in Microsoft.NET with C#

LibPhoneNumber from Google is an awesome library. LibPhoneNumber is a Java, C++ and Javascript library for parsing, formatting, storing and validating international phone numbers. You can input any phone number from over the world and the lib is telling you if the phone number might be valid, from which country the phone number is and the number format which is common for the number type and region.

 

libphonenrresultsmsmsmssm

 

Well, I was looking for such functionality, because our CRM users have to enter phone numbers from all over the world and we want to format and validate the phone number. Unfortunately there is no C# or VB.NET version available from this great Google library so I ended in doing some tests to integrate them into Microsoft.NET environment.

 

The first try

I’ve build my own JavaScript function the get the needed functionality running (region code, number formatting) in my own html site. Then I merged all related Google JS files from the closure-libaray into one single file with help of the Google closurebuilder.py. This task is very good documented by Google.

So, after that I was looking for a JavaScript engine running in .NET, so that I can execute JS-code in managed .NET runtime. I thought the DLR support of .NET would be the best environment to do this. Unfortunately there is no official JS engine from Microsoft so far. So I ended in trying some engines found on codeplex.com. javascriptdotnet.codeplex.com did the job. This engine can interpret the Google JS file (which has a size of ~500kb and is quite big) and returns the correct result. I should mention here that other engines did also work but sometimes with a wrong result. But stop, there is still a problem with this JS engine: it does not run under 64bit system. This is because the engine used the v8 engine from Google behind the scenes and the v8 only supports 32bit (x86) architectures. There are some hacks to use v8 under 64bit but these seems to be too much experimental.

 

Second try

I’ve tried to convert the Java code into C# manually and by a converter tool. Result: no success, because there are too much of specialties in the code and my java knowledge is somewhat old.

 

Third try

There is a C++ version available and I thought it should be possible to use it via p/invoke within .NET. But there seems to be a similar issue with 32/64bit systems. So I did not further investigate into this possibility.

 

Last and successful try

So finally I’ve tried to use the phone metadata directly within C#. Google’s metadata behind the Java project is a very well structured XML document written by Google which contains a lot of regex patterns. These patterns build a structure to find out to which country a number belongs and which number format is common for a specific region.

 

phonemetadataxmlofromgooglednmdmdmdm

 

I was very surprised how easy it was to use this metadata XML in my own code. With just a few lines and within two hours the prototype was working…. well, to finalize the library has cost me another day…

 

Source

At the end I thought it is worth to share my code with other C#/VB.NET folks. You can grab the code here. It does not everything the original Google library can do; I just implemented the cases that we need in our project (resolve the region and common format for any phone number). Here is a quick example of the C# code (from the Unit Test project…)

 

phonenumberresultincsharp

 

Let me see if someone other is interested to use this C# version. If so i can put the code onto codeplex.com or so. Any feedback is highly appreciated.

 

Happy coding

Advertisements
Tagged , , ,

.NET Reflector – Working with different profiles for Silverlight and the Core Framework

.NET Reflector is a one of the 10 Must-Have utilities for .NET developers. If you need to work with more than one version of the .NET Framework, especially with Silverlight and the Core Framework (3.5 or 4.0) you will find you reconfiguring your Reflector every time you changing the platform. For me this is very annoying tasks for which I was looking for a solution.

 

Different config files

.NET Reflector stores it settings into a config structure which includes all assemblies from the left tree in the application.

Recently I noticed the ability to start .NET Reflector with command line arguments. One command line argument allows to specify a config file path:
"C:\Program Files\Reflector\Reflector.exe" /configuration:”Reflector.cfg”

Unfortunately there seems to be a bug in version 6.1.0.11. When closing Reflector it reports the following error:

clip_image001

When changing the config-path to an absolute syntax then it works fine:
"C:\Program Files\Reflector\Reflector.exe" /configuration:”C:\Program Files\Reflector\Reflector.cfg”

Creating different profiles

First create different .NET Reflector shortcuts for each profile you want to have. In my case these are Silverlight, .NET 3.5 and .NET 4.0.

clip_image002

Edit every shortcut and add the /configuration argument to every shortcut with a different name as config file. The config file must not exists at this time.

My shortcuts are as following:

  • "C:\Program Files\Reflector\Reflector.exe" /configuration:"C:\Program Files\Reflector\DOTNET40.cfg"
  • "C:\Program Files\Reflector\Reflector.exe" /configuration:"C:\Program Files\Reflector\DOTNET35.cfg"
  • "C:\Program Files\Reflector\Reflector.exe" /configuration:"C:\Program Files\Reflector\Silverlight.cfg"

clip_image003

Now start each profile with its shortcut. .NET Reflector will not find a config and asks you which default assembly list you want to use. Select the version matching to your shortcut and repeat this for every shortcut you have created.

clip_image004

 

Existing Add-Ins

.NET Reflector has a clear and simple config file structure. Therefore you can easily copy and paste your favorite Add-Ins from one config file to another config file.

image

 

Improving startup

Working with Vista/Windows 7 makes it very easy to find programs via the start menu. To use the program search, just put a copy of your shortcuts into your start menu folder (or a subfolder in it).

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\MyStartMenuLinks

image

Now you can type in “Reflector” into your start menu search box and you get a selection of different .NET Reflector profiles.

clip_image007

For me these profiles are very helpful during my daily coding life.

Tagged , ,

VS 2010 Unit Test Problem with DataSet and Remoting

We ran into problems when using Visual Studio 2010 Unit Tests targeting Framework 3.5.

We use Visual Studio 2010 for our development, but we still use .NET Framework 3.5, because our customers a not ready to run .NET 4.0 applications.

Problem description in detail

When trying to transfer a DataSet instance over .NET Remoting and the executing client is a unit test environment, then it fails with an exception: “AssemblyResolveException…System.Data 4.0.0.0 not found…”

.NET Remoting uses the XmlSerializer to serialize and deserialize DataSets over Remoting boundaries.
The XmlSerializer itself generates a dynamic in-memory assembly for each root-type in the object graph it serializes. This assembly is used to serialize or deserialize the object graph. That means initially the XmlSerializer creates a dynamic assembly with a reference to System.Data 4.0.0.0, because Visual Studio 2010 executes its Unit Tests with the runtime 4.0.

On server side .NET Remoting is trying to deserialize the DataSet of Version 4.0.0.0 (because of the System.Data 4.0.0.0 reference on client side). The deserialization process fails, because the server is running with Framework version 3.5.
Unfortunately VS2010 does not allow setting another Framework version for unit test projects, only version 4.0 is supported (http://connect.microsoft.com/VisualStudio/feedback/details/483939/unable-to-change-target-framework-version-on-unit-test-projects).

Possible solutions so far

  1. Migrate client and server to .NET 4.0
  2. Run unit tests with VS 2008
  3. Implement the AssemblyResolve event on server side and redirect to the System.Data 3.5.0.0
  4. Add an assemblyBinding element to the server’s config file to redirect System.Data 4.0.0.0 to System.Data 3.5.0.0
  5. Waiting for a new Visual Studio Version which supports different target frameworks for unit test projects.

Our solution

We use the assemblyBinding element to redirect the System.Data 4.0.0.0 assembly request to System.Data 3.5.0.0. If we put the following config section into our application server app.config then we are able to use VS2010 for our Unit Tests targeting Framework 3.5.

<runtime>
   <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089"/>
          <bindingRedirect oldVersion="4.0.0.0" newVersion="2.0.0.0"/>
        </dependentAssembly>
   </assemblyBinding>
</runtime>  

 

Resources

Tagged ,

Be careful when using WeakReference.IsAlive

The property WeakReference.IsAlive returns true when the target instance to which the WeakReference is pointing to is alive. While IsAlive retuns true there is no guarantee that the Target was not collected in the meantime, because the GC can run at any time between any instructions. The following code can run into a NullReferenceException.

if (_weaRef.IsAlive)
{
    MyClass obj = (MyClass)_weaRef.Target;
    var val = obj.ToString();
} 

The correct usage pattern with the WeakReference  should be as following:

// create a temporary reference to the target
MyClass obj = _weaRef.Target as MyClass; 
// when not null then the target is alive
if (obj != null)
{
   var val = obj.ToString();
}
 

The MSDN documentation declares this problem in the Remarks section as following: “Because an object could potentially be reclaimed for garbage collection immediately after the IsAlive property returns true, using this property is not recommended unless you are testing only for a false return value.”

Update: I found this blog post from Chris Lvon in which he explains the problem in detail.

Tagged ,

Random values generator for different needs

Currently I’m working on a large Silverlight project where we often need random values for testing purpose during UI development or unit testing.

Recently I’ve implemented a RandomProvider class to generate random values for different needs such as simple values like int, short, long, byte, DateTime, Timespan, Thickness, string as well as complex types such as words, addresses, phone numbers, company names, email adresses, names and so on.

 

image

 

Below is a list with the common method implemented in the RandomProvider class.

    RandomProvider.NextBoolean();
    RandomProvider.NextShort();
    RandomProvider.NextInt();
    RandomProvider.NextLong();
    RandomProvider.NextUShort();
    RandomProvider.NextUInt();
    RandomProvider.NextULong();
    RandomProvider.NextDouble();
    RandomProvider.NextSingle();
    RandomProvider.NextDateTime();
    RandomProvider.NextDate();
    RandomProvider.NextTimeSpan();
    RandomProvider.NextThickness();
    RandomProvider.NextString();

    // returns a random string from the given input parameters
    RandomProvider.NextString("value1", "value2", "value3");

    // generates a "lorum ipsum" word combination
    RandomProvider.NextWords(10);

    // returns a value from the given input parameters
    RandomProvider.NextValue<FontWeight>(FontWeights.Normal, FontWeights.Black, FontWeights.Bold);

    // returns a random enum value from the given enum type 
// If the enum is using the FlagsAttribute (enum values as bit flags),
// it may return a combination of these enum values.

RandomProvider.NextEnum(typeof(RandomProviderTestEnum)); RandomProvider.NextColor(); RandomProvider.NextSystemColor(); RandomProvider.NextSolidBrush(); RandomProvider.NextLinearGradientBrush(); RandomProvider.NextFirstname(); RandomProvider.NextLastname(); RandomProvider.NextSalutation(); RandomProvider.NextEMail(); RandomProvider.NextWebLink(); RandomProvider.NextPhoneNumber(); RandomProvider.NextStreet(); RandomProvider.NextCity(); RandomProvider.NextCompany(); // returns a complex object with firstname, lastname, salutation, eMail, weblink, street, city name, company. // email, phone number and weblink are connected to firstname, lastname and the company. RandomProvider.NextContact();

 

Most of the methods above provides on overloaded signature which takes the minimum and maximum range of the random value. See the example below:

    RandomProvider.NextInt(10, 10000); 
    RandomProvider.NextTimeSpan(TimeSpan.FromMilliseconds(1), TimeSpan.FromMinutes(1)); 
    RandomProvider.NextWords(10, 1000); 

 

Have a lock to this small demo application to get a feeling what the RandomProvider class gives.

You can download the source here

Have fun.

Tagged , ,

Microsoft .NET Innovation Award

Last week, we got an Innovation Award from Microsoft for our Silverlight Client called “evidence nova“.

image

The award was presented at the Tech Days ’09 in Bern (CH).
image 
(http://www.microsoft.com/switzerland/msdn/de/techdays/default.aspx)

What is evidence nova?

evidence nova is a full-frame Silverlight client framework on top of the existing evidence application server. The client framework loads the views (XAML from DB), behaviors and related data from the application server through WCF/IIS. The application server is written in .NET 3.5 too.

image
For more information please see: http://www.evidence.eu

The Award

Here you can see our Award as a Silverlight Deep Zoom Image.
http://rnd.glauxsoft.ch/nova

image
(Please note: there are 4 sub-pictures embedded. Three in the corners of the glass and one above the “i” of evidence.)

The video

To get a first impression about our client concept, you should watch this short video from the “April 2009 Preview” version.

image 
http://rnd.glauxsoft.ch/novashowcase

(Why this movie is in flash? Unfortunately this is a problem in Silverlight 2.0. Videos where the height is greater than 576 or the width wider than 1024 are not played correct. Please see here for more information: http://silverlight.net/forums/t/6019.aspx ).

The live demo

The “April 2009 Preview” version is available as live demo here:

image
http://rnd.glauxsoft.ch/evidenceNovaWeb/index.html

(Username/Password: Demo/demo)

UPDATE: Screencast from Tech Days ’09

The screencast from the keynote where our evidence nova Silverlight client was presented is now available also.

FirstFrame

http://blog.thekieners.com/2009/04/30/evidence-nova-screencast-from-tech-days-09-available/

Tagged , ,

Showcase (Part 2): evidence crm – Avaya Contact Center

Yesterday we repeated the showcase for the Avaya Sales and Presales in the meeting room from CASSARiUS service delivery in Zuerich.

Please see on this earlier post for more information: http://blog.thekieners.com/2009/02/09/showcase-evidence-crm-avaya-contact-center/

 

Here are some impressions.

My presentation desk

IMG_3598

The whole equipment (Avaya Contact Center at the wall)

IMG_3594

UPDATE: See the video from the presentation here: http://blog.thekieners.com/2009/04/27/showcase-evidence-crm-avaya-contact-center-the-video-from-presentation-is-now-available/

Tagged , , , ,

US TechEd 2008, Orlando Florida

Manuel and I visit the US TechEd this year. We started a client project at Glaux Soft based on the Silverlight technology. The main reason to visit this conference is to get more information about Silverlight 2.

We stay in the Buena Vista Resort (no it hasn’t anything to do with Microsoft Vista…)

hotel

The Conference

It is my first time I saw Bill Gates live.

DSC02410

The Convention Center

The dimensions here are very big. Here are some pictures to illustrate it.

The convention center

ConventionCenter

IMAG0049

IMAG0051

IMAG0054

IMAG0053

IMAG0128

I was there… 🙂

DSC02403

The entrance

DSC02388

The registration desk (or lane?)

DSC02392

DSC02391

700 Desktops only for Hands on labs!

IMAG0058

The meal area

DSC02417

Exhibitor area

DSC02421

Gate to the session rooms…

DSC02440

 

Here a video (Silverlight required)

Universal Studios

On Wednesday evening Microsoft hired the universal studio for all TechEd attendees.

IMAG0087

I was in the Kwik-E-Mart!

IMAG0108

Tagged , ,