Something The C# Compiler Will Let You Do

by Frederic Torres 30. August 2010 16:33

While writing unit tests, I shoot myself in the foot trying the re use an already declared int.
I am surprise that the C# compiler will let you do this.
The result is that we will only loop once in the first loop.

         static  void  LoopIssue()
         {             
             for  (int  i = 0; i < 5; i++){
 
                 Console .WriteLine("i:{0}" , i);
 
                 for  (i = 0; i < 10; i++){

                     Console .WriteLine("   i:{0}" , i);
                 }
             }            
         }
 

Tags:

C#

Looping through an array in Javascript

by Frederic Torres 30. July 2010 23:28

A little bit confused with Javascript array. I was.

Mastering Javascript Arrays

 
 function  LoopingTroughArray() {
 
     var  Values = ["A" ,"B" ,"C" ];
                                 
     for  (var  i = 0; i < Values.length; i++) {  // Solution 1 
 
         alert(Values[i]);
     }
                 
     for  (var  index in  Values) { // Solution 2 
 
         alert(Values[index]);
     }
                 
     jQuery.each(Values,         // Solution 3 with jQuery 
                 function (index, value){ 
                     alert(value); 
                     // return true;  same as continue 
                     // return false; same as break 
                 } 
     );
     // The array method forEach is supportted in FireFox but not in Internet Explorer. 
 }
 
 function  FilteringAnArray() {
 
     var  Values    = [1,2,3];
     var  NewValues = jQuery.map( Values,
                                 function  (value){
                                     if  (value > 2)                                
                                         return  value;                                
                                     else 
                                         return  null ; // remove the item from the array 
                                 }
     );
     alert(NewValues.valueOf());
 }
 
 function  ChangingTheContentOfAnArray() {
 
     var  Values    = [1,2,3];                                
     var  NewValues = jQuery.map( Values,
                                 function (value){                                 
                                 return  value*2;
                                 }
     );
     alert(NewValues.valueOf());                
 }
 
 function  LoopingTroughAnObjectProperties() {
 
     var  Person = {
         LastName:   "Descartes" ,
         FirstName:  "Rene" 
     }
                 
     jQuery.each(Person,
         function (key, value){ 
             alert(key+"=" +value);
         }
     );                
 }
 
 

Tags:

Code Contrat Cheat Sheet

by Frederic Torres 29. July 2010 06:22

Code Contrat Basic Syntax:

 
 class  CodeContratCheatSheet  {
 
     public int Value { get ; set ; }
         
     [ContractInvariantMethod ]
     private void RationalInvariant(){
 
         Contract .Invariant( this .Value > 0 );
     }
 
     public int VerifyInputParameter(int  a){
             
         Contract .Requires ( (a > 0) && (a < 100) );
         Contract .Ensures  ( a > 0 );
         Contract .Ensures  ( Contract .Result<int >() > 0 );
 
         return  1;
     }
 
     public void VerifyDataInInputOutputParameterOfTypeList(List <int > L){
 
         Contract .Requires( Contract .ForAll( L, l => l > 0 ) );             
         Contract .Ensures ( Contract .ForAll( L, l => l > 0 ) );
     }
 
     public void VerifyOutputParameters(out  int  i){
 
         Contract .Ensures(Contract .ValueAtReturn<int >(out  i) > 0 );
         i=1;
     }
 
     public List <int> VerifyDataInListReturned(){
         Contract .Ensures( Contract .Result<List <int >>().Count > 1 );
         Contract .Ensures(
             Contract .ForAll(
                 0, Contract .Result<List <int >>().Count,
                 index => Contract .Result<List <int >>()[index] > 0
                 )
         );
             
         List <int > l = new  List <int >();
         l.Add(1); l.Add(2); l.Add(3);
         return  l;
     }
 }
 

Tags:

Implementing a simple configuration file in Python for a C# application - Part III

by Frederic Torres 28. June 2010 05:33

In this post I want to make my user description richer and for this I going to implement a class with 3 attributes UserName, LastName and FirstName.
Now my Users attribute from my Configuration dictionary is a list containing 3 instances of the class User.
You can even write some code to test the Python indepently of the C#.

 """
     Configuration of my application
 """ 
 class User(object): 
 
      def  __init__( self,  userName,  lastName,  firstName): 
         self. UserName   =  userName
         self. LastName   =  lastName
         self. FirstName  =  firstName
         
      def  __str__( self):  # Same as C# ToString() 
         return  "UserName:%s, LastName:%s, FirstName:%s"  %  ( self. UserName,  self. LastName,  self. FirstName) 
         
 
  Configuration =  { 
     "Server"     :    "TOTO", 
     "Database"   :    "Rene", 
     "Debug"      :    True, 
     "MaxUser"    :    3, 
     "Users"      :    [ 
                         User("rdescartes"    ,"rene"      ,"descartes"     ), 
                         User("bpascal"       ,"blaise"    ,"pascal"        ), 
                         User("cmontesquieu"  ,"charles"   ,"montesquieu"   ) 
                     ] 
 } 
 
 # Code for quickly testing the user class. This Python code will work with IronPython or the C Python.
 if  __name__ == "" : 
     u =  User("rdescartes"    ,"rene"      ,"descartes"     ) 
     u =  User("bpascal"       ,"blaise"    ,"pascal"        ) 
     u =  User("cmontesquieu"  ,"charles"   ,"montesquieu"   ) 
     print  u
     
 

How to read this configuration variables in C# 4.0.

 static void Demo() {
 
     ScriptRuntime  PythonScriptRuntime = Python .CreateRuntime();
     dynamic        PythonScript        = PythonScriptRuntime.UseFile("Configuration3.py" );
 
     Console.WriteLine(PythonScript.Configuration["Server" ]);
     Console.WriteLine(PythonScript.Configuration["Database" ]);
     Console.WriteLine(PythonScript.Configuration["Debug" ]);
     Console.WriteLine(PythonScript.Configuration["MaxUser" ]);
 
     foreach (var u in PythonScript.Configuration["Users" ]){
     
         // Force to convert the User instance into a string which will call __str__ 
         Console .WriteLine((string )u);
     }                                       
     foreach (var u in PythonScript.Configuration["Users" ]){
         
         Console .WriteLine(u.UserName);
     }
     Console .ReadLine();
 }
 
 

Tags:

Implementing a simple configuration file in Python for a C# application - Part II

by Frederic Torres 28. June 2010 05:10

In this post I going to use a Python dictionary to store my configuration variables:

 """
     Configuration of my application
 """ 
 Configuration =  { 
     "Server"     :    "TOTO", 
     "Database"   :    "Rene", 
     "Debug"      :    True, 
     "MaxUser"    :    3, 
     "Users"      :    ["rdescartes",  "bpascal",  "cmontesquieu"] 
 }
 


How to read this configuration variables in C# 4.0.

 static void Demo() {
 
     ScriptRuntime  PythonScriptRuntime = Python .CreateRuntime();
     dynamic        PythonScript        = PythonScriptRuntime.UseFile("Configuration2.py" );
 
     Console.WriteLine(PythonScript.Configuration["Server" ]);
     Console.WriteLine(PythonScript.Configuration["Database" ]);
     Console.WriteLine(PythonScript.Configuration["Debug" ]);
     Console.WriteLine(PythonScript.Configuration["MaxUser" ]);
 
     foreach (string u in PythonScript.Configuration["Users" ]){
 
         Console .WriteLine(u);
     }                                    
     Console .ReadLine();
 }
 

Tags:

Implementing a simple configuration file in Python for a C# application

by Frederic Torres 28. June 2010 04:46

Combining IronPython and C# can bring very interresting things. For example implementing configuration. In this first post I am implementing a configuration file by using IronPython global variables. I am using C# 4.0 which make things easier but this can be done with C# 2.0.

The configuration file Configuration1.py.

 """
     Configuration of my application
 """ 
 Server      =    "TOTO" 
 Database    =    "Rene" 
 Debug       =    True
 Users       =    ["rdescartes",  "bpascal",  "cmontesquieu"] 
 
 


How to read this configuration variables in C# 4.0.

 static void Demo() {
 
     ScriptRuntime  PythonScriptRuntime = Python.CreateRuntime();
     dynamic        PythonScript        = PythonScriptRuntime.UseFile("Configuration1.py" );
 
     Console .WriteLine(PythonScript.Server);
     Console .WriteLine(PythonScript.Database);
     Console .WriteLine(PythonScript.Debug);
 
     foreach (string u in PythonScript.Users){
 
         Console .WriteLine(u);
     }                                    
     Console .ReadLine();
 }
 


You will need to install IronPython 2.6 For .NET 4.0 and reference the following assemblies:

  • IronPython.dll
  • Microsoft.Dynamic.dll
  • Microsoft.Scripting.dll

Here are the namespaces used:

 using  Microsoft.Scripting.Hosting;
 using  IronPython.Hosting;
 using  Microsoft.Scripting;
 

Tags:

Bat File Syntax Highlighter For Visual Studio 2010

by Frederic Torres 26. June 2010 06:44

I created an extension for Visual Studio 2010 to display batch files (.bat) with syntax highlighting.

The colors can be configured by editing a Python file named COLORS_DEFINITION.py.

 BAT_COLORS_DEFINITIONS =  { 
     "Keyword"        :  "Blue",             # Echo, Copy any Bat keyword 
     "Comment"        :  "Green",            # rem 
     "Param"          :  "Brown",            # /b /s 
     "Label"          :  "Darkmagenta",      # label 
     "EnvVar"         :  "MediumPurple",     # %TEMP% 
     "Redirection"    :  "Red",              # > and >>  
     "Default"        :  "Black" 
 }
 


Download the extension at http://visualstudiogallery.msdn.microsoft.com/en-us/6706b602-6f10-4fd1-8e14-75840f855569

Tags:

Text File Syntax Highlighter For Visual Studio 2010

by Frederic Torres 26. June 2010 05:10

I created an extension for Visual Studio 2010 to display .txt and .log file with colors. Based on a simple rule the line is displayed in full in a specific color.

The colors can be configured by editing a Python file named COLORS_DEFINITION.py. If the line contains the string defined in ColorDefinition or if the line matches the regular expression the color is selected. To get the regular expression to work you will need to install IronPython 2.6 for .NET 4.0. in the default folder (%PROGRAMFILES%\IronPython 2.6 for .NET 4.0).

The rules are evaluated from top to bottom, we stop at the first one that match. You can add as many rules as you want.

 COLORS_DEFINITIONS =  { 
     "txt":  [  # Color definition for .txt file 
         ColorDefinition (  "[WARNING]"                ,"DarkGoldenrod"         ), 
         ColorDefinition (  ".*\\[ERROR\\].*Minor.*"   ,"Salmon"        ,  True ),         
         ColorDefinition (  ".*\\[ERROR\\].*"          ,"Red"           ,  True ), 
         ColorDefinition (  "[INFO]"                   ,"Blue"                  ), 
         ColorDefinition (  "[PASSED]"                 ,"Green"                 ), 
         ColorDefinition (  ""                         ,"Black"                 )  # The last item is the default color 
     ] 
 }
 

 

Download the extension at http://visualstudiogallery.msdn.microsoft.com/en-us/6706b602-6f10-4fd1-8e14-75840f855569

Once you ran the install, start Visual Studio 2010, click on the menu Tool Extension Manager, selection the extension and click Enable.
Restart Visual Studio 2010.

To change the colors edit the file

%userprofile%\Local Settings\Application Data\Microsoft\VisualStudio\10.0\Extensions\TextHighlighterExtension\COLORS_DEFINITION.py

with Visual Studio. Once done, restart Visual Studio.

To get PYTHON syntax highlighting see IronPython tools for Visual Studio.

 

Tags:

C# function returning multiple values

by Frederic Torres 7. June 2010 04:00

Python functions can return multiple values.

 class  MultiValueFunctionExperiment(object): 
 
      def  MyFunctionWithMultiValues(self): 
         return 1, 2, "Toto"
 
      def  Demo(self): 
         a, b, s =  self. MyFunctionWithMultiValues() 
         print  a
         print  b
         print  s
 
 e =  MultiValueFunctionExperiment() 
 e. Demo() 
 
 

 

