Monday, December 29, 2008

Silverlight : xap to exe

Here is an excerpt from the main site : http://www.blendables.com/labs/Desklighter/Default.aspx
Why do I need Desklighter?
The idea of taking the Silverlight application off the web into a portable single file executable opens up a whole new playing field.
You can share your Silverlight applications without having to worry about the hosting infrastructure.
With Desklighter you can carry your favorite Silverlight content from the web and share with colleagues who are not connected to internet.
Distribute your Silverlight content on USB flash drives or in CDs where ever and to whomever you want. The possibilities are endless.

You can of course distribute like that your IronPython Silverlight application :-)

Wednesday, December 24, 2008

ASP.NET Ajax : Templating


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="CSAstoria.index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .sys-template
        {
            display: none;
        }
    </style>

    <script type="text/javascript" language="javascript">
        var ds;
        var array;
        function pageLoad() {
            ds = new Sys.Data.AdoNetServiceProxy("Northwind.svc");
            ds.query("Products", cbSuccess, cbFailure, null, null);
        }

        function cbSuccess(result, context, opertation) {
            var dataView = new Sys.UI.DataView(document.getElementById("listTemplate"));
            dataView.set_data(result);
            dataView.updated()
        }

        function cbFailure(error, context, operation) {
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/MicrosoftAjaxAdoNet.js" />
            <asp:ScriptReference Path="~/MicrosoftAjaxTemplates.js" />
        </Scripts>
    </asp:ScriptManager>
    <div id="listTemplate" class="sys-template">
        <ul>
            <li>{{ ProductID }} - {{ ProductName }} </li>
        </ul>
    </div>
    </form>
</body>
</html>

ADO Data Services : Service Operations and Interceptors

ADO Data Services (aka Astoria) is a very powerful framework, which enables to expose easyly data and methods on the web.
Here is a document which illustrate how to create new methods or intercept calling methods.

http://msdn.microsoft.com/en-gb/library/cc668788.aspx

Sunday, December 14, 2008

IronPython - SIlverLight

Here is the adapted version of ScottGu sample


from System.Windows import Application
from System.Windows.Controls import UserControl

class App:

root = None

def MyButton_Click(self,s,e):
App.root.MyButton.Content = "Pushed"
App.root.Message.Text = "MyButton has been pushed"

def __init__(self):
App.root = Application.Current.LoadRootVisual(UserControl(), "app.xaml")
App.root.Message.Text = "Welcome to Python and Silverlight!"
App.root.MyButton.Content = "Push Me"
App.root.MyButton.Click += self.MyButton_Click

App()





The xaml code

<UserControl x:Class="System.Windows.Controls.UserControl"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Grid x:Name="layout_root" Background="White">
<TextBlock x:Name="Message" FontSize="55" />
<Button x:Name="MyButton" Content="Push Me" Width="100" Height="50" />
<Grid>

</UserControl>

Silverlight 2 and app.xap

Found of Python, i was in search of running xap files from the filesytem without success
Until I read this post :
http://groups.google.co.il/group/ironpy/browse_thread/thread/b6459831ed03af57

"""
Srivatsn Narayanan
l'original | Signaler ce message | Rechercher les messages de cet auteur
I was running into the same issue but you can specifically ask Chiron to zip the app folder by doing:
Chiron /d:app /z:app.xap. The /z switch adds the dlr assemblies as well. This xap runs from cassini.
"""

Thanks Srivatsn

Friday, December 12, 2008

Saturday, November 1, 2008

Aspose Words : mail merge from a custom data source

Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word®.

Custom datasource is possible.
As showed on this example

http://www.aspose.com/Documentation/file-format-components/aspose.words-for-.net-and-java/aspose.words.reporting.imailmergedatasource.html

Friday, October 24, 2008

Fun with delegates and dictionnary

In Python functions are first class citizen.
It's very easy to assign a value to a dictionnary entry mydict["myfunction"]=hello
and simply call it with mydict["myfunction"]()
Can the same be done n C# ?
I found a way using delegates although it is not as flexible as Python
Here is the code, feel free to comment

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dictcaller
{
class Program
{
delegate void DictDelegate(string message);
Dictionary d = new Dictionary();

static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}

static void Main(string[] args)
{
Program s = new Program();
s.d["test"] = SampleDelegateMethod;
s.d["test"].Invoke("hello");
Console.ReadLine();
}
}
}

