SlideShare a Scribd company logo
Dynamic Language Programming
                   for the Statically Typed Programmer




» Marco Parenzan
Marco Parenzan



» Abito a Fiume Veneto (Pordenone)
» Sono un libero professionista
  • Mi muovo sul medio piccolo
  • Mi muovo tra Friuli e Veneto
» Insegno all’Università di Trieste Programmazione
  dei Web Services
  • …e in aziende…
» Sviluppo applicazioni su commessa
» Sviluppo prototipi
  • Idee alternative…

                        www.xedotnet.org             2
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org     3
I tuls



» Sono uno statically-typed programmer
   • Intellisense-addicted
   • Pesante uso del refactoring
» Tipicamente in overloading (carico di lavoro)
   • Relativamente poco spazio per l’ingegneria
      • Tutto ciò che è ingegneristico non viene pagato
      • Il documento di specifiche…chi è costui?
      • Nessun tempo per lo Unit Testing, almeno non in questa forma
   • Sicuramente Agile, è buon senso…
   • Largo spazio alla produttività (=butta li?)
» C#, .NET, Visual Studio e i metadati aiutano pesantemente
   • Perché complicarsi la vita?


                               www.xedotnet.org                        4
Non uccidetemi…



» Spero di non fare cattiva pubblicità
  • Non è mia intenzione fare cattiva pubblicità
» Non sono un programmatore di scarsa qualità
  • Le notti sono amiche…
» I compromessi ci devono essere
» Progetti da n K€
  • n<<10




                        www.xedotnet.org                  5
Dove si sta andando a finire?



» Dynamic Languages
  • No Intellisense
     • Non tutto è jQuery…
  • No Refactoring (…)
  • No prestazioni (…, ???)
» Però…




                         www.xedotnet.org                           6
… bisogna accontentare il cliente



» Modifiche/personalizzazioni continue
» Il deployment è un problema
  • Non siamo a “velocità ingegneristiche” (tipicamente
    lente)
  • Rilasci “non controllati”
» UI=Testing sul campo
  • Stiamo inserendo ORA l’MVC o l’MVVM
  • WPF difficile da adottare
     • 3 anni persi (dall’introduzione di WPF)
     • L’MVVM è la parte più semplice (comunque se ne parla da un
       anno)
  • ASP.NET MVC
  • Fino all’anno scorso non c’erano

                           www.xedotnet.org                               7
“code is value”



» Il codice “è un valore”
  • Non solo in termini di Know-How
  • Qualcosa da assegnare ad una variabile
» Il codice è un parametro
» L’algoritmo può cambiare
  • Gestire il versioning dell’algoritmo…
  • …come gestire la coesistenza di n-versioni?
  • …ricostruire il calcolo
» Legare documenti a versioni di codice

                        www.xedotnet.org                    8
Ispirazioni



» VBScript
» Office
  • Visual Basic for Application (Alt+F11)
» La community Unix
  • Perl
  • Shell
» Powershell



                        www.xedotnet.org           9
Necessità



» Scrivere codice dopo il deployment
  • On site
  • Magari senza aprire Visual Studio
» Codice dopo il deployment=dato




                       www.xedotnet.org       10
Quando realmente serve?



»   Formule
»   Codice di calcolo
»   Report (io uso librerie PDF)
»   Import/Export
»   Altre idee (non ancora provate)
    • Maschere (stile Access)




                         www.xedotnet.org                     11
Come lo potevo fare fino ad ora?



» I due estremi
  • VBScript spero di no…
  • .NET 5.x
     • Compiler as a Service (Anders Hejlsberg, PDC 2008)
     • “eval”




                          www.xedotnet.org                              12
.NET 1.x, 2.0, 3.x




 » CodeDom + csc.exe
      • Lo stesso discorso vale anche per VB



                                                   Creazione                   IStaticScript
                Inclusione in un    Creazione
Script C#                                           dinamica      istanza
                    template       dell’assembly
                                                   dell’istanza                •Execute




      www.xedotnet.org                                                                         13
C# 3.0 Consuming IronPython




public class Calculator {               class Calculator:
    …                                       …
    public int Add(int x, int y) {          def Add(self, x, y):
        return x + y;                           return x + y
    }
}


                                   PyObject calc = GetCalculator();
Calculator calc = GetCalculator(); object res = calc.Invoke("Add", 10, 20);
int sum = calc.Add(10, 20);        int sum = Convert.ToInt32(res);

               object calc = GetCalculator();
               Type calcType = calc.GetType();
               object res = calcType.InvokeMember("Add",
                   BindingFlags.InvokeMethod, null,
                   new object[] { 10, 20 });
               int sum = Convert.ToInt32(res);
Vantaggi del CodeDOM



» C#/VB
» C# 3.0 features
  •   anonymous types
  •   Implicit typed variabiles
  •   Object/collection initializers
  •   Lambda Expression
» Magari un Editor con Color Syntax Highlighting e
  Intellisense
  • Soprattutto ora che l’editor di VS2010 è riusabile

                           www.xedotnet.org                  15
Svantaggi del CodeDOM



» Static Compiling
» “NO” REPL
  • In realtà Mono ce l’ha: http://mono-
    project.com/CsharpRepl
» “NO” CODE AS VALUE
  • No valutazione “istantanea”
» Vincoli della compilazione statica
  • Add Reference
  • Using…

                       www.xedotnet.org                    16
C# 4.0




public class Calculator {                     class Calculator:
    …                                             …
    public int Add(int x, int y) {                def Add(self, x, y):
        return x + y;                                 return x + y
    }
}


Statically typed to
   be dynamic                dynamic calc = GetCalculator();
                             int sum = calc.Add(10, 20);


                       Dynamic                Dynamic method
                      conversion                 invocation
Quando usare il CodeDOM?



» Quando scrittura codice e consumo sono due
  momenti:
  • distinti (chi usa non consuma)
  • distanti (scrivo una volta e faccio il test, poi andrà in
    esecuzione)




                          www.xedotnet.org                      18
Scripting (da Wikipedia)


» La distinzione tra un programma normale ed uno script non è
  netta, ma generalmente negli script si possono individuare le
  seguenti caratteristiche:
   • complessità relativamente bassa
   • utilizzo di un linguaggio interpretato
   • integrazione in un processo di configurazione automatica del
     sistema (ad esempio ad ogni avvio, o ad ogni login di un dato
     utente), in una pagina web (tipicamente utilizzando il linguaggio
     JavaScript), o comunque per svolgere mansioni accessorie e molto
     specifiche
   • una certa linearità (uno script può anche accettare input
     dall'utente, ma solitamente input diversi non modificano
     sostanzialmente la struttura del Diagramma a blocchi che descrive
     il comportamento dello script)
   • mancanza di una propria interfaccia grafica (…)
   • richiamo di altri programmi per svolgere operazioni più sofisticate

                              www.xedotnet.org                          19
Specifiche (1)


» complessità relativamente bassa
   • Non si vuole sostituire il C#
   • Non me ne voglia la community dei Dynamic Languages
   • Ognuno usa il linguaggio con cui si trova bene…
   • …e io sto bene con il C#
   • Sostituire solo alcuni pezzi
» utilizzo di un linguaggio interpretato
   • Non siamo in condizioni di criticità per le performances
» svolgere mansioni accessorie e molto specifiche
   • Non si vuole scrivere TUTTO Il programma, ma solo certe
     parti
   • Personalizzazioni

                          www.xedotnet.org                    20
Specifiche (2)



» una certa linearità
  • Il flusso di esecuzione viene sempre implementato
    nel core scritto in C#
» mancanza di una propria interfaccia grafica
  »   Qui si può disquisire
  »   WPF è scripting? No, però XamlReader.Load()…
  »   …e una maschera custom….
  »   …ma adesso no…di nuovo, il core è in C#
      » Release 2 di questo lavoro
» richiamo di altri programmi per svolgere operazioni
  più sofisticate
  » Richiamare il core dell’applicazione

                               www.xedotnet.org              21
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org    22
Static(ally typed) Language



» Un linguaggio in cui il controllo dei tipi avviene a
  compile time
» Il tipo è associato alle variabili, non ai valori
» Permettono di verificare e notificare (almeno in
  parte) parte degli errori sui tipi prima ancora di
  andare in esecuzione




                       www.xedotnet.org                        23
Dynamic(ally typed) Language



» Un linguaggio in cui il controllo dei tipi avviene a
  runtime
» Il tipo è associato ai valori, non alle variabili
» Non permettono di verificare e notificare gli
  errori di tipo se non quando vanno in
  esecuzione




                       www.xedotnet.org                          24
Confronto




     Static                Dynamic
   Languages              Languages

     Robusto           Semplice e stringato

                           Interpretato
   Performante
                        (no compilazione)

     Strumenti           “implicitamente
   “intelligenti”           tipizzato”

Migliore scalabilità   Meta-programming
Le peculiarità di un Dynamic Language



» Semplice e stringato
  • È una scelta tipica di chi ha sviluppato questi linguaggi
  • Sintassi leggera
  • Molte funzioni lasciate in API in linguaggi statici sono
    implementate nel linguaggio
» Interpretato
  • È la diretta conseguenza della semplicità, evitando la
    “complicazione” di un processo di compilazione
  • Il senso è generale, senza pensare ad un IDE
» Implicitamente tipizzato
Metaprogramming



» Il metaprogramming è la scrittura di un programma
  in grado di scrivere o manipolare altri programmi o
  se stesso
» Un metaprogramma effettua a tempo di esecuzioni
  operazioni che sarebbero, in condizioni normali,
  effettuate a tempo di compilazione
» L'obiettivo del metaprogramming è quello di
  produrre programmi in grado di adattarsi
  dinamicamente ad una configurazione che cambia
  nel tempo, senza intervento umano

                       www.xedotnet.org              27
Alune definizioni



» Metaprogramma: il prodotto dell'atto di
  metaprogramming
» Metalinguaggio: linguaggio utilizzato per
  scrivere il metaprogramma
» Linguaggio oggetto: il linguaggio del programma
  manipolato
» Se il metalinguaggio ed il linguaggio di
  programmazione coincidono, l'attività di
  metaprogramming prende il nome di reflection

                     www.xedotnet.org               28
Quale scegliere?



» Due “generazioni” di linguaggi
  • Nativi (con virtual machine proprietaria)
  • Su Runtime (.NET o JVM)
» Alcuni
  • Python (IronPython, Jython)
  • Ruby (IronRuby, JRuby)
» Perché portare Python o Ruby su .NET o JVM?
  • Py o Rb usano il runtime
  • Py o Rb sono accessibli dal runtime (e questo è il
    nostro caso)

                        www.xedotnet.org                   29
Dynamic Interoperability




  Different heaps                 CLR’s GC heap

                                          py1
                       Common
                       Language
 py1           c2       Runtime

                                           c2


Python       C-Based
Objects      Objects                 .NET Objects
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org    31
Cos’è Python?