I like to do the same in C#. Here is the syntax I came with by using a class named MultiValue.

 class  MultiValueFunctionExperiment  {
 
     private MultiValue MyFunctionWithMultiValues() { 
 
         return new MultiValue().Add(1).Add(2).Add("Toto");
     }
     public void Demo() { 
 
         MultiValue mv = MyFunctionWithMultiValues();
         int a         = mv.Value<int >();
         int b         = mv.Value<int >();
         string s      = mv.Value<string >();
 
         Console.WriteLine(a);
         Console.WriteLine(b);
         Console.WriteLine(s);
     }
 }
 
 
 

 

Here is the class MultiValue

 class MultiValue  { 
 
     List<object > _values;
 
     public MultiValue(){
 
         _values = new  List<object >();
     }
     public MultiValue Add(object  i) { 
 
         this ._values.Add(i);
         return  this ;
     }
     public T Value<T>() { 
 
         T i = (T)this ._values[0];
         this ._values.RemoveAt(0);
         return  i;
     }
 }
 
 

C# IDisposable+Using keyword in Python

by Frederic Torres 9. April 2010 02:49

Introduction

Python has a way to mimic the C# IDisposable interface + keyword using. Python 2.6 required.

First the C# sample

 class  MyClass  : IDisposable {
 
     public  MyClass() {
 
         System.Console .WriteLine("Initializing..." );
     }
     public  void  Dispose() {
 
         System.Console .WriteLine("Exiting..." );
     }
     public  void  Run() {
 
         System.Console .WriteLine("Running..." );
     }
 }
 class  Console  {
 
     static  void  Main(string [] args) {
 
         using  (MyClass e = new  MyClass()) {
 
             e.Run();
         }
     }
 }
 

 

IDisposable+Using keyword in Python

In Python the keyword with match the C# keyword using. The method __exit__() match the method Dispose(). But a method __enter__() is required. The __enter__() simply returns the instance itself.

 class  MyClass: 
 
      def  __init__( self): 
         print  "Initializing..." 
 
      def  __enter__( self): 
         print  "Entering..." 
         return  self
 
      def  __exit__( self,  type,  value,  traceback): 
         print  "Exiting..." 
         return  False # Do not swallow raised exception 
 
      def  Run( self): 
         print  "Running" 
 
 def  Main(): 
 
      with  MyClass()  as  e: 
         e. Run() 
 
  Main()
 


IDisposable+Using keyword in Python, another implementation using inheritance

 class  IDisposableBaseClass: 
 
      def  __enter__( self): 
         print  "Entering..." 
         return  self
 
      def  __exit__( self,  type,  value,  traceback): 
         self. Dispose() 
         return  False
 
 class  MyClass( IDisposableBaseClass): 
 
      def  __init__( self): 
         print  "Initializing..." 
 
      def  Dispose( self): 
         print  "Exiting..." 
 
      def  Run( self): 
         print  "Running" 
 
 def  Main(): 
 
      with  MyClass()  as  e: 
         e. Run() 
 
  Main()
 

Tags:

Dependency Injection C# vs Python

by Frederic Torres 8. April 2010 03:59

Just to make sure I understand the dependency injection concept, I wrote a little simple showing 2 highly coupled classes and the loosely coupled solution in C# and in Python.

Highly Coupled Dependency in C#


Because the classes Invoice and SaleTaxe are Highly Coupled and the class SaleTaxe use the DB class to read the sale taxe from the database, it is impossible to unit test the Invoice class without an SaleTaxe instance and a database.

    public class SaleTaxe {

private Decimal _Value = 0;

public SaleTaxe() {

_Value = DB.Read("SaleTaxe");
}

public Decimal Value {
get {
return this._Value;
}
}
}

public class Invoice {

private SaleTaxe _SaleTaxes = null;
private Decimal _AmountBeforeTaxe = 0;

public Invoice(decimal amountBeforeTaxe) {

_SaleTaxes = new SaleTaxe(); // << HighlyCoupledDependency
_AmountBeforeTaxe = amountBeforeTaxe;
}

public Decimal TotalAmount {
get {
return this._AmountBeforeTaxe + (this._AmountBeforeTaxe * this._SaleTaxes.Value / 100);
}
}
}

Loosely Coupled Dependency in C#


To implement a loose coupling we are using an interface.


public interface ISaleTaxes {

decimal Value { get; }
}

public class SaleTaxes : ISaleTaxes {

private Decimal _Value = 0;

public SaleTaxes() {

_Value = DB.Read("SaleTaxe");
}

public Decimal Value {
get {
return this._Value;
}
}
}

