Simax F1 Simulator

Today, we have released an introductory video of the next challenge we are facing here at Simax: take our technology to the F1 racing field.

In this case, we are developing a replica of the Renault R30: a 2.4L V8 engine which reaches 19.000 rpm and almost 900 hp, for less than 600 Kg… Awesome!

Hope you like it…

Battery charging problems on Samsung Focus (Windows Phone 7)

Yesterday, my Samsung Focus stopped working properly.

I plugged it to the wall for hours, the battery icon showed that it was plugged, but the battery level did not raise. If I unplugged the phone, an immediate message of “Battery critically low” appeared.

After reading some posts, I realized that the battery was in fact being charged, but the OS was not “reading” the battery level correctly.

In my case, as in many others, it was fixed by simply entering the Diagnostics mode of the Samsung Focus, to directly read the “actual” battery level. After that, everything is back to normality.

1.- To enter Diagnostics mode, open the phone keypad and enter: ##634#

2.- To access battery information (and others), type *#2*# in the next keypad that will appear.

And that´s all.

Silver Navigator 1.2 released !

Hi there!

Silver Navigator, ranking top downloads in many countries around the world, is ready for an update, as version 1.2 has just passed through the certification process in the Windows Phone Marketplace. So it´s ready for download!!

This new version includes:

  • Local Searches: hotels, restaurants, shops... (might not be available in all countries)
  • Map rotation
  • Voices volume increased
  • Some minor bug fixes
  • And much more…

You can follow Silver Navigator 1.2 here, and download it from this Zune Link.

ArtWork2_1000x800

Taking advantage of high-level C# features to make our 3D games API or platform independent

In the last few years, programming languages and development tools have evolved quite a bit. Visual Studio is a masterpiece nowadays, and things like Refactoring and Intellisense make our life much easier.
There are other cool features that can be now used in our code, and that are really appropriate to make our 3D engines API-Independent. I´m talking about Generics and Extension Methods.

What is API or platform multi-targeting?

Multi-targeting is writing a software (a game, for instance) that can run in different platforms or use different APIs. Of course, we should try to achieve this with the following constraints:
  • Avoid redundancy as much as possible (as we already saw that Duplicating is wrong).
  • If possible, introduce no performance overhead at all, or at least try to minimize it

When is multi-target necessary?


It is obviously necessary if your application is meant to be distributed for different platforms (XBox, PS3, PC, etc, for example). But making your software multi-target is also very recommendable in other situations, for example when you need to upgrade your technology to a newer version of an API.
For instance, imagine that DirectX11 just came out. You would like to take advantage of some new features of it, but cannot force all your clients to upgrade their graphics cards, so you still need to support DirectX10. The solution is to make your software support both DirectX10 and 11, with multi-targeting. In this article, we will use the case of targeting an application to two different render APIs: SlimDX and XNA.
If you already faced this problem before, you know it can be a serious one, especially if your software was not designed to support multi-targeting from the beginning, and you have API calls scattered all around your code. How do we make the change without needing to re-write the entire software from scratch?
Let’s explore the possibilities:

A macro-C++ approach

When using languages like C++, some people make multi-targeting using Macros:
  • Write all your game-logic code using your own MACRO-named types like: myMatrix4x4, myTexture, etc.
  • Write a header file for each platform, in which all that macros are declared:
#define myVector3 Microsoft::Xna::Framework::Vector3
#define myMatrix4x4 Microsoft::Xna::Framework::Matrix
But remember, MACROS ARE THE SOURCE OF ALL EVIL IN THE WORLD.
Macros easily grow in complexity. Specially if you start making multi-level macro calls. They make debugging and understanding the software a hell on Earth, and are extremely bug-prone, if you are not very careful. They have even been removed from modern languages like C#. So I totally discourage you to use this solution.
  • Pros:
      • Everything arranged for each platform at compilation: no performance penalty.
      • No design effort. Easy development
      • Resolved at compilation: no performance overhead
  • Cons:
      • Make debugging, tracing and maintenance of the software in general a hell in Earth
      • Very bug-prone
      • Not available in modern languages, like C#
      • In my opinion it’s against good practices in software. At least as long as a better solution exists.
      • Compilation of C++ projects which massively use macros can take years to complete, especially if macros are recursive
      • They don´t do the job for every case