» Un linguaggio di programmazione general purpose
» Sviluppato da Guido van Rossum nel 1991
» Un linguaggio dinamico usato spesso come linguaggio di
  scripting
» Supporta diversi paradigmi di programmazione:
   • Object Oriented
   • Imperative
   • Functional
» Its design philosophy emphasizes:
   •   Leggibilità del codice
   •   Sintassi minimalista
   •   Una estesa set di librerie
   •   Duck Typing
IronPython



» È l’implementazione del linguaggio Python
  • IronPython è scritto interamente in C#
» Creato da Jim Hugunin
  • sviluppatore anche di Jython (Python su JVM)
  • Voleva scrivere un paper dal titolo “Why .NET is a
    Terrible Platform for Dynamic Languages”
  • Invece nel settembre del 2004 iniziava a lavorare in
    Microsoft
     • http://conferences.oreillynet.com/presentations/os2004/
       hugunin_jim_up.ppt

                         www.xedotnet.org                    33
Performances


 Test                       Descrizione                                                                         Prestazione
 parser (b0)                heavy OO plus meta programming                                                      x1.1 faster
 stacks (b1)                handling of stack overflow                                                          x2.1 faster
 PI (b2)                    using generators to compute π                                                       same
 sorting (b3)               many different comparsions and sorting                                              x1.5 faster
 parser2 (b4)               reprise of parser with different input                                              x1.2 slower
 builtins (b5)              testing unicode, complex numbers, …                                                 x2.3 slower
 iterators (b6)             – looping and overflow from int to long                                             x1.2 faster

      Python-2.3                                                                           OSCon 2004 – IronPython 0.6
                                                                                           1.7x faster than Python-2.3 on
       IronPython                                                                          pystone

IronPython (Mono)


                    0   1    2    3    4          5    6   7   8        9   10   11   12
                                                time (seconds)
                             b0   b1       b2     b3   b4   b5     b6


                                                                        www.xedotnet.org                                34
Versioni di IronPython




IronPython         IronPython               IronPython        IronPython
1.0                1.1                      2.0               3.0
• Sept. 2006       • April 2007             • Early 2008      • Early 2009
• 2.4 language     • 2.4 language           • 2.5 language    • 3.0 language?
• 27/54            • Partial 2.5            • More modules    • More modules
  builtinmodules     support                • Internal
                   • More modules             architecture
                   • Top user issues          work




                                 www.xedotnet.org                            35
Aggiornamento IronPython al 30 ottobre 2009


» http://ironpython.codeplex.com/
» .NET 3.5sp1
   • IronPython 2.0.3
      • 22 ottobre 2009
      • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea
        seId=30416
   • IronPython 2.6 RC2
      • 27 ottobre 2009
      • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea
        seId=34451
» .NET 4.0 Beta 2
   • IronPython 2.6 CTP for .NET 4.0 Beta 2
      • 21 ottobre 2009
      • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea
        seId=28125


                              www.xedotnet.org                              36
Aggiornamento IronRuby al 30 ottobre 2009


» http://ironruby.codeplex.com/
» .NET 3.5sp1
   • IronRuby 0.9.1
      • 29 settembre 2009
      • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI
        d=30916
   • IronPython binaries for ironruby-0.9.1 interop
      • 29 settembre 2009
      • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI
        d=30916#DownloadId=85530
» .NET 4.0 Beta 2
   • IronRuby CTP for .NET 4.0 Beta 2
      • 21 ottobre 2009
      • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI
        d=33305


                              www.xedotnet.org                               37
Aggiornamento DLR al 30 ottobre 2009



» http://dlr.codeplex.com/
» .NET 3.5sp1 e .NET 4.0 Beta 2, solo src
  • 22 ottobre 2009
  • http://dlr.codeplex.com/Release/ProjectReleases.as
    px?ReleaseId=34834




                       www.xedotnet.org                                  38
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org    39
» “Why .NET is a Terrible Platform for Dynamic
  Languages”
» IronPython “risolve” l’implementazione del
  Python su .NET
  • In realtà risolve anche problematiche valide per tutti
    i Dynamic Languages implementabili
» IronPython 2.0 (specific)
  • On the top of DLR (generic)



                        www.xedotnet.org                40
Dynamic Languages on .NET




IronPython      IronRuby          C#           VB.NET        Others…


                 Dynamic Language Runtime

   Expression Trees         Dynamic Dispatch       Call Site Caching

 Object        JavaScript        Python         Ruby            COM
 binder          binder          binder        binder          binder
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org    42
Alcuni esempi



» IronPython (scripting) in applicazioni WPF
  • Customize LOB application
» IronPython e l’interrogazione DB
» Report in PDF
  • Un esempio di una libreria Python
  • Una delle tante




                       www.xedotnet.org                43
A commercial use of IronPython



» Resolver Systems, ResolverOne
  a financial analytical tool that simulates
  a spread sheet
Agenda



»   Introduzione
»   Cos’è un Dynamic Language
»   Python e IronPython
»   Dynamic Language Runtime
»   Alcuni esempi
»   Conclusioni




                     www.xedotnet.org    45
Conclusioni



» Necessità dello scripting
   • Risolvere il problema delle personalizzazioni c/o il cliente
» Risolto?
   • No, forse non si risolverà mai
   • Però è un altro passo avanti
» Credenza di fondo
   • Scelgo di usare ANCHE un altro linguaggio
      • “Polyglot programmer”
   • Accetto il “compromesso” del “dinamico”
» Attingere ad un parco di implementazioni (tutte
  open source) eccezionale in maniera nativa
   • Ruby on Rails

                           www.xedotnet.org                     46
Esempi Visti



» “Static” scripting con C#
» Esempy
» Hosting DLR in una applicazione .NET
  •   Expressions
  •   Customize the lifetime di una LOB WPF window
  •   Query con Entity Framework
  •   Reports (con ReportLab)
» Resolver One


                        www.xedotnet.org               47
Esempi Non Visti



» Altre librerie Python
» Ruby e Ruby on Rails
» Gestalt
  • Python e Ruby per lo scripting in pagine HTML
  • Usa un componente Silverlight senza UI




                       www.xedotnet.org                  48
Il team che lavora sul DLR e dintorni


» Jim Hugunin (DLR)                                       » Dave Fugate (IronPython)
    •   Blog: http://blogs.msdn.com/hugunin/                       •   Blog: http://knowbody.livejournal.com/
» Dino Viehland (IronPython)                                       •   Twitter: http://twitter.com/davefugate
    •   Blog: http://blogs.msdn.com/dinoviehland/         » Harry Pierson (Evangelist)
    •   Twitter: http://twitter.com/DinoViehland                   •   Blog: http://www.devhawk.net/
» Jimmy Schementi (Silverlight                                     •   Twitter: http://twitter.com/DevHawk
  integration)                                            » Seo Sanghyeon (IronPython)
    •   Blog: http://blog.jimmy.schementi.com/                     •   Blog: http://fepy.blogspot.com/
    •   Twitter: http://twitter.com/jschementi                     •   Twitter: http://twitter.com/sanxiyn
» John Lam (IronRuby)                                     » Jim Deville (IronRuby)
    •   Blog: http://www.iunknown.com/                             •   Blog: http://blog.jredville.com/
    •   Twitter: http://twitter.com/john_lam/                      •   Twitter: http://twitter.com/jredville
» Curt Hagenlocher (IronPython)                           » Shri Borde (IronRuby)
    •   Blog: http://blogs.msdn.com/curth/                         •   Blog: http://blogs.msdn.com/shrib/
                                                          » Tomas Matousek (IronRuby)
                                                                   •   Blog: http://blog.tomasm.net/




                                                www.xedotnet.org                                                49
Autori



» Michael Foord
  • Libro: http://www.manning.com/foord/
  • Blog: http://www.voidspace.org.uk/python/weblog/index.shtml
  • Twitter: http://twitter.com/Voidspace
» Ivar Porto Carrero
  • Libro: http://www.manning.com/carrero/
  • Blog: http://flanders.co.nz/
  • Twitter: http://twitter.com/casualjim



                               www.xedotnet.org                    50
Link


Marco Parenzan
          blog: http://blog.codeisvalue.com/
         email: marco.parenzan@libero.it
          web: http://www.codeisvalue.com/
        Skype: marco.parenzan
     Messenger marco.parenzan@live.it
       Twitter: marco_parenzan
    community: www.xedotnet.org




                         www.xedotnet.org      51
Agenda



Virtual Meetings
Venerdì 30/10
Dynamic Language Programming for the Statically Typed
Language Programmer
          Speaker: Marco Parenzan

Venerdì 20/11
Microsoft Velocity: overview, practical setup and usage
          Speaker: Andrea Colaci




Dalle 21:00 alle 22:00


                               www.xedotnet.org            52
Agenda



Community Meetings
Venerdì 25/9 - Pattern Track
          Speaker: Senatore e Servienti

Venerdì 16/10 – Team Foundation Server Track
          Speaker: Barbieri e Vernole

Venerdì 6/11 – Web Track
          Speaker: Boschin e Vernole

Venerdì 12/12 – Data Track
          Speaker: Boschin e Dottor

Dalle 19:00 alle 23:00


                                www.xedotnet.org    53
Grazie
                                         Q&A

                       blog:    http://blog.codeisvalue.com/
                      email:    marco.parenzan@libero.it
                       web:     http://www.codeisvalue.com/
                      Skype:    marco.parenzan
                   Messenger    marco.parenzan@live.it
                     Twitter:   marco_parenzan

www.xedotnet.org                                               54

More Related Content

PPTX
Introduzione a TypeScript
PDF
DotNetToscana - Sessione TypeScript
PPT
PDF
Lezione 3: Sviluppo in Extreme Programming
PPTX
Da JavaScript a TypeScript
PDF
Lezione 4: I tool Ant e Subversion
PDF
Lezione 6b: Design Pattern Strutturali
PPT
Primo Incontro Con Scala
Introduzione a TypeScript
DotNetToscana - Sessione TypeScript
Lezione 3: Sviluppo in Extreme Programming
Da JavaScript a TypeScript
Lezione 4: I tool Ant e Subversion
Lezione 6b: Design Pattern Strutturali
Primo Incontro Con Scala

Viewers also liked (6)

PPTX
.NET Development for SQL Server Developer
PPTX
Objects in the Cloud - Edition 2014
PPTX
Implementing CQRS with Azure
PDF
2010.04.30 summary of cloud futures 2010 marco parenzan pov
PPTX
GWAB2014 Italy Keynote
PPTX
2014.11.22 Azure for Sql Server Developer - SQLSAT355 Parma
.NET Development for SQL Server Developer
Objects in the Cloud - Edition 2014
Implementing CQRS with Azure
2010.04.30 summary of cloud futures 2010 marco parenzan pov
GWAB2014 Italy Keynote
2014.11.22 Azure for Sql Server Developer - SQLSAT355 Parma
Ad

Similar to Dynamic Language Programming For The Statically Typed Programmer (20)