Wednesday, October 8, 2008

Saturday, October 4, 2008

Consuming Web Services With ASP.NET AJAX

Simple, clear, efficient :-)
http://www.singingeels.com/Articles/Consuming_Web_Services_With_ASPNET_AJAX.aspx

PageMethods - Ajax

Very nice article on using this powerful feature
http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx

ASP.NET AJAX Development Approach

Three Part series

http://dotnetslackers.com/articles/ajax/ASP-NET-AJAX-Development-Approach-Part-1.aspx

Javascript : Prototype

The 'Protype'keyword allows to add extented properties to an existing object.
Its awesome how powerful is this language.
Whatever you think about it, you have to deal with it, so master the beast ;-)
Here is an example on how to add the 'reverse' propertie to all instances
of 'String' objects
http://www.javascriptkit.com/javatutors/proto2.shtml

ASP.NET AJAX Control Development

An in depth guide to developing controls with the ASP.NET AJAX
from Kazi Manzur Rashid

http://dotnetslackers.com/articles/ajax/ASPNETAJAXControlDevelopment.aspx

Friday, October 3, 2008

Wednesday, September 24, 2008

VB.NET Imports Alias

In case of you missed Python 'import as' :-)
Here the VB.NET equivalent

Imports cfg = System.Configuration.ConfigurationSettings

http://weblogs.asp.net/eporter/archive/2003/08/12/23892.aspx

Control ID Naming in Content Pages

The renaming id when using Master Pages
can be a pain
Here is an article to get out of it
http://www.asp.net/LEARN/master-pages/tutorial-05-vb.aspx

Monday, September 22, 2008

Filling a dropdownlist with LINQ


Partial Public Class _Default
Inherits System.Web.UI.Page

Dim northwind As New northwindDataContext()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then
Dim categories = From categorie In northwind.Categories _
Select categorie
DropDownList1.DataSource = categories
DropDownList1.DataTextField = "CategoryName"
DropDownList1.DataValueField = "CategoryID"
DropDownList1.DataBind()
End If

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim selectValue = DropDownList1.SelectedItem.Value
Dim products = From product In northwind.Products _
Where product.CategoryID = selectValue
GridView1.DataSource = products
GridView1.DataBind()
End Sub

End Class

The ASPX Page

<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<hr />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>

Transmit Forms Data to another ASP.NET page

A dicscussion a bout this problem
http://www.velocityreviews.com/forums/t67347-how-aspnet-page-gets-user-input-from-another-aspnet-page.html
And from Microsoft
http://msdn.microsoft.com/msdnmag/issues/03/04/ASPNETUserState/default.aspx

Sunday, September 21, 2008

LINQ to XML

Simple Query Sample


Module Module1

Sub Main()
Dim doc = XDocument.Load("c:\books.xml").Elements
Dim query = From data In doc.Elements _
Where data.Element("title") = "Python"
For Each g In query
Console.WriteLine(g.Element("author").Value)
Next
Console.ReadLine()
End Sub

End Module

Sample File

<books>
<book><title>Python</title><author>Guido</author></book>
<book><title>Haskell</title><author>Books</author></book>
</books>

LINQ to XML Samples

A few samples on querying XML with LINQ
http://www.thomasclaudiushuber.com/blog/tag/linq/

Creating Custom Configuration Sections in Web.config

From Scott Mitchell

http://aspnet.4guysfromrolla.com/articles/020707-1.aspx

Wednesday, September 17, 2008

Displaying the Files in a Directory using a DataGrid

In his article from http://aspnet.4guysfromrolla.com/articles/052803-1.aspx
Scott Mitchell describe the method.
Here is the c# version

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var rootFolder = @"C:\Documents and Settings\All Users\Documents\Mes images\Échantillons d'images";