The conditional compilation approach

As we have already seen, some parts of your code must be different for each platform, so an obvious and easy way to make your software multi-target is using conditional compilation.
This approach is supported in almost every language, and works by defining compilation constants in your project like: PLATFORM_XNA, or PLATFORM_SLIMDX. Then, each time you find an API-dependent code part, you do something like:
#if(PLATFORM_XNA)
...
#else
...
#endif

  • Pros:
      • Everything arranged for each platform at compilation: no performance penalty.
      • No design effort. Easy development
      • Available in all languages
  • Cons:
      • Ugly and un-elegant code
      • Uncomfortable to understand and trace
      • Your code will grow considerably (too much redundancy)
      • In my opinion it’s against good practices in software. At least as long as a better solution exists.

The layered approach

This is one of the usual approaches. It is related to software engineering more than to an specific language, and involves all the stages of development, since conception and first designs, to the final coding.
What it suggests is dividing your application in “layers”, keeping internal layers for the game-logic related issues, which do not depend on the API or platform at all, and making an external layer that will give output to all that logic, through the API. This way, when you need to target a different platform, only the external layer has to be rewritten.
This external layer, usually deals with things like Rendering, that’s why it’s very typical to find games out there with DLLs like: RendererDX9.dll, RendererDX10.dll, etc.
  • Pros:
      • Elegant
      • Easy to understand, trace and debug
      • Robust, not too bug-prone
      • Available in all languages
  • Cons:
      • It requires a big design effort
      • It can introduce a bit of performance overhead
      • It introduces redundancy of code and information, as some game states has to be stored in several layers
      • It’s sometimes not a feasible solution if the project is already written (the multi-target was not planned from the beginning), as it implies big structural changes.
      • Following this design will give your software a Library or API looking I personally don’t like, as it breaks a bit the consistency of classes, by separating tasks that conceptually should belong to a class into other assemblies. This is one of the points I personally disagree more of this approach. I prefer to keep this consistency, leaving all tasks related to an object inside it’s class. Just an example to show this:
You will end up with lines of code like:
RendererDX9.RenderModel(this);
Instead of the traditional:
this.Render();
Some people would say that rendering an object is not a task naturally belonging to that object. Well, as I said, this is a matter of personal preference, and I prefer the second approach. That’s why in next chapter we will try to make a multi-target system that follows it.

The inheritance approach

This approach is elegant as well (as the previous one). It also related to engineering and planning more to an specific language, and also involves many stages of the development.
Instead of dividing your software in layers, it relies mostly on Inheritance, through a very basic design for classes that are API-Dependant like the next example:
            • Model3DBase
                  • Model3DSlimDX
                  • Model3DXNA
It is quite obvious that we will put in the base class all the non API-dependent code, and the rest in the child classes. For example, the ToString() method has nothing to do with the platform the 3D model will be rendered in. So that code will be in the base class, avoiding rewriting it for each child.
Once we have all the classes divided for each version of the API, in the outer part of your software you just need to choose which kind of Scene to use. Something like: SceneSlimDX or SceneXNA.
This approach works, it’s elegant, easy to understand and trace, and keeps the consistency of classes, but it has a major drawback: for classes like this (a 3D Model), many many member variables and methods will be API-specific, so the amount of code in the base class will be much lower than in the child, dependent classes. This will force you to write a huge amount of duplicated code, and we already said that duplicating is wrong.
  • Pros:
      • Elegant
      • Easy to understand, trace and debug
      • Robust, not too bug-prone
      • Available in all languages
      • It keeps the consistency of classes, allowing us to put the Render method inside the Model3D class, instead of having to take it out to another class.
  • Cons:
    • It requires some design effort
    • It’s sometimes not a feasible solution if the project is already written (the multi-target was not planned from the beginning), as it implies big structural changes.
    • Splitting your types for each API won´t help reducing redundancy in higher code levels too (what will happen when we are going to use the model? which version will be use? Again conditional compilation?)
    • The biggest problem is the redundancy of code mentioned (many code parts will be repeated in the child classes)