PPTX
.Net 4.0 Preview @ UGIdotNet
PDF
2010.05.21 introducing sql server modeling
PPTX
Lo sai che si può fare DDD in Javascript grazie a Typescript? Visual Studio e...
PPTX
2010.11.19 iniziare con F#
PPTX
2010.11.19 iniziare con f#
PPTX
C#, imparare a programmare e sopravvivere
PDF
MonoTouch, un anno dopo
PDF
OOP... Object Whaaat?
PPTX
Inversion of Control @ CD2008
PPTX
2010.11.26 F# questo sconosciuto
PPTX
Christmas greetings cards with blazor
PDF
2010 02 26 C# E Vb Language Evolution
PPTX
Test Driven Development @ Xe.Net
PDF
T1 introduzione
PPTX
VS Package @ CD2008
PDF
Wasm and Blazor CDays keynote
PPTX
Evoluzione degli strumenti di sviluppo Microsoft
PPTX
Silverlight m v-vm @ DotNetteria
PDF
Spa with Blazor
PPT
Generazione Dinamica di Codice in .NET
.Net 4.0 Preview @ UGIdotNet
2010.05.21 introducing sql server modeling
Lo sai che si può fare DDD in Javascript grazie a Typescript? Visual Studio e...
2010.11.19 iniziare con F#
2010.11.19 iniziare con f#
C#, imparare a programmare e sopravvivere
MonoTouch, un anno dopo
OOP... Object Whaaat?
Inversion of Control @ CD2008
2010.11.26 F# questo sconosciuto
Christmas greetings cards with blazor
2010 02 26 C# E Vb Language Evolution
Test Driven Development @ Xe.Net
T1 introduzione
VS Package @ CD2008
Wasm and Blazor CDays keynote
Evoluzione degli strumenti di sviluppo Microsoft
Silverlight m v-vm @ DotNetteria
Spa with Blazor
Generazione Dinamica di Codice in .NET
Ad

More from Marco Parenzan (20)

PPTX
Azure IoT Central per lo SCADA engineer
PPTX
Azure Hybrid @ Home
PPTX
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
PPTX
Azure Synapse Analytics for your IoT Solutions
PPTX
Power BI Streaming Data Flow e Azure IoT Central
PPTX
Power BI Streaming Data Flow e Azure IoT Central
PPTX
Power BI Streaming Data Flow e Azure IoT Central
PPTX
Developing Actors in Azure with .net
PPTX
Math with .NET for you and Azure
PPTX
Power BI data flow and Azure IoT Central
PPTX
.net for fun: write a Christmas videogame
PPTX
Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...
PPTX
Anomaly Detection with Azure and .NET
PPTX
Deploy Microsoft Azure Data Solutions
PPTX
Deep Dive Time Series Anomaly Detection in Azure with dotnet
PPTX
Azure IoT Central
PPTX
Anomaly Detection with Azure and .net
PPTX
Code Generation for Azure with .net
PPTX
Running Kafka and Spark on Raspberry PI with Azure and some .net magic
PPTX
Time Series Anomaly Detection with Azure and .NETT
Azure IoT Central per lo SCADA engineer
Azure Hybrid @ Home
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Azure Synapse Analytics for your IoT Solutions
Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central
Developing Actors in Azure with .net
Math with .NET for you and Azure
Power BI data flow and Azure IoT Central
.net for fun: write a Christmas videogame
Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...
Anomaly Detection with Azure and .NET
Deploy Microsoft Azure Data Solutions
Deep Dive Time Series Anomaly Detection in Azure with dotnet
Azure IoT Central
Anomaly Detection with Azure and .net
Code Generation for Azure with .net
Running Kafka and Spark on Raspberry PI with Azure and some .net magic
Time Series Anomaly Detection with Azure and .NETT

Dynamic Language Programming For The Statically Typed Programmer

  • 1. Dynamic Language Programming for the Statically Typed Programmer » Marco Parenzan
  • 2. Marco Parenzan » Abito a Fiume Veneto (Pordenone) » Sono un libero professionista • Mi muovo sul medio piccolo • Mi muovo tra Friuli e Veneto » Insegno all’Università di Trieste Programmazione dei Web Services • …e in aziende… » Sviluppo applicazioni su commessa » Sviluppo prototipi • Idee alternative… www.xedotnet.org 2
  • 3. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 3
  • 4. I tuls » Sono uno statically-typed programmer • Intellisense-addicted • Pesante uso del refactoring » Tipicamente in overloading (carico di lavoro) • Relativamente poco spazio per l’ingegneria • Tutto ciò che è ingegneristico non viene pagato • Il documento di specifiche…chi è costui? • Nessun tempo per lo Unit Testing, almeno non in questa forma • Sicuramente Agile, è buon senso… • Largo spazio alla produttività (=butta li?) » C#, .NET, Visual Studio e i metadati aiutano pesantemente • Perché complicarsi la vita? www.xedotnet.org 4
  • 5. Non uccidetemi… » Spero di non fare cattiva pubblicità • Non è mia intenzione fare cattiva pubblicità » Non sono un programmatore di scarsa qualità • Le notti sono amiche… » I compromessi ci devono essere » Progetti da n K€ • n<<10 www.xedotnet.org 5
  • 6. Dove si sta andando a finire? » Dynamic Languages • No Intellisense • Non tutto è jQuery… • No Refactoring (…) • No prestazioni (…, ???) » Però… www.xedotnet.org 6
  • 7. … bisogna accontentare il cliente » Modifiche/personalizzazioni continue » Il deployment è un problema • Non siamo a “velocità ingegneristiche” (tipicamente lente) • Rilasci “non controllati” » UI=Testing sul campo • Stiamo inserendo ORA l’MVC o l’MVVM • WPF difficile da adottare • 3 anni persi (dall’introduzione di WPF) • L’MVVM è la parte più semplice (comunque se ne parla da un anno) • ASP.NET MVC • Fino all’anno scorso non c’erano www.xedotnet.org 7
  • 8. “code is value” » Il codice “è un valore” • Non solo in termini di Know-How • Qualcosa da assegnare ad una variabile » Il codice è un parametro » L’algoritmo può cambiare • Gestire il versioning dell’algoritmo… • …come gestire la coesistenza di n-versioni? • …ricostruire il calcolo » Legare documenti a versioni di codice www.xedotnet.org 8
  • 9. Ispirazioni » VBScript » Office • Visual Basic for Application (Alt+F11) » La community Unix • Perl • Shell » Powershell www.xedotnet.org 9
  • 10. Necessità » Scrivere codice dopo il deployment • On site • Magari senza aprire Visual Studio » Codice dopo il deployment=dato www.xedotnet.org 10
  • 11. Quando realmente serve? » Formule » Codice di calcolo » Report (io uso librerie PDF) » Import/Export » Altre idee (non ancora provate) • Maschere (stile Access) www.xedotnet.org 11
  • 12. Come lo potevo fare fino ad ora? » I due estremi • VBScript spero di no… • .NET 5.x • Compiler as a Service (Anders Hejlsberg, PDC 2008) • “eval” www.xedotnet.org 12
  • 13. .NET 1.x, 2.0, 3.x » CodeDom + csc.exe • Lo stesso discorso vale anche per VB Creazione IStaticScript Inclusione in un Creazione Script C# dinamica istanza template dell’assembly dell’istanza •Execute www.xedotnet.org 13
  • 14. C# 3.0 Consuming IronPython public class Calculator { class Calculator: … … public int Add(int x, int y) { def Add(self, x, y): return x + y; return x + y } } PyObject calc = GetCalculator(); Calculator calc = GetCalculator(); object res = calc.Invoke("Add", 10, 20); int sum = calc.Add(10, 20); int sum = Convert.ToInt32(res); object calc = GetCalculator(); Type calcType = calc.GetType(); object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 }); int sum = Convert.ToInt32(res);
  • 15. Vantaggi del CodeDOM » C#/VB » C# 3.0 features • anonymous types • Implicit typed variabiles • Object/collection initializers • Lambda Expression » Magari un Editor con Color Syntax Highlighting e Intellisense • Soprattutto ora che l’editor di VS2010 è riusabile www.xedotnet.org 15
  • 16. Svantaggi del CodeDOM » Static Compiling » “NO” REPL • In realtà Mono ce l’ha: http://mono- project.com/CsharpRepl » “NO” CODE AS VALUE • No valutazione “istantanea” » Vincoli della compilazione statica • Add Reference • Using… www.xedotnet.org 16
  • 17. C# 4.0 public class Calculator { class Calculator: … … public int Add(int x, int y) { def Add(self, x, y): return x + y; return x + y } } Statically typed to be dynamic dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); Dynamic Dynamic method conversion invocation
  • 18. Quando usare il CodeDOM? » Quando scrittura codice e consumo sono due momenti: • distinti (chi usa non consuma) • distanti (scrivo una volta e faccio il test, poi andrà in esecuzione) www.xedotnet.org 18
  • 19. Scripting (da Wikipedia) » La distinzione tra un programma normale ed uno script non è netta, ma generalmente negli script si possono individuare le seguenti caratteristiche: • complessità relativamente bassa • utilizzo di un linguaggio interpretato • integrazione in un processo di configurazione automatica del sistema (ad esempio ad ogni avvio, o ad ogni login di un dato utente), in una pagina web (tipicamente utilizzando il linguaggio JavaScript), o comunque per svolgere mansioni accessorie e molto specifiche • una certa linearità (uno script può anche accettare input dall'utente, ma solitamente input diversi non modificano sostanzialmente la struttura del Diagramma a blocchi che descrive il comportamento dello script) • mancanza di una propria interfaccia grafica (…) • richiamo di altri programmi per svolgere operazioni più sofisticate www.xedotnet.org 19
  • 20. Specifiche (1) » complessità relativamente bassa • Non si vuole sostituire il C# • Non me ne voglia la community dei Dynamic Languages • Ognuno usa il linguaggio con cui si trova bene… • …e io sto bene con il C# • Sostituire solo alcuni pezzi » utilizzo di un linguaggio interpretato • Non siamo in condizioni di criticità per le performances » svolgere mansioni accessorie e molto specifiche • Non si vuole scrivere TUTTO Il programma, ma solo certe parti • Personalizzazioni www.xedotnet.org 20
  • 21. Specifiche (2) » una certa linearità • Il flusso di esecuzione viene sempre implementato nel core scritto in C# » mancanza di una propria interfaccia grafica » Qui si può disquisire » WPF è scripting? No, però XamlReader.Load()… » …e una maschera custom…. » …ma adesso no…di nuovo, il core è in C# » Release 2 di questo lavoro » richiamo di altri programmi per svolgere operazioni più sofisticate » Richiamare il core dell’applicazione www.xedotnet.org 21
  • 22. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 22
  • 23. Static(ally typed) Language » Un linguaggio in cui il controllo dei tipi avviene a compile time » Il tipo è associato alle variabili, non ai valori » Permettono di verificare e notificare (almeno in parte) parte degli errori sui tipi prima ancora di andare in esecuzione www.xedotnet.org 23
  • 24. Dynamic(ally typed) Language » Un linguaggio in cui il controllo dei tipi avviene a runtime » Il tipo è associato ai valori, non alle variabili » Non permettono di verificare e notificare gli errori di tipo se non quando vanno in esecuzione www.xedotnet.org 24
  • 25. Confronto Static Dynamic Languages Languages Robusto Semplice e stringato Interpretato Performante (no compilazione) Strumenti “implicitamente “intelligenti” tipizzato” Migliore scalabilità Meta-programming
  • 26. Le peculiarità di un Dynamic Language » Semplice e stringato • È una scelta tipica di chi ha sviluppato questi linguaggi • Sintassi leggera • Molte funzioni lasciate in API in linguaggi statici sono implementate nel linguaggio » Interpretato • È la diretta conseguenza della semplicità, evitando la “complicazione” di un processo di compilazione • Il senso è generale, senza pensare ad un IDE » Implicitamente tipizzato
  • 27. Metaprogramming » Il metaprogramming è la scrittura di un programma in grado di scrivere o manipolare altri programmi o se stesso » Un metaprogramma effettua a tempo di esecuzioni operazioni che sarebbero, in condizioni normali, effettuate a tempo di compilazione » L'obiettivo del metaprogramming è quello di produrre programmi in grado di adattarsi dinamicamente ad una configurazione che cambia nel tempo, senza intervento umano www.xedotnet.org 27
  • 28. Alune definizioni » Metaprogramma: il prodotto dell'atto di metaprogramming » Metalinguaggio: linguaggio utilizzato per scrivere il metaprogramma » Linguaggio oggetto: il linguaggio del programma manipolato » Se il metalinguaggio ed il linguaggio di programmazione coincidono, l'attività di metaprogramming prende il nome di reflection www.xedotnet.org 28
  • 29. Quale scegliere? » Due “generazioni” di linguaggi • Nativi (con virtual machine proprietaria) • Su Runtime (.NET o JVM) » Alcuni • Python (IronPython, Jython) • Ruby (IronRuby, JRuby) » Perché portare Python o Ruby su .NET o JVM? • Py o Rb usano il runtime • Py o Rb sono accessibli dal runtime (e questo è il nostro caso) www.xedotnet.org 29
  • 30. Dynamic Interoperability Different heaps CLR’s GC heap py1 Common Language py1 c2 Runtime c2 Python C-Based Objects Objects .NET Objects
  • 31. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 31
  • 32. Cos’è Python? » Un linguaggio di programmazione general purpose » Sviluppato da Guido van Rossum nel 1991 » Un linguaggio dinamico usato spesso come linguaggio di scripting » Supporta diversi paradigmi di programmazione: • Object Oriented • Imperative • Functional » Its design philosophy emphasizes: • Leggibilità del codice • Sintassi minimalista • Una estesa set di librerie • Duck Typing
  • 33. IronPython » È l’implementazione del linguaggio Python • IronPython è scritto interamente in C# » Creato da Jim Hugunin • sviluppatore anche di Jython (Python su JVM) • Voleva scrivere un paper dal titolo “Why .NET is a Terrible Platform for Dynamic Languages” • Invece nel settembre del 2004 iniziava a lavorare in Microsoft • http://conferences.oreillynet.com/presentations/os2004/ hugunin_jim_up.ppt www.xedotnet.org 33
  • 34. Performances Test Descrizione Prestazione parser (b0) heavy OO plus meta programming x1.1 faster stacks (b1) handling of stack overflow x2.1 faster PI (b2) using generators to compute π same sorting (b3) many different comparsions and sorting x1.5 faster parser2 (b4) reprise of parser with different input x1.2 slower builtins (b5) testing unicode, complex numbers, … x2.3 slower iterators (b6) – looping and overflow from int to long x1.2 faster Python-2.3 OSCon 2004 – IronPython 0.6 1.7x faster than Python-2.3 on IronPython pystone IronPython (Mono) 0 1 2 3 4 5 6 7 8 9 10 11 12 time (seconds) b0 b1 b2 b3 b4 b5 b6 www.xedotnet.org 34
  • 35. Versioni di IronPython IronPython IronPython IronPython IronPython 1.0 1.1 2.0 3.0 • Sept. 2006 • April 2007 • Early 2008 • Early 2009 • 2.4 language • 2.4 language • 2.5 language • 3.0 language? • 27/54 • Partial 2.5 • More modules • More modules builtinmodules support • Internal • More modules architecture • Top user issues work www.xedotnet.org 35
  • 36. Aggiornamento IronPython al 30 ottobre 2009 » http://ironpython.codeplex.com/ » .NET 3.5sp1 • IronPython 2.0.3 • 22 ottobre 2009 • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea seId=30416 • IronPython 2.6 RC2 • 27 ottobre 2009 • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea seId=34451 » .NET 4.0 Beta 2 • IronPython 2.6 CTP for .NET 4.0 Beta 2 • 21 ottobre 2009 • http://ironpython.codeplex.com/Release/ProjectReleases.aspx?Relea seId=28125 www.xedotnet.org 36
  • 37. Aggiornamento IronRuby al 30 ottobre 2009 » http://ironruby.codeplex.com/ » .NET 3.5sp1 • IronRuby 0.9.1 • 29 settembre 2009 • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI d=30916 • IronPython binaries for ironruby-0.9.1 interop • 29 settembre 2009 • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI d=30916#DownloadId=85530 » .NET 4.0 Beta 2 • IronRuby CTP for .NET 4.0 Beta 2 • 21 ottobre 2009 • http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseI d=33305 www.xedotnet.org 37
  • 38. Aggiornamento DLR al 30 ottobre 2009 » http://dlr.codeplex.com/ » .NET 3.5sp1 e .NET 4.0 Beta 2, solo src • 22 ottobre 2009 • http://dlr.codeplex.com/Release/ProjectReleases.as px?ReleaseId=34834 www.xedotnet.org 38
  • 39. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 39
  • 40. » “Why .NET is a Terrible Platform for Dynamic Languages” » IronPython “risolve” l’implementazione del Python su .NET • In realtà risolve anche problematiche valide per tutti i Dynamic Languages implementabili » IronPython 2.0 (specific) • On the top of DLR (generic) www.xedotnet.org 40
  • 41. Dynamic Languages on .NET IronPython IronRuby C# VB.NET Others… Dynamic Language Runtime Expression Trees Dynamic Dispatch Call Site Caching Object JavaScript Python Ruby COM binder binder binder binder binder
  • 42. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 42
  • 43. Alcuni esempi » IronPython (scripting) in applicazioni WPF • Customize LOB application » IronPython e l’interrogazione DB » Report in PDF • Un esempio di una libreria Python • Una delle tante www.xedotnet.org 43
  • 44. A commercial use of IronPython » Resolver Systems, ResolverOne a financial analytical tool that simulates a spread sheet
  • 45. Agenda » Introduzione » Cos’è un Dynamic Language » Python e IronPython » Dynamic Language Runtime » Alcuni esempi » Conclusioni www.xedotnet.org 45
  • 46. Conclusioni » Necessità dello scripting • Risolvere il problema delle personalizzazioni c/o il cliente » Risolto? • No, forse non si risolverà mai • Però è un altro passo avanti » Credenza di fondo • Scelgo di usare ANCHE un altro linguaggio • “Polyglot programmer” • Accetto il “compromesso” del “dinamico” » Attingere ad un parco di implementazioni (tutte open source) eccezionale in maniera nativa • Ruby on Rails www.xedotnet.org 46
  • 47. Esempi Visti » “Static” scripting con C# » Esempy » Hosting DLR in una applicazione .NET • Expressions • Customize the lifetime di una LOB WPF window • Query con Entity Framework • Reports (con ReportLab) » Resolver One www.xedotnet.org 47
  • 48. Esempi Non Visti » Altre librerie Python » Ruby e Ruby on Rails » Gestalt • Python e Ruby per lo scripting in pagine HTML • Usa un componente Silverlight senza UI www.xedotnet.org 48
  • 49. Il team che lavora sul DLR e dintorni » Jim Hugunin (DLR) » Dave Fugate (IronPython) • Blog: http://blogs.msdn.com/hugunin/ • Blog: http://knowbody.livejournal.com/ » Dino Viehland (IronPython) • Twitter: http://twitter.com/davefugate • Blog: http://blogs.msdn.com/dinoviehland/ » Harry Pierson (Evangelist) • Twitter: http://twitter.com/DinoViehland • Blog: http://www.devhawk.net/ » Jimmy Schementi (Silverlight • Twitter: http://twitter.com/DevHawk integration) » Seo Sanghyeon (IronPython) • Blog: http://blog.jimmy.schementi.com/ • Blog: http://fepy.blogspot.com/ • Twitter: http://twitter.com/jschementi • Twitter: http://twitter.com/sanxiyn » John Lam (IronRuby) » Jim Deville (IronRuby) • Blog: http://www.iunknown.com/ • Blog: http://blog.jredville.com/ • Twitter: http://twitter.com/john_lam/ • Twitter: http://twitter.com/jredville » Curt Hagenlocher (IronPython) » Shri Borde (IronRuby) • Blog: http://blogs.msdn.com/curth/ • Blog: http://blogs.msdn.com/shrib/ » Tomas Matousek (IronRuby) • Blog: http://blog.tomasm.net/ www.xedotnet.org 49
  • 50. Autori » Michael Foord • Libro: http://www.manning.com/foord/ • Blog: http://www.voidspace.org.uk/python/weblog/index.shtml • Twitter: http://twitter.com/Voidspace » Ivar Porto Carrero • Libro: http://www.manning.com/carrero/ • Blog: http://flanders.co.nz/ • Twitter: http://twitter.com/casualjim www.xedotnet.org 50
  • 51. Link Marco Parenzan blog: http://blog.codeisvalue.com/ email: marco.parenzan@libero.it web: http://www.codeisvalue.com/ Skype: marco.parenzan Messenger marco.parenzan@live.it Twitter: marco_parenzan community: www.xedotnet.org www.xedotnet.org 51
  • 52. Agenda Virtual Meetings Venerdì 30/10 Dynamic Language Programming for the Statically Typed Language Programmer Speaker: Marco Parenzan Venerdì 20/11 Microsoft Velocity: overview, practical setup and usage Speaker: Andrea Colaci Dalle 21:00 alle 22:00 www.xedotnet.org 52
  • 53. Agenda Community Meetings Venerdì 25/9 - Pattern Track Speaker: Senatore e Servienti Venerdì 16/10 – Team Foundation Server Track Speaker: Barbieri e Vernole Venerdì 6/11 – Web Track Speaker: Boschin e Vernole Venerdì 12/12 – Data Track Speaker: Boschin e Dottor Dalle 19:00 alle 23:00 www.xedotnet.org 53
  • 54. Grazie Q&A blog: http://blog.codeisvalue.com/ email: marco.parenzan@libero.it web: http://www.codeisvalue.com/ Skype: marco.parenzan Messenger marco.parenzan@live.it Twitter: marco_parenzan www.xedotnet.org 54