Solibulo

Uninteresting things

How to improve the much-to-be-desired Silverlight installation experience?

by softlion 29. July 2009 10:02

The Silverlight installation in all browsers is confusing, unsettling, and scary.

 

Update 09/2009 : you can get Microsoft's white paper and sample code about Silverlight installation.

Because of the numerous security warnings and lack of options other than to abort installation, you unfortunately get the false impression that Silverlight is a Trojan horse of sorts that "could infect and harm your computer with viruses and malicious code" with no apparent way to protect your computer other than agreeing to install it and hope for the best.

In addition you have to download a file then go find it then execute it.

It is a step that many people finds frustrating.

It will likely be a reason why they never get Silverlight installed on their machine.

And a reason I will lost them as customers.

 

Silverlight installation experience in FIREFOX 3:

  • see: the graphic button to "Install Microsoft Silverlight" (which I put in my object tag)
  • click the button
  • see: "you have chosen to install Silverlight 3.0" [save file] [cancel]
  • click [save file]
  • click [save]
  • (sit there wondering what happened)
  • ...eventually ask someone what to do or get lucky and right click download message and choose "open"
  • see: "silverlight 3.0.exe" is an executable file...may contain viruses...malicious code...harm your computer...use caution...are you sure?... [OK] [Cancel]
  • in spite of the fear that I am infecting my computer with "viruses and malicious code", I click [OK]
  • see: "Security warning...may potentionally harm your computer..." [Run] [Cancel]
  • fearfully click "Run"
  • says: "extracting files...Install Silverlight 3" one button: [Install Now]
  • click [Install Now]
  • says: "Silverlight is being installed on your computer", then shows checkbox "enable microsoft update (recommended) ... privacy statement..." [Next]
  • click [Next]
  • says: "Installation Successful, you may have to refresh the web page..." [Close]
  • click [Close]
  • go back to web page and click the refresh button on browser
  • I see the silverlight application, success.

Silverlight installation experience in INTERNET EXPLORER 6/7/8:

  • see: the graphic button to "Install Microsoft Silverlight" (which I put in my object tag)
  • click the button
  • see: "To help protect your security...blocked this site from downloading files to your computer" and "did you notice the information bar" [OK]
  • click [OK]
  • (sit there wondering what to do)
  • finally click the bar on top, see "what's the risk?" click "download file" anyway
  • see: "Security warning...may potentionally harm your computer..." [Run] [Cancel]
  • click [Run]
  • watch it download, 15 seconds
  • see: "Security warning...can potentially harm your computer" [Run] [Don't Run]
  • click [Run]
  • says "Install Silverlight 3" one button: [Install Now]
  • click [Install Now]
  • says: "Silverlight is being installed on your computer", then shows checkbox "enable microsoft update (recommended) ... privacy statement..." [Next]
  • click [Next]
  • says: "Installation Successful, you may have to refresh the web page..." [Close]
  • click [Close]

Someone answered:

Well, considering you now know what steps the user is going to have to do you could create a help page for the user. Granted, it isn't the best thing (a simplified install experience would be better, obviously) but at least the user would be able to easily find steps on what is going on.

Source: http://stackoverflow.com/questions/523596/how-to-improve-the-much-to-be-desired-silverlight-installation-experience

Tags:

Bug with Blend 3 RC and sample data

by softlion 25. July 2009 12:26

 

This has been fixed in RTM version : in the "build action" property of all files which are in the SampleData folder a "DesignTimeOnly" value is set so sample data is no compiled in your release project (if you unticked the "Enable when running Application" choice in the datasource property in Blend 3).

 

Update: it is not fixed at all ! The .cs file is still set to "compile" (as the referenced sample data is still in app.xaml this makes sense). This workaround is still needed.

 

In Blend 3 there is a userful feature called sample data which helps design UIs binded to data not currently existing.

 

When using this feature, blend adds a “SampleData” folder in your silverlight project, and new XAML files with their associated codebehind (.xaml.cs). It also modifies your App.xaml to reference the sample data class and creates a new global instance of this xaml.

 

When switching to release mode, your xap file will grow bigger than needed. So in the xaml.cs file there is a conditional compilation symbol which can be define in ‘project/properties/build’ tab to minimize the content of the cs file: DISABLE_SAMPLE_DATA

 

The default .xaml.cs generated by blend 3 contains :

 

#if DISABLE_SAMPLE_DATA
    internal class BoardInfosDataSource { }
#else

 

But when in release mode, the compiler removes all non public unused objects. And your silverlight application will throw an errror (if you use asp:Silverlight you won’t see the error just a blank screen. Use the object tag with onerror set to your javascript instead. See MSDN for more infos.).

 

To correct this set the class public:

 

#if DISABLE_SAMPLE_DATA
    public class BoardInfosDataSource { }
#else

 

Tags:

Syntax Highlighter for ScrewTurn wiki v3

by softlion 24. July 2009 14:34

I’ve upgraded the Syntax Highlighter plugin from Tim Bellette to work with ScrewTurn wiki v3 RC1.

 

Download the

Download the

 

See Tim Bellette blog doc for how to use it.

 

Cheat Sheet

 

<code {language}>…</code>

 

{language}: C# xml … + 23 other languages

 

eg: <code C#>…</code>

Tags:

Useful LINQ extensions

by softlion 2. February 2009 16:13

LINQ is an intuitive and powerful extension to .NET. But it misses a useful method to be able to write code as compact as possible. Look at this code:

   1: var list = from xitem in (XDocument.Parse(xmlText).Root.FirstNode as XElement).Elements()
   2:            select new { keyText = xitem.Name.LocalName, keyValue = xitem.Value };
   3:  
   4: foreach( var keyPair in list )
   5: {
   6:     ... do some action ...
   7: }

 

What if you could write a single line instead of the foreach loop:

   1: list.Action( keyPair => s.Append(keyPair.keyText + "=" + keyPair.keyValue) );

 

Well this is now possible if having this extension method in your project:

   1: public static class LINQExtension
   2: {
   3:         public static void Action<T>(this IEnumerable<T> list, Action<T> action)
   4:         {
   5:             foreach (var t in list)
   6:                 action(t);
   7:         }
   8:  
   9:         public static string Append(this IEnumerable<string> list)
  10:         {
  11:             StringBuilder sb = new StringBuilder();
  12:             list.Action(s => sb.Append(s));
  13:             return sb.ToString();
  14:         }
  15: } 

 

Next is an example usage of these methods to compute the MD5 hash of any string:

   1: // Compute the MD5 hash of a string
   2: public string ComputeMD5Hash( string signatureContent )
   3: {
   4:       StringBuilder signature = new StringBuilder();
   5:       MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(signatureContent)).Action(b => signature.AppendFormat("{0:x2}", b));
   6:       return signature.ToString();
   7: }