So, which one is best?

Again, this is all a matter of personal preference.
Macros are discarded by themselves… too bug-prone, and not present in modern languages. In my opinion, best option is a combination of: a little bit of conditional compilation (in very few cases), and in some cases a bit of layered design too. But whatever we choose, all of them have the same problem: code redundancy.
If only we could reduce that code redundancy…

C# comes to save the day

.Net has been introducing improvements to software development since it’s conception. It saves you time. It saves you money. It saves you headaches. It saves you stress. In my opinion, that’s precisely the strong selling point of .Net.
Microsoft has succeeded in making programmers’ life easier, with no renounce to performance, efficiency or robustness
In the latest releases, .Net is going even further, introducing new ways of development that can, not only make your life easier, but also offer you the possibility to face old problems in new ways. This case is just an example.

Extension Methods

Many times, APIs are similar to each other. You will have textures, you will have 3D models, you will have vertices and faces. Even rendering methods will be probably similar. And it´s a pain having to add conditional compilation just for something like finding the number of vertices in a 3D model mesh:
#if(RENDER_XNA)
            int vertexCount = mMesh.NumVertices;
#elif(RENDER_SlimDX9)
            int vertexCount = mMesh.VertexCount;
#endif
Both XNA and SlimDX offer that information, but the name of the property changes. There are many many cases like this where code changes are just semantics, or just re-arranging stuff. And it´s a pity to add redundancy all around your code for such a simple thing.
We of course can put a “GetVertexCount” method or a “VertexCount” property in our Model3D class, but… What happens when we are working with simple Meshes (no access to our own Model3D type)? Conditional compilation again?
Not yet… Because Extension Methods can help here…

What are Extension Methods?

Extension Methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
So, we can take the type "SlimDX.Direct3D9.Mesh”, or “Microsoft.Xna.Framework.Graphics.ModelMeshPart”, and add a method to it. Just like if we could modify its code.
This way, we are allowed to unify or standardize the interfaces of API-dependent types, to drastically reduce the need for conditional compilation, and therefore code redundancy.

How do they work?

Following what´s explained here, we can easily code the “GetVertexCount” method like this:
public static int GetVertexCount(this Microsoft.Xna.Framework.Graphics.ModelMeshPart pMesh)
{
     return pMesh.NumVertices;
}
 
public static int GetVertexCount(this SlimDX.Direct3D9.Mesh pMesh)
{
     return pMesh.VertexCount;
}
Note: You just need to add that method to a static class in your DLL that holds Extension Methods.
Having this, both XNA´s ModelMeshPart and SlimDX´s Mesh will offer the GetVertexCount method. With the exact same interface. So, any part of our code that wants to have this information won´t need to add conditional compilation nor redundancy anymore.
We can do similar stuff with many many differences between APIs: properties renamed or relocated, methods with different or re-arranged parameters, or even creating methods that exist in one API and not in the other.
The objective is to unify the interfaces of both APIs as much as possible.

What about performance?

We are adding a call to a method where there wasn’t any. So, in theory, we are adding a performance overhead. But here is where the Visual Studio compiler comes to help.
As you already know, there is a thing called Inlining that will help here. When your code is compiled, the compiler will replace any call to the GetVertexCount method with it´s real inner code. So no performance overhead is really added.
However, you should take care with Inlining, as there are several conditions for this to happen:
  • Methods that are greater than 32 bytes of IL will not be inlined.
  • Virtual functions are not inlined.
  • Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.
  • Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.
  • If any of the method’s formal arguments are structs, the method will not be inlined.
More info on Inlining: here, and here and here.

C# comes to save the day (II)

Generics

Since 2.0, .Net introduced Generics, a way to work with variables without specifying what type they are. This is especially useful for cases where the type of those variables is irrelevant. One of the direct and most useful examples that soon appeared is Generic Collections. The logic behind a List or Dictionary of things is the same, no matter what that “things” are.

How can Generics help out here?

Generics introduce two clear advantages:
  • Generics are resolved at compilation, so no performance overhead is introduced at all. In fact, Generics can imply some performance advantages, in certain cases. Read this article (Generics implementation chapter) for more information.
  • Generics will again dramatically reduce the Duplication and redundancy of information and code in our projects.

Reducing duplication even more, with generics

Apart from using Extension Methods, as we have seen in the previous chapter, we can reduce Conditional Compilation and code redundancy even more, with the use of Generics.
Many times, some parts of our code need to add conditional compilation just because types used are different on each API, but the operations performed on them don´t need to know what type they actually are. For instance, if we create a Material class, it will probably hold a list of textures, and the Texture type is API-dependent. Will we need to add conditional compilation every time we want handle that list of textures? Probably not.
Making the Material class to be generic, will allow us to work with Textures, without knowing if they actually are SlimDX or XNA textures:
public class Material<T_Texture>
{
     protected List<T_Texture> mTextures;
}

That reduces redundancy in the Material class, as any management of the List of textures can be done without knowing the type: adding or removing textures, accessing to them, etc.

What if we still need to perform an API-dependent operation in a generic class?

Sometimes, your classes won´t be purely generic, and still will need to perform some operations that are API-specific. In those cases, you can always check what the type of the generic T_Texture actually is.
Just like in the following example, where the generic type is checked to return one type of value or another:
 public static T GetRenderState<T>(this Microsoft.DirectX.Direct3D.Device pSrc, RenderState pState)           
        {
            if (typeof(T) == typeof(int))
                return (T)Convert.ChangeType(pSrc.GetRenderStateInt32((RenderStates)pState), typeof(T));
            else if (typeof(T) == typeof(float))
                return (T)Convert.ChangeType(pSrc.GetRenderStateSingle((RenderStates)pState), typeof(T));
            else if (typeof(T) == typeof(bool))
                return (T)Convert.ChangeType(pSrc.GetRenderStateBoolean((RenderStates)pState), typeof(T));
            else throw new System.ApplicationException("Generic Type invalid");
        }

Using the generic (Material) class

When the Material class is finished, we will probably want to use it in a Model3D class. We just need to do something like:
public class Model3D
{
    #if(RENDER_XNA)
         protected Material<Microsoft.Xna.Framework.Graphics.Texture2D> mMaterial;
    #elif(RENDER_SlimDX9)
         protected Material<SlimDX.Direct3D9.Texture> mMaterial;
    #endif
}

This way, we remove any conditional compilation or code redundancy from the Material class, and add it just a couple of times when declaring and instantiating the mMaterial variable.

Going even further with conditional #using statements

This is pretty obvious, but anyway it might help someone.
Many times, types have the same names in several APIs. For instance, the type VertexBuffer exists in: XNA, in SlimDX and in Managed DirectX.
For such cases, we can reduce conditional compilation and code redundancy even more, with #using statements at the beginning of each code file. Imagine we have a class XXX like the following:
public class XXX
{
    #if(RENDER_XNA)
        protected Microsoft.Xna.Framework.Graphics.VertexBuffer mVertexBuffer;
    #elif(RENDER_SlimDX9)
        protected SlimDX.Direct3D9.VertexBuffer mVertexBuffer;
    #endif
}

In that case, we are adding the conditional compilation just because the namespace of a type changes. It´s much better to add the conditional compilation just once in the #using statements, avoiding to spare them all through your code:
#if(RENDER_XNA)
    #using Microsoft.Xna.Framework.Graphics;
#elif(RENDER_SlimDX9)
    #using SlimDX.Direct3D9;
#endif

public class XXX
{
    protected VertexBuffer mVertexBuffer;
}

Using Generic’s constraints to reduce even more redundancies

We still didn’t mention other possibilities Generics have, like Constraints. Constraints are a way to tell the environment that, even when a type is Generic (like T_Texture), it meets certain constraints, like to have a constructor, or to inherit from a class or interface. Just an example:
public class Model3DBase<T_Material, T_Texture>
    where T_Material : MaterialBase<T_Texture>
{
        protected List<T_Material> mMaterials;

}
This makes an huge difference reducing duplication as now, even specifying no type for T_Material, we will be able to access all the properties and methods specified in MaterialBase.
Other examples:
Constraint Description
where T: struct The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.
where T : class The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)
where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.
where T : <base class name> The type argument must be or derive from the specified base class.
where T : <interface name> The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.
where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
More on Constraints here.