var selectedImages = from file in Directory.GetFiles(rootFolder,"*.jpg")
select new {
Name= new FileInfo(file).Name,

};

imageList.DataSource = selectedImages;
imageList.DataBind();
}

}
}

Here is the aspx page


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:DataGrid runat="server" ID="imageList" Font-Name="Verdana" 

                      AutoGenerateColumns="False"

                      AlternatingItemStyle-BackColor="#eeeeee" 

                      HeaderStyle-BackColor="Navy" 

                      HeaderStyle-ForeColor="White"

                      HeaderStyle-Font-Size="15pt" 

                      HeaderStyle-Font-Bold="True">

            <Columns>

               <asp:HyperLinkColumn DataNavigateUrlField="Name" 

                                    DataTextField="Name" HeaderText="Nom du Fichier"  

                                    ItemStyle-ForeColor="DarkOrange" 

                                    ItemStyle-BackColor="#FF0066" />

            </Columns>

        </asp:DataGrid>

    </div>

    </form>

</body> 

</html>




Tuesday, August 19, 2008

Ironpython - ADO.NET

Here is a very simple example on accessing ADO.NET
Feel free to comment

# Module Init.py

import clr
clr.AddReference("System.Data")
from System.Data import *
from System.Data.SqlClient import *

dbCn = SqlConnection("""Data Source=Python\Sqlexpress;Initial Catalog="C:\SQL SERVER 2000 SAMPLE DATABASES\NORTHWND.MDF";Integrated Security=True""")


dbCn.Open()


ds = DataSet()
dbDa = SqlDataAdapter()


class Table:

def __init__(self,name,command=None):
self.name = name
if command:
self.command = command
else:
self.command = "select * from %s"%self.name
self.sqlCommand()
self.fill_dbDa()

def sqlCommand(self):
self.dbCmd = SqlCommand(self.command,dbCn)
self.CommandType = CommandType.Text
dbDa.SelectCommand = self.dbCmd

def fill_dbDa(self):
dbDa.Fill(ds,self.name)
self.dataTable = ds.Tables[self.name]

dbCn.Close()




# File default.asp.py
import Init

def Page_Load(sender, e):
products = Init.Table("Products")
GridView1.DataSource = products.dataTable
GridView1.DataBind()

Saturday, August 9, 2008

A walkthrough the Jasper API with IronPython

!!! This project is stopped for now :-(


From Microsoft site :

"""
Jasper leverages the power of dynamic languages and the concept of convention over configuration to provide a programming surface for data that enables rapid development of data-bound applications. While most other rapid data access frameworks are only capable of working against simple databases, Jasper can scale to almost any database, regardless of size or complexity. This is possible because Jasper takes advantage of the ADO.NET Entity Framework’s significant investments in mapping and conceptual data modeling.
"""

The coolest thing is that it can be used with IronPython.


http://blogs.msdn.com/aconrad/archive/2007/05/10/a-walkthrough-the-jasper-api-with-ironpython-part-1.aspx

Friday, August 8, 2008

Generators - Iterators - Coroutines in Python

If you ever wonder what are generators useful for, look at this excellent
document, which shows how they can save your life as system programmers
http://www.dabeaz.com/generators/

Tuesday, August 5, 2008

LINQ : GroupJoin Operator

In C# in order to make an outer join
you have to use the 'GroupJoin' operator

You can see a good example on :

http://www.java2s.com/Code/CSharp/LINQ/GroupJoinOperator.htm

Monday, August 4, 2008

Why does C# have both 'ref' and 'out'? from MSDN

Coming from Python which allows multiple values when returning from a function
the 'out' keyword may seemed strange.


http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

Friday, August 1, 2008

C# Anonymous Methods & The Action Object

Matthew is really great :-)

C# Anonymous Methods & The Action Object

Introduction to Functional Programming in C#.

Very Nice article from Matthew Cochran.

Introduction to Functional Programming in C#.

List<T>.foreach

Here is a sample code on how to use 'foreach' on 'generic list'
Notice the call to the anonymous function


class Employee
{
private string _nom;
private double _salary;

public Employee()
{
}

public Employee(string nom, double salary )
{
_nom = nom;
_salary = salary;

}

public string Nom
{
get {return _nom; }
set { _nom = value;}

}

public double Salary
{
get { return _salary;}
set { _salary = value; }
}
}



class Program
{

public static void incSalary(Employee p)
{
p.Salary += 100;
Console.WriteLine(p.Nom + Convert.ToString(p.Salary));
}

public static void Main(string[] args)
{
List lstEmployee = new List();

lstEmployee.Add(new Employee("Paul",3300));
lstEmployee.Add(new Employee("Raphael",2500));

lstEmployee.ForEach(incSalary);

lstEmployee.ForEach(delegate(Employee p){Console.WriteLine(p.Nom);});

Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}

Wednesday, July 30, 2008

LINQ - Accés aux données

Great article from Julien Corioland

Visual Studio 2008 : Les nouveautés de l’accès aux données avec LINQ !

LINQ - C#

This article explains compares
Lazy Loading et Agressive Loading
(in French)

Lazy Loading et Agressive Loading

LINQ - Select using Class

Beth Massi shows a way to project select data in class instances
Here the c# equivalent


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileSystem
{
public partial class Form1 : Form
{
class MyFile
{
private System.DateTime _creationTime;
private string _name;

public System.DateTime CreationTime
{
get {return _creationTime;}
set { _creationTime = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}
}

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo root = new DirectoryInfo(".");

var myFiles = from FileInfo f in root.GetFiles()
select new MyFile { Name = f.Name,
CreationTime = f.CreationTime
};

dataGridView1.DataSource = myFiles.ToList();

}
}
}

FileSystem in C#

Here is a way to retrieve file info in C#
using LINQ syntax.
Feel free to comment.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo root = new DirectoryInfo(".");
var files = from FileInfo f in root.GetFiles()
select new { FileName = f.Name, LengthFile = f.Length };


dataGridView1.DataSource = files.ToList();

}
}
}

Tuesday, July 29, 2008

LINQ - Operators

Here is the main list of LINQ operators
Thanks >Kader Yildirim



Restriction operators
Where

Projection operators
Select
SelectMany

Partitioning operators
Take
Skip
TakeWhile
SkipWhile

Ordering operators
OrderBy
OrderByDescending
ThenBy
ThenByDescending
Reverse

Grouping operators
GroupBy
Joining operators
Join
GroupJoin

Set operators
Distinct
Union
Intersect
Except

Conversion operators
Cast
ToArray
ToList
ToDictionary
OfType
ToLookup
ToSequence

Element operators
DefaultEmpty
First
FirstOrDefault
Last
LastOrDefault
ElementAt
ElementAtOrDefault
Single
SingleOrDefault

Generation operators
Empty
Range
Repeat
Quantifiers
Any
All
Contains

Aggregate operators
Aggregate
Count
LongCount
Sum
Min
Max
Average
Fold

Miscellaneous operators
Concat
EqualAll
Custom Sequence operators
Combine
Query Execution
Deferred
Immediate
QueryReuse

LINQ - Articles in french

Some french articles using LINQ

LINQ à 360 degré

Functional programming - C#

Here is a series of articles concerning functional in C#

A C# library to write functional code

Sunday, July 20, 2008

Extension Method - C#

Extensions Methods are the base of LINQ implementation.
Mitsuru Furuta from Microsoft France show a neat way
to return default value from a dictionnary

http://blogs.msdn.com/mitsufu/archive/2008/05/07/astuce-faciliter-la-lecture-des-donn-es-d-un-dictionnaire-gr-ce-une-m-thode-d-extension.aspx

Thanks Mitsuru for this nice tip

Friday, July 18, 2008

Functional Programming in C#

Functional programming style can save a lot of time.
Here are somme samples from Microsoft site itself.
C# tend to include some F# features.
Give it a look, it will change your life as a C# developper ;-)

The following topics are covered

Closures
Currying
Filter
Fold
Iterators
Lazy Evaluation
LINQ
Lists (Immutable and Recursive)
List Continuations
Maps/Map2
Memoization
Monads
Operators (Forward, Reverse, etc)
Recursion
Unfolding and Generators

http://code.msdn.microsoft.com/FunctionalCSharp

Thursday, July 17, 2008

Wednesday, July 16, 2008

List Comprehension in C# with LINQ - part 2

In this example, I tried to figure how to use
a static method to filter an array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQArray
{
class Program
{
public static bool filter(string s)
{
bool ret = false;
if (s.StartsWith("A"))
{
ret = true;
}
return ret;
}

static void Main(string[] args)
{
string[] countries = { "Britain", "France", "Croatia", "Argentina", "Australia", "Mexico", "Finland",
"Spain", "Italy", "Greece" };
var thecountries = from c in countries
where filter(c)
select c;
foreach (var c in thecountries)
{
Console.WriteLine(c);
}
Console.ReadLine();
}
}
}

List Comprehension in C# with LINQ

List comprehensions from Python (from Haskell) miss me a lot in C#
Happily with LINQ I dont miss then anymore :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListComprehension
{
class Program
{
static void Main(string[] args)
{
string[] countries = { "Britain", "France", "Croatia", "Argentina", "Australia", "Mexico", "Finland",
"Spain", "Italy", "Greece" };

string[] favcountries = { "Britain", "Argentina", "Greece", "Brazil" };

var thecountries = from c in countries
where favcountries.Contains(c)
select c;

foreach (var c in thecountries)
{
Console.WriteLine(c);
}
Console.ReadLine();
}
}
}

LINQ - .NET

LINQ stands for "Language Integrated QUery"
This really great feature can drastically ease SQL request.
Here is an example :

var products = from p in db.Products
where p.Category.Categoryname == "Beverages"
select p;

Here is the corresponding SQL statement :

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t1].[CategoryID] = [t0].[CategoryID]
WHERE [t1].[CategoryName] = 'Beverages'

Choose your camp :-)

Tuesday, July 15, 2008

C# - Learning Events

Here is my simple attempt on implementing events in C#
Any comment would be appreciate.

using System;
namespace TutorialEvents
{
    delegate void PersonHandler(string information);

    class Person
    
        protected string name = "Anonymous";
        public static event PersonHandler PersonEvt;

        public void Process(string name)
        {
            OnPersonEvt(name);
        }

        protected void OnPersonEvt(string name)
        {
            string oldname;
            if (PersonEvt != null)
            {
                oldname = this.name;
                this.name = name;
                PersonEvt(String.Format("OldName : {0} - NewName : {1}", oldname, this.name));
            }
        }
    }

    class ControlNameChange
    {
        static void myPersonEvt(string message)
        {
            Console.WriteLine(message);
        }

        public void Subscribe()
        {
            Person.PersonEvt += new PersonHandler(myPersonEvt);
        }
    }

    class Test
    {
        public static void Main(String[] args)
        {
            Person p = new Person();
            ControlNameChange controlNameChange = new ControlNameChange();
            controlNameChange.Subscribe();
            p.Process("Henri");
            p.Process("Marcel");
            Console.ReadLine();
        }
    }
}

Tuesday, July 8, 2008

Data Access Tutorial in ASP.NET 2.0

quote from site :

Series of tutorials that will explore techniques for implementing these common data access patterns in ASP.NET 2.0. These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Each tutorial is available in Visual Basic and Visual C# versions and includes a download of the complete code used.

http://www.asp.net/learn/data-access/?lang=cs#intro

Thursday, May 29, 2008

Proccesing - Sparkling Stars

Processing is a wonderful environment for those who like to experiment
with design and graphics and sound
It has been created by artists for artists.

float posx = 250;
float posy = 250;
int numstars = 36;

Star[] p = new Star[numstars];

class Star {
  float x;
  float y;
  Star(float _x, float _y) {
    x = _x;
    y = _y;        
  }

  void moveTo(float _x,float _y){
    x = _x;
    y=_y;
    for (float i=0; i<360 ;i+=4){
      stroke(random(255)+245,random(255)+245,random(12)+245,random(30));
      line(x,y,random(40)*cos(i)+x,random(40)*sin(i)+y);      
    }  
  }
}

void setup(){
  size(800,800);
  smooth();
  noStroke();
  for (int i=0; i<numstars; i++){
    p[i] = new Star(100,100);
  }
}

void draw(){
  background(0,0,30);
  for (int i=0; i<numstars; i++){
    posx = random(width);
    posy=random(height);  
    p[i].moveTo(posx,posy);
  }
  
}  

Wednesday, April 2, 2008

HTA-Python : BarGraph


<html>
<head>

<style type='text/css'>
body
{
   color : #fff;
}


</style>
<script language="Python">

def getDiv(div):
    return document.getElementById(div)

def graphBar(data=[],largeur=10,hauteur=400,bgcolor="#00FFFF"):
    table = "<table><tr>"
    maxdata = max(data,key=lambda liste : liste[1])[1]
    coeffmul = 1.0*hauteur/maxdata
    for item in data:
        haut = item[1]*coeffmul
        stl = """style=background-color:%s;padding:4px;font-weight:bold;height:%spx;"""%(bgcolor,haut)
        col = """<td valign='bottom' width='%s'><div %s>%s</div></td>"""%(largeur,stl,item[0])
        table += col
    table += "</tr></table>"
    return table

def test():
    graphdiv = getDiv('graph')
    data = [('11',32),('12',16),
            ('13',8),('14',78),
            ('21',15),('22',45),
            ('23',65),('24',34),
            ('31',55),('32',34),
            ('33',67),('34',45),
            ('41',15),('42',45),
            ('43',65),('44',34)]

    g = graphBar(data,bgcolor='#FF5700',largeur=0,hauteur=200)

    graphdiv.innerHTML = "<div style='border:2px solid #797979;width:1px;'>%s</div>"%g

def init():
    test()
</script>
</head>

<body onload='init()'>
<center>

<div id='graph'></div>
</center>

</body>
</html>

Thursday, March 27, 2008

Simple Tree : Python

I needed a simple example on using list in Python for
a Python tutorial :
This sample shows a way to diplay a hierachical list

tree=["Serveurs",
["Dakar",
["System",
"Banque",
"Reseaux",
['R1',
'R2']],
"Dublin",
"Denver",
"Douala",
["Queue"]]]

hidedNodes = []


def displayTree(tree,n=0):
ident = " "
nextitem = None
for item in tree:
if not isinstance(item,list):
try:
nextitem = tree[tree.index(item)+1]
except:
pass
if isinstance(nextitem, list):
print n*ident+"+" + item
if item in hidedNodes:
if nextitem[0] != 'x':
nextitem.insert(0,'x')
else:
try:
nextitem.remove('x')
except:
pass
else:
print n*ident+" "+ item
else:
if not nextitem[0] == 'x':
n = n + 1
displayTree(nextitem,n)
n = n -1


def hideNode(node):
hidedNodes.append(node)

def showNode(node):
hidedNodes.remove(node)

def test():
print "TEST 1 : Display all"
displayTree(tree)
print ""
print "TEST 2 : Hiding Douala,Dakar"
map(hideNode,['Dakar','Douala'])
displayTree(tree)
print ""
print "TEST 3 : Showing Dakar"
showNode('Dakar')
displayTree(tree)
print ""
print "TEST 4: Hide Reseaux"
hideNode('Reseaux')
displayTree(tree)

if __name__ == "__main__":
test()


Tuesday, March 4, 2008

Learning F# - List Concatenation

My first attempt with lists in F# :-)

let lofl = [[1;2];[3;4];[5;6]]

let rec concat ll =
match ll with
| [] -> []
| h :: t -> h @ concat t

printf "%A" (concat lofl)
read_line()

Sunday, March 2, 2008

Embed Win32 resources in C# programs

This article explains all ...
http://www.codeproject.com/KB/cs/embedwin32resources.aspx

ADO - Python

Querying ACCESS with Python


from win32com.client import Dispatch as CreateObject

conn = CreateObject("ADODB.Connection")
mdb = r"C:\northwind.mdb"
conn.Open("Driver={Microsoft Access Driver (*.mdb)}; DBQ=%s;"%mdb)


def execRequest(sql):
r,t = conn.Execute(sql )
cust = "<table>\n"
while not r.EOF:
s = "<tr>"
for item in r.Fields:
if item.Name == "ContactName" or item.Name == "Address":
s+= "<td>%s</td>"%(item.Value)
s += "</tr>\n"
cust += s
r.MoveNext()
cust += "</table>\n"
return cust

cust = execRequest("select * from customers")

conn.Close()


Sunday, February 24, 2008

WMI - FSharp

WMI test is my 'Hello World' :-)

#light
open System
open System.Management

let getLogicalDisk () =
let query = "select * from win32_logicaldisk where drivetype = '3'"
let objMgt = new ManagementObjectSearcher(query)
let result = objMgt.Get()
for info in result do
let caption = info.GetPropertyValue("Caption").ToString()
let size = info.GetPropertyValue("Size").ToString()
printf "%2s : %15s Ko\n" caption size

getLogicalDisk ()

read_line ()

FSharp - Discovering

I must admit that after Python, It has been difficult for me to find another
language which was as attractive as Python.
I think F# will be this one.


#light

open System

let print x = printfn "%A" x
let sub a b = a - b

let halfway a b =
let dif = b -a
let mid = dif/2
let z = mid + a
z

let y = (fun x y -> x + y) 1 2

let rec fib x =
match x with
| 1 -> 1
| 2 -> 1
| x -> fib (x-1) + fib (x-2)

let UnAnApres =
DateTime.Now + new TimeSpan(365,0,0,0,0)

let print_List l =
List.iter print_string l
print_string "\n"

let shortHand = ["apples"; "pairs"]

shortHand |> printf "%A"

read_line ()

Wednesday, February 6, 2008

Performance Counters - Python

The module win32pdh allows to retrieve performance counters on Windows host
Here is an example published on ASPN.
You will have to use "win32pdhutil.browse" to translate counters names
in your language.


import win32pdh
import win32pdhutil

#Use win32pdh, Kevan Heydon, 2006/06/23
#http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496815

#win32pdhutil.browse()

def uptimeServeur(serveur='Python'):
path = win32pdh.MakeCounterPath( ( serveur, 'Système', None, None, 0, "Temps d'activité système") )
query = win32pdh.OpenQuery()
handle = win32pdh.AddCounter( query, path )
win32pdh.CollectQueryData( query )
seconds = win32pdh.GetFormattedCounterValue( handle, win32pdh.PDH_FMT_LONG | win32pdh.PDH_FMT_NOSCALE )[ 1 ]
return "Serveur : %s - Uptime: %d seconds" %(serveur,seconds )

print uptimeServeur()

Sunday, February 3, 2008

HTA - Python - Sorting Table

This example shows a method to sort a html table in Python within a HTA file
The things to note are:
- Inserting dynamically within a url the name of the list to be display.
- How to sort a list by index

To run HTA files, simply copy this peace of code with the extension '.hta'
and of course Python must be installed (ActiveState Python will do the job)


<html>
<head>
<TITLE>HTML Application Example</TITLE>
<HTA:APPLICATION ID="HTAEx" APPLICATIONNAME="HTAEx" ICON="e.ico" WINDOWSTATE="normal">
</head>

<body onLoad="Initialisation()">

<table><tr><td valign="top"><div id="menu">Menu</td><td><div id="content">contenu</div></td></tr></table>

<script language="Python">

from win32com.client import GetObject
import os
import cPickle as pickle
import base64
import operator

sorteddata = [0]*10