public class Invoice {

private ISaleTaxes _SaleTaxes = null;
private Decimal _AmountBeforeTaxe = 0;

public Invoice(decimal amountBeforeTaxe, ISaleTaxes saleTaxes) {

_SaleTaxes = saleTaxes;
_AmountBeforeTaxe = amountBeforeTaxe; // << LooseCoupling
}

public Decimal TotalAmount {
get {

return this._AmountBeforeTaxe + (this._AmountBeforeTaxe * this._SaleTaxes.Value / 100);
}
}
}


Unit Testing


Now we can create a class SaleTaxesForTesting just for unit testing.

        class SaleTaxesForTesting : DependencyInjection.LooseCoupling.ISaleTaxes {

public Decimal Value {
get {
return 10;
}
}
}

[TestMethod]
public void LooseCouplingDependency_TotalAmount() {

DependencyInjection.LooseCoupling.Invoice i = new DependencyInjection.LooseCoupling.Invoice(1, new SaleTaxesForTesting());
Assert.AreEqual(1.10M, i.TotalAmount);
}

And now in Python


In Python there is no need to create the interface. Any instance referencing another is loosely coupled. See Uncle Bob's SOLID principal.

class SaleTaxes:

def __init__(self):

self.Value = DB.Read("SaleTaxe")

class Invoice:

def __init__(self, amountBeforeTaxe, saleTaxes):

self.AmountBeforeTaxe = amountBeforeTaxe
self.SaleTaxes = saleTaxes

def TotalAmount(self):

return self.AmountBeforeTaxe + (self.AmountBeforeTaxe * self.SaleTaxes.Value / 100.0)

# Unit Tests

class SaleTaxesForTesting:

def __init__(self):

self.Value = 10

class UnitTests(unittest.TestCase):

def test_LooseCouplingDependency_TotalAmount(self):

i = Invoice(1, SaleTaxesForTesting())
self.assertEqual(1.10, i.TotalAmount())


Tags:

ASP.NET form authentication, cookie encryption and IIS7

by Frederic Torres 28. March 2010 18:41

With IIS7 the encryption key, to encrypte the ASP.NET form authentication cookie is by default
re-generated every time IIS start or every time the application process is recycled
(when the application pool is recycled). My guess is that IIS6 uses a static encryption key.

Thefore if your application is trying the decrypte a cookie saved before the last recycling
the method FormsAuthentication.Decrypt() will raise the following Exception

    System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.

One solution is to add your own machine key in the web.config file in the section <system.web>.


<machineKey
  validationKey="40107878EFF79547946F85EE34808A7BDB9B7CB0EC2184029F1..."
  decryptionKey="04BCBB3929F44DE6B7C0DD5C4A992A24E0E05565D5A718B59C3..."
  validation="SHA1" decryption="AES"
/>

 

You can google machinekey generator to find online application that will generate the xml for you:

    http://www.developmentnow.com/articles/machinekey_generator.aspx
    http://aspnetresources.com/tools/keycreator.aspx

My Sansa Fuze MP3 Player And Rhapsody software

by Frederic Torres 19. March 2010 18:02

You do not have to install the Rhapsody software that comes with the Sansa Fuze.

To simply drag and drop mp3 and wma files to the player, you must first turn the player in USB mode MSC (Media Storage Class).

From main menu -> Settings -> System Settings -> USB Mode.

MSC mode will only work for MP3 files and WMA files without digital rights management (DRM).

Tags:

My Sansa Fuze MP3 Player And DotNetRocks

by Frederic Torres 19. March 2010 17:48

My new Sansa Fuze MP3 player, does not recognize MP3 podcasts from DotNetRocks .

By chance i found that episode 166 was recognized. Also if I open and save an MP3 file with an audio editor, the MP3 file is then recognized.

Anyway DotNetRocks provide the podcasts in WMA format which are recognized.

Blog Testing

by Frederic Torres 12. February 2010 04:00

This is my first blog post with blog engine.

Tags:

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Category list

Most comments

Gregory Despain Gregory Despain
3 comments
us United States
James James
2 comments
zw Zimbabwe
Wordpress SEO Secrets Wordpress SEO Secrets
2 comments
us United States