Want to know more on Generics?

This magnificent article on generics will explain you more about this issue.

Conclusion

C# and .Net are offering new ways of facing old problems. This article tried to show how to take advantage of some new features like Generics and Extension Methods in a very old problem: API-independent 3D engines.
So, we took those new functionalities and combined them with old approaches of facing this issue, to come with a new, improved implementation, that has a basic objective: reduce code redundancy.
Hope you liked it.
Cheers!

A highly recommendable Windows Phone 7 game development book…

If you want to start, or become an expert on Windows Phone 7 game development using XNA, I´d highly recommend you to buy a.s.a.p the following book:

http://www.amazon.com/Professional-Windows-Phone-Game-Development/dp/0470922443

It´s written by two masters of XNA and fellow MVPs Chris Williams and George Clingerman, and they did a really really good job.

What are you waiting for? Go get it !!

Desarrollo de videojuegos para Windows Phone 7. Conferencia en Zaragoza

Este próximo miércoles día 30, estaré en Zaragoza dando una charla sobre Desarrollo de Videojuegos para Windows Phone 7. Podéis encontrar más detalles del evento aqui:

http://www.cpilosenlaces.com/site/pages/jornadas-tE9cnicas.php

Y descargar el PDF del mismo aqui: jornadas_tecnicas.pdf

Saludos!

Gravitards for Windows Phone 7

Today, Gravitards has been finally released for Windows Phone 7.

“Gravitards is a skill-based game with amazing graphics and real physics, where you have to drive a ball through many different levels, reaching the end zone (or “gravitard”), without dropping it, while collecting rings distributed all around. You´ll find obstacles, moving parts, force fields, guillotines, ramps, jumps, and even a pinball table to play with. Test yourself by controlling the ball with your device’s accelerometer, with on-screen buttons, or with the keyboard, and get the needed practice to complete all the levels.”

You can download Gravitards directly to your Windows Phone 7 using the following Zune link.

Some other videos and pictures:

 

 

Captura36

Captura38

Captura3

Hope you all like it!!!

3D-O-Matic. Is it feasible to make our favorite shows in 3D?

There has been several attempts to make cartoon TV shows in 3D, or look realistic. For instance, Simpsons’ first attempt looked something like this:

It was really fun, but didn’t actually capture the essence of Homer, which for me is nothing more than this:

Many artists have tried to do so since then, but honestly, they scared me more than make me laugh. Some amazing examples:

Pretty awesome, but they are stills mostly. Hard to animate that. Recently though, I have discovered other examples that seem more feasible to me, as they are just plain 3D models, not so post-processed, and in my opinion they capture pretty well the essence of the characters (from Futurama, in this case):

unti3tled

untitl6ed

un8titled

COOL !

For those of you who always asked themselves how are The Simpsons done, you can check this video (sorry it´s in Spanish only, from Chile TV apparently):

I always thought they had some kind of software to manage camera angles automatically. I even thought sometimes (specially for the most recent seasons) that backgrounds or characters where initially animated in 3D, and then rendered as 2D, but it seems they are animated traditionally.

The video is pretty old though, so things probably changed in the last years.

Some other hilarious examples:

 

untitled

 

un44titled

And some other pics as a present. Not in 3D, but really fun !!, and very appropriate for T-Shirts… ja jaaa:

untitl7ed

 

untitle22d

 

4untitled

All of them come from here.

Cheers!

Simax Forklift Simulator

We are about to release the next Simax simulator. It´s the new Forklift Simulator, a full-featured, next-gen training simulator to learn all the concepts needed to drive and work with a forklift, including basic management of the device´s features, load handling and distribution, driving in every possible situation, dangerous or emergency situations, usual load and unload works, etc. All of our virtual machines are exact replica of their real counterparts: with real motorized joints, mass distribution, and exact layout of controls like levers, joysticks, pedals, etc.