donnee = [('Name','Town','Age'),('Albert','Paris',46),
('Robert','Denver',49),
('Grace','Monaco',18),
('Catherine','Palaiseau',25)]

services = {}


ChaineConnexion = r"WinMgMts:\\%s\%s"

#Menu
menu="""
<p>Menu Principal</p>
<center>
<select name="choices" onChange="SelectOption()">
<option>%s</option>
<option value="service">Service</option>
<option value="process">Process</option>
</select>
</center>
"""%('-'*40)


def getValue(id):
#return document.getElementById(id).value
return document.getElementById(id).getAttribute("value")

def getElt(id):
return document.getElementById(id)

def setValue(divid,data):
elt = document.getElementById(divid)
elt.innerHTML = data

def Pointer():
document.body.style.cursor = "hand"
return

def Default():
document.body.style.cursor = "default"
return


def sortTable(idcol,table):
obj = decodeObj(table)
titre = list(obj[0])
data = obj[1:]
index = titre.index(idcol)
sorteddata[index] = 1 - sorteddata[index]
data.sort(key=operator.itemgetter(index),reverse=sorteddata[index])
data.insert(0,titre)
t = formatTable(data)
setValue('content',t)


def decodeObj(s):
objects = base64.decodestring(s)
return pickle.loads(objects)

def encodeObject(obj):
data = base64.encodestring(pickle.dumps(obj))
return data.__repr__()

def formatTable(data):
tablestr = encodeObject(data)
titre = data[0]
numitem = len(titre)
lnktitre = ["""<span onclick="sortTable('%s',%s)" \
onmouseover='Pointer()' \
onmouseout='Default()'>%s</span>"""%(t,tablestr,t) for t in titre]
table = "<table border='1'>"
table += "<tr>" + ("<td>%s</td>"*numitem)%tuple(lnktitre) + "</tr>"
for item in data[1:] :
table += "<tr>" + ("<td>%s</td>"*numitem)%item + "</tr>"
table += "</table>"
return table

def getAllObjects(serveur = ".", espaceDenom = "root\cimv2", classe = "Win32_Service"):
c = GetObject(ChaineConnexion%(serveur,espaceDenom))
objects = c.ExecQuery(r"select * from %s"%classe)
return objects

def getService():
data = [('Caption','State')]
services = getAllObjects()
for svc in services:
data.append((svc.caption,svc.state))
setValue('content',formatTable (data))

def getProcess():
data = [('Handle','Name','CommandLine')]
process = getAllObjects(classe="Win32_Process")
for proc in process:
data.append((int(proc.Handle),proc.Name,proc.CommandLine))
setValue('content',formatTable (data))

def SelectOption():
services[getValue('choices')]()

services['service'] = getService
services['process'] = getProcess

def Initialisation():
setValue('content',formatTable(donnee))
setValue('menu',menu)
</script>

</body>
</html>

Thursday, January 24, 2008

Sunday, January 20, 2008

ASP.NET - IronPython

It's now possible to use IronPython in Visual Web Developpement Express Edition 2008.
If you are wondering does it worth to switch to IronPython.
Look at this server side part, and compare it with the traditionals languages used

Server Side:

def Page_Load(sender, e):
pass

def onClickButton1(s,e):
color = result.InnerHtml = TextBox1.Text
result.Style.set_Value("background-color:%s;"%color)

def Menu1_MenuItemClick(s,e):
result.Style.set_Value("background-color:red")
choice = Menu1.SelectedValue
result.InnerHtml = choice


Client Part:

<%@ Page Language="IronPython" CodeFile="Default.aspx.py" Inherits="Microsoft.Web.Scripting.UI.ScriptPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="Fichier" Value="Fichier"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="onClickButton1" />
<div id="result" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Friday, January 18, 2008

Boo on .Net

What language choose for .Net : C# VB.NET IronPython ?
Although my language of choice is Python, I must admit
that Boo is very attractive.
It does not have the verbosity of VB.NET or C# and it's syntax
is greatly inspired by Python.
Take a look at this presentation :
http://www.infoq.com/articles/boo-intro