Of course it is a bad example, as there is a much more efficient way to do it:

 

return BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(signatureContent)));

 

 

Tags:

A better DeleteExpiredSession stored procedure for ASP.NET sessions in SQL Server database

by softlion 6. January 2009 14:52

The standard ASP.NET 2/3/3.5 SP locks the ASPStateTempSessions table for a long time, which in turns locks running applications. This becomes very useful when SQL Server Agent jobs (especially xxx_Job_DeleteExpiredSessions) were disabled for some time for some reason.

A better SP looks like this:

   1: SET ANSI_NULLS ON
   2: GO
   3: SET QUOTED_IDENTIFIER ON
   4: GO
   5:  
   6: ALTER PROCEDURE [dbo].[DeleteExpiredSessions]
   7: AS
   8:  
   9: DECLARE @now datetime
  10: SET @now = GETUTCDATE()
  11: declare @count int
  12: set @count = 1
  13:  
  14: set ROWCOUNT 1000
  15: while @count != 0
  16: begin
  17:     begin tran
  18:     DELETE [Softlion].dbo.ASPStateTempSessions
  19:         WHERE Expires < @now
  20:     set @count = @@ROWCOUNT
  21:     commit
  22: end
  23: set ROWCOUNT 0
  24:  
  25: RETURN 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

You may also add the hint WITH (ROWLOCK) on the delete statement to be sure no lock are set on a range which may contains rows currently used by the application.

Tags: , ,

Useful LINQ extensions

by softlion 10. December 2008 15:17

Tags:

SQL Server transaction isolation level and .NET sql library pitfall / bug !

by softlion 21. November 2008 05:49

Yesterday I found what can easily be named THE bug of the year. Even I can named it the biggest bug in the last 4 years. It affects nearly all of our past projects with different degrees of impact.

It is documented in MSDN as a feature in a small note in the description of the SqlConnection.BeginTransaction .NET method (see references below).

Let me explain the context first so you really understand the bug and how to fix it.

 

Imagine you have a web application created using ASP.NET, and a SQL Server data storage.

To construct a web page, your ASP.NET code will query 3 times data on the SQL server.