The Simax Forklift Simulator is still a beta release, but will be in the market very soon. You can find more info at: www.simaxvirt.com or at info@simax.es.

 

 

 

 

Using DirectoryInfo.GetFiles returns more files than expected (or how to get exactly what you need, with an exact extension match lookup)

Introduction

I didn’t noticed this behavior of the GetFiles() method until now, I must admit. It’s something not frequent to see, but might happen. And it’s dangerous.
As this post, and the MSDN library itself state, when you use the GetFiles() method with a search wildcard that includes the asterisk symbol, and you include a 3 characters long extension (like *.xml, or *.jpg), the GetFiles() method will return any file whose extension STARTS with the one you provided. That means that a search for *.jpg will return anything with extensions like: *.jpg, *.jpg2, *.jpegfileformat, etc.
This is a quite weird behavior (and not too elegant, I should say), introduced to support the 8.3 file name format. As stated in the above mentioned blog:
“A file with the name “alongfilename.longextension” has an equivalent 8.3 filename of “along~1.lon”. If we filter the extensions “.lon”, then the above 8.3 filename will be a match.”
That’s the reason to make the GetFiles() method behave that way. The official MSDN explanation:
Note
When using the asterisk wildcard character in a searchPattern (for example, "*.txt"), the matching behavior varies depending on the length of the specified file extension. A searchPattern with a file extension of exactly three characters returns files with an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern. A searchPattern with a file extension of one, two, or more than three characters returns only files with extensions of exactly that length that match the file extension specified in the searchPattern. When using the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files in a directory, "file1.txt" and "file1.txtother", a search pattern of "file?.txt" returns only the first file, while a search pattern of "file*.txt" returns both files.
In my case, I had a bug in my software because I temporally renamed an XML file to xxx.XML2222, just to wipe it out of the application. The program was still reading it, what made it had a wrong behavior.

A workaround for this issue

If you want to prevent this behavior, you will need to do a manual check for the returned array of FileInfo classes, to remove those not matching your pattern. An elegant way to do so, is to write a MethodExtender to the DirectoryInfo class, like the following one:
/// <summary>
/// Returns array of files that matches the search wildcard, but with an exact match for the extension.
/// </summary>
/// <param name="pSearchWildcard">Search wildcard, in the format: *.xml or file?.dat</param>
/// <returns>Array of FileInfo classes</returns>
public static FileInfo[] GetFilesByExactMatchExtension(this DirectoryInfo dinfo, string pSearchWildcard)
{
         FileInfo[] files = dinfo.GetFiles(pSearchWildcard);
         if (files.Length == 0)
             return files;
 
         string extensionSearch = Path.GetExtension(pSearchWildcard).ToLowerInvariant();
         List<FileInfo> filtered = new List<FileInfo>();
         foreach (FileInfo finfo in files)
         {
             if (finfo.Extension.ToLowerInvariant() != extensionSearch)
                 continue;
             filtered.Add(finfo);
         }
         return filtered.ToArray();
}
This way, just by the regular GetFiles() method of the DirectoryInfo class, you will find now the brand new GetFilesByExactMatchExtension(), which will have the desired behavior.
Note: In order to be able to use this method in a class, just like any other MethodExtender, you will need to include a “Using” statement to the extension method’s namespace.
Hope it helps !

Enabling/Disabling properties at runtime in the PropertyGrid

Many people knows about the benefits of using PropertyGrids in user interfaces.
You probably know about the System.ComponentModel namespace, and how it can help you customizing the behavior of classes and their properties when edited through controls like the PropertyGrid. One of the attributes you can find in that namespace is the ReadOnly, which will make a property to be read only and appear in gray (even if it has the Set accessor).
The problem with this attribute is that it must be defined at build-time. Sometimes, it is very useful (and improves the User Experience quite a bit), to enable or disable properties at runtime.
Imagine the following example, where we have a “UserData” class:
public class UserData
{
...
 
        public string Country
        {
            get { return mCountry; }
            set { mCountry = value; }
        }
        public string State
        {
            get { return mState; }
            set { mState = value; }
        }
}
Now, imagine you want the user to fill the “State” field only in the case he selected U.S. as his Country. In such a case, you need to make this change at Runtime.
There are several solutions for this, but I find the following one to be the most elegant, as it´s coded in the “UserData” class itself. The final code looks like:
[RefreshProperties(System.ComponentModel.RefreshProperties.All)]
[ReadOnly(false)]
public string Country
{
  get { return mCountry; }
  set
      {
      mCountry = value;
      PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this.GetType())["State"];
      ReadOnlyAttribute attribute = (ReadOnlyAttribute)
                                    descriptor.Attributes[typeof(ReadOnlyAttribute)];
      FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
                                       System.Reflection.BindingFlags.NonPublic |
                                       System.Reflection.BindingFlags.Instance);                   fieldToChange.SetValue(attribute, mCountry != "U.S.");
      }
}
[ReadOnly(true)]
public string State
{
   get { return mState; }
   set { mState = value; }
}

Some Tips

1.- We obviously change the “ReadOnly” attribute of the “State” property in the setter accessor of the property “Country”. That´s the exact point where we know if State should be enabled or disabled.
2.- It is important to add the “RefreshProperties” attribute to the “Country” property. That will force the PropertyGrid control to refresh all it’s properties every time the value of “Country” changes, reflecting the changes we made to the attributes of “State”
3.- In order to work properly all of this, it is important to statically define the “ReadOnly” attribute of every property of the class, to whatever value you want. If not, changing the attribute at runtime that way, will wrongly modify the attributes of every property of the class.
Hope it helps!

More Info

At The Code Project
At C-Sharp Corner
Cheers!

Como agregar tus contactos de Outlook a Windows Phone 7, sin Exchange, sin aplicaciones ni cuentas de correo adicionales

Como ya sabréis, por el momento Windows Phone 7 no se sincroniza localmente con OutLook. Si no tenéis un servidor de correo compatible con Exchange (ese es el modo recomendado de sincronización para WP7), podéis realizar la sincronización con el dispositivo de varias formas, descritas en detalle aqui.

Companion Link ha sacado una aplicación que supuestamente realiza la sincronización, pero me parece un pufo, ya que necesita de una cuenta de correo de Google para funcionar. O sea, más de lo mismo, y encima te cobran 39 $ por la broma. Podéis descargar la versión trial aqui.

En fin, que a falta de que salga algo mejor, por ahora la mejor manera de añadir (que no sincronizar), tus contactos (solo tus contactos, ni tus citas, ni ná) a tu WP7 es utilizando uno de los métodos sugeridos en el enlace de arriba: a través de un fichero CSV.

Requiere tener un Windows Live ID (que no una cuenta de HotMail), pero mucha gente ya tiene uno, aunque solo sea para jugar a la XBox, así que no es una solución tan mala. Lo que haremos es subir nuestros contactos a la cuenta de Windows Live, con la que el Windows Phone sí se sincroniza.

1.- Preparar tus contactos

Como descubrirás más abajo, el proceso de importación de contactos de Windows Live es bastante puñetero. Falla por un montón de motivos, y algunas veces simplemente ni te dice por qué.

Por mi propia experiencia, para evitar que el proceso falle, revista en OutLook tus contactos, sobre todo los números de teléfono almacenados, ya que al parecer no pueden contener caracteres distintos de a-z A-Z y 0-9.

Así que elimina cualquier aparición de cosas como:

  • Espacios
  • Prefijos de países con formato +34 y similares. Substitúyelos por “0034”.

2.- Exportando tus contactos a un fichero CSV

Si tiene Outlook 2010

  1. Empiece por abrir Microsoft Outlook 2010 en el equipo.
  2. Haga clic en Archivo y, a continuación, en Opciones. Haga clic en Avanzadas y, en la sección Exportación, en Exportar.
  3. En el Asistente para importar y exportar, seleccione Exportar a un archivo y haga clic en Siguiente.
  4. Seleccione Valores separados por comas (Windows) y haga clic en Siguiente.
  5. Seleccione Contactos como la carpeta de origen de la exportación y haga clic en Siguiente.
  6. Elija una ubicación de archivo y un nombre de archivo, y haga clic en Siguiente.
  7. Haga clic en Finalizar. Los contactos deben haberse exportado como archivo CSV.
  8. Siga las instrucciones indicadas a continuación en Importar el archivo CSV de Outlook a Windows Live.

Si tiene Outlook 2007
  1. Abra Microsoft Outlook 2007 en el equipo.
  2. Haga clic en Archivo y, a continuación, en Importar y exportar.
  3. En el Asistente para importar y exportar, seleccione Exportar a un archivo y haga clic en Siguiente.
  4. Seleccione Valores separados por comas (Windows) y haga clic en Siguiente.
  5. Seleccione Contactos como la carpeta de origen de la exportación y haga clic en Siguiente.
  6. Elija una ubicación de archivo y un nombre de archivo, y haga clic en Siguiente.
  7. Haga clic en Finalizar. Los contactos deben haberse exportado como archivo CSV.
  8. Siga las instrucciones indicadas a continuación en Importar el archivo CSV de Outlook a Windows Live.

3.- Importando tus contactos en tu Windows Live

  • Importar el archivo CSV de Outlook a Windows Live
    1. Abra un explorador web, vaya a http://contacts.live.com (http://contacts.live.com) e inicie sesión en su cuenta de Windows Live.
    2. Haga clic en Administrar y, a continuación, en Importar.
    3. En la página "Agregar personas", haga clic en Outlook.
    4. Seleccione el botón de radio "Microsoft Outlook (usando CSV)".
    5. Vaya al archivo CSV que exportó a su equipo [pasos 1-7]. 
    6. Haga clic en Importar contactos. Si ya ha agregado la cuenta de Windows Live Hotmail al teléfono, ha terminado. Los contactos se sincronizarán automáticamente con el teléfono cuando inicie sesión en Windows Live desde el teléfono.
      Nota Windows Live tiene un límite de tamaño para carga de archivos CSV de 500 KB. Si su archivo CSV supera los 500 KB, no se cargará y se mostrará el siguiente error: 

      El archivo que deseas importar es demasiado grande. Elimina algunos contactos e intenta importarlo de nuevo.

      Para solucionar este problema, abra el archivo CSV en Excel y divídalo en varios archivos. De esta forma podrá cargar los archivos en Windows Live siempre que el tamaño total de cada archivo no supere el límite de 500 KB.
      Nota Windows Live tiene un límite de almacenamiento de 6500 contactos por usuario.

  • Si no ha agregado la cuenta de Windows Live Hotmail al teléfono, siga estos pasos:
    1. En Inicio, vaya a la izquierda en la lista Aplicación, puntee Configuración y, a continuación, Correo electrónico y cuentas.
    2. Puntee Agregar una cuenta y, a continuación, Windows Live.
    3. Escriba la dirección de correo electrónico y la contraseña, y puntee Iniciar sesión.
    4. Una vez iniciada la sesión, los contactos de Windows Live Hotmail se sincronizarán con el teléfono.

Ultimo consejo

Es muy probable que a pesar de las precauciones del punto 1, el proceso te falle en algún punto. Que sepas que Windows Live habrá importado todos los contactos que haya podido hasta que se haya producido el fallo, así que te recomiendo ir a revisar tus contactos, y mirar cual es el último que se añadió.

Una vez sepas cual es, abre el fichero CSV. Te recomiendo hacerlo con WordPad –desactivando el ajuste de línea-, ya que si lo salvas con Excel le cambiará el formato o la distribución de caracteres y no podrás volver a utilizarlo para importar (simplemente te dirá que el fichero está vacío).

Una vez lo tengas en WordPad, borra todas las líneas de los contactos ya agregados, y ve al contacto siguiente al último que se agregó. En él, busca algún carácter extraño que pudiera haber producido el error (si no encuentras nada raro, simplemente borra la línea de ese contacto). Salva el fichero, y vuelve a repetir el proceso.

Así sucesivamente hasta que completes la importación.

Es un rollo, lo sé, pero al menos te permitirá tener todos tus contactos en el móvil.