The 1st and 2nd queries are executed inside a transaction which runs under a non default isolation level  READ UNCOMMITTED.

The last query is executed alone, completely separated from the previous ones. This query is using the with(READPAST) option in one of its statement.

If you run  your application, you'll see a nice .NET error page telling you that READPAST can not be used in this transaction isolation level (it does not tell you which).

 

So first you debug your application and you check in which isolation level you are. This is easily done using this query:

 

select
      transaction_isolation_level,
      last_request_start_time,
      *
from sys.dm_exec_sessions

 

And you'll find what ? That instead of being the default READ COMMITED isolation level, the query is executed under READ UNCOMMITTED !

Have you guessed why already ? Well it is because of the "feature" of the transaction handling combined with the feature of the SQL connections pooling implemented in ADO.NET.

Connection pooling makes .NET reuse existing SQL connections which is an efficient way to use this network resource.

In our case,  a connection is created by the first query and is used by the whole transaction. When closed by code, the connection is not closed but moved to the connections pool (with a TTL so it won't last forever if not used).

For the third query the code creates a new connection, which the library converts to a 'get the opened connection from my connections pool'.

 

Now read the note from MSDN :

After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call SqlConnection..::.BeginTransaction followed immediately by SqlTransaction..::.Commit. For more information on SQL Server isolation levels, see "Isolation Levels in the Database Engine" in SQL Server 2005 Books Online.

 

What happens here is that the first connection is returned to the pool but the transaction isolation level is not reset to its default value. So our 3rd query will execute and fail unexpectedly because the with(READPAST) option is not compatible with an isolation level equals to read uncommited.

 

How to fix this ?

Before closing your connection, after a transaction where you know you change the default isolation level, just execute this code wich resets it to the default READ COMMITED or wathever you set to be the default:

myConnection.BeginTransaction().Commit();

 

 

References:

SqlConnection.BeginTransaction .NET method and the note explaining the "feature".

.NET SQL connection pooling (ADO.NET 2.0)

 

Tags: ,

uniqueidentifier in SQL xml type are upper case strings but C# Guid are lower case strings

by softlion 20. November 2008 10:00

A modern way to put a list of IDs in a stored procedure parameter is to type the parameter as xml (instead of the conventional CSV like varchar). With the nodes() method you can inner join directly the xml 'table' with one of your database table without first filling a temporary table. And building the xml fragment with LINQ TO XML (ie: XDocument class) is a piece of cake.

 

If these ids are C# Guids (or tsql uniqueidentifier) and you optimize your query (like msdn tells you), you may fall in the uppercase/lowercase trap.

 

-- Optimized query (working)
select * from MyGames a
left join MyUsers b on a.Winners.exist('//winner[upper-case(@userId)=sql:column("b.UserId")]')=1

 

In this XQuery optimized comparison, T-SQL converts a uniqueidentifier to an upper case string. The Winners xml column has been filled using C# XDocument, which uses by default the C# method Guid.ToString() to convert a guid ... to lowercase.

 

So we have SQL converting by default uniqueidentifier to uppercase, and C# converting by default Guid to lowercase.
If you rely on defaults any comparison done between uniqueidentifier in this cutting edge xml/sql technology then it will not work.



Notes:
The xml type is a new native type available since SQL Server 2005. I use it essentially to simplify the model for 1-N relations by storing ids of the N table in a field of the 1 table instead of creating this dummy relationship table I always hated. This without giving up performance, as long as you setup the new special xml indexes for the xml typed field and provide the XSD schema to SQL. See references below for the full documentation.


A uniqueidentifier is a 16 bytes (128 bits) value which is used by the default implementation of User/Membership provider of the ASP.NET framework for all unique IDs.



With the xml data type, SQL 2005 introduced "methods" that can be used to efficiently query the xml data and use it as if it was a normal table : exists(..), value(..), ...
A common parameter for these methods is an XQuery string, where XQuery is a SQL Server specific language based on XPath, with at least 2 useful efficients extensions in the sql namespace:
sql:variable(..) which is replaced by the value of an existing variable
sql:column(..) which is replaced by the value of any table row available in the t-sql query




References:
SQL Server xml data type

XML indexes
XML type query methods
XQuery language reference

 

Tags: ,

Silverlight 2 basic performance test for procedural animations

by softlion 5. November 2008 21:31

Today I created my first Silverlight 2 application and my first control : a simple ball. The aim was to evaluate how easy it is to create a Silverlight 2 application and a control, and to test SL display smoothness and speed.

The ball has an update method which is called for each ball instance at most every 25ms through the application's CompositionTarget.Rendering event. I don't know if it is the best way to do procedural animation, but it sure is a way.

This event fires before each frame is rendered, like the well known frame technics in Flash. But unlike Flash, the frame rate is not constant and depends on the running machine and the silverlight application load.

I may try later using a worker thread and the InvalidateArrange() call combination. 

 

This application displays the framerate computed over the last second, creates a new ball object each time the mouse is moved over its window, and displays the total number of balls created and animated.

 

If you take a look at the result, you'll immediatly see that frame displays are not synchronized with the graphic card's vertical sync, which results in ugly breaks in the animation.

The animation slows when the mouse is moved over it : that confirms what the documentation says about the CompositionTarget.Rendering event, so we can not complain Sealed

 

 

 

Please post your FPS, ball count, and OS in the comment section.Try to get exactly 1000 or 2000 balls.

 

References

How to declare a Custom User Control from a XAML page

This app uses a fixed version of PathTextBlock silverlight control to display a text with a stroke (in fact this control converts text to glyphs which does support stroke and fill).

Configure IIS for hosting Silverlight 2 applications (don't forget to stop/start your IIS server after)

Silverlight 2 control lifecycle

 

 

Tags:

Microsoft PDC 2008 et l'arrivée prochaine de C#4

by softlion 2. November 2008 20:26

La conférence pour développeurs professionnels de Microsoft s'est terminée le 30 octobre dernier, avec des informations sur le C#4 qui va bentôt sortir et même la version suivante (session de Anders Hejlsberg).

Résumé:

 

C#1 a été initié en 1998, avec la création du MSIL et de la gestion de la mémoire automatique. La version 1.1 a apporté des modifications majeures pour rendre le language utilisable.

 

C#2 a corrigé toutes les erreurs du C#1 et du MSIL1 en apportant le plus qui existait encore dans le C++ à savoir les generics (templates en C++).

 

C#3 (et 3.5) a amélioré le compilateur pour supporter LINQ, une syntaxe ressemblant au SQL pour manipuler facilement des listes. C'est la première fois qu'un langage réussit cette prouesse et je crois pour ma part que ca a été une avancée majeure dans les languages de développements qui met à la traine Java et C++. LINQ intervient également dans une stratégie d'optimisation automatique du logiciel pour le multicore. Le 3.5 intègre également les fonctions anonymes qui ont fait la force du javascript et du PHP, et le type delegate qui représente une fonction typée (très utilisé en C++ sous forme de pointeur typé).

 

C#4, avec Visual Studo 2010, pompe encore quelques goodies à Javascript avec le nouveau type "dynamic" (pratique pour COM) qui représente un objet non typé (eh oui ca peux faire rire !) sur lequel on peux appeler des propriétés ou méthodes non connues à la compilation. Ecrire des macros Excel ou Word en C# ou .NET va peux être devenir une réalité et enfin remplacer le très vieux VBA. Dommage que cela arrive si tard ! C#4 ajoute également les paramètres de fonction optionnels (merci C++) et nommés (extension pratique qui manque à C++), ainsi qu'une amélioration des generics et des delegates utile au compilateur.

 

Enfin la version suivante (C# 4.5 ?) devrait intégrer le "Compiler as a Service" - une API pour utiliser le compilateur dans le code. Ca permet d'exécuter des bouts de code dynamiquement comme pour la fonction Eval du javascript. Ca va aussi permettre de poubelliser/remplacer le language bizarre de PowerShell. Bon ok c'était déjà possible avec la version 1.1, mais la ca devrait être encore plus facile.

 

Ex d'objet dynamic:
dynamic monObjet1 = { Code=1, Name="Parapluie" };
dynamic monObjet2 = { Code=2, Name="Casquette" };
DisplayObject( monObjet1 );
DisplayObject( monObjet2 );
...
void DisplayObject( dynamic o )
{
  Console.WriteLine( String.Format( "Code: {0}, Name: {1}", o.Code, o.Name ) );
}

 

Ex de fonction avec paramètres optionnels : (existe depuis ... 15ans dans C++ ?)

public void SaveAs( string fileName, Encoding encoding = Encoding.UTF8 ) { ... }

 

Ex de fonctions avec paramètres nommés: (n'existe pas dans C++)

SaveAs( fileName: "monFichier.xml", encoding: Encoding.ASCII );

 

Référence:

La vidéo de la session sur C#4

Visual Studio 2010 et .NET Framework 4 CTP

Un résumé des sessions du PDC par Thomas Lebrun

Tags: