Affichage des articles dont le libellé est DOTNET. Afficher tous les articles
Affichage des articles dont le libellé est DOTNET. Afficher tous les articles

20/02/2010

60+ .NET libraries every developer should know about.

Voici un copie du post "60+ .NET libraries every developer should know about."
Je me suis permis la copie du blog ici, pour ne pas perdre le contenu.



Voici la copie du blog.

Yedda Twitter Library.
URL: http://devblog.yedda.com/index.php/twitter-c-library/

I’ve used this on a number of very simple twitter projects, where I’ve just needed to send an update. As the site says its more of a wrapper for the Twitter API than an actual library, but none the less its an easy way to integrate with the service via a drop in dll. Here’s how to use it.

1.Dim objYedda As New Yedda.Twitter
2.Dim status as String
3.Dim strTwitterUser as String = “username”
4.Dim strTwitterPassword as String = “password”
5.status = “Hello World”
6.objYedda.Update(strTwitterUser, strTwitterPassword, strStatus, Yedda.Twitter.OutputFormatType.RSS)
This small section of code will update your Twitter stream (provided you have a reference to the DLL), and your username and password correct.

FileHelpers Library
URL: http://filehelpers.sourceforge.net/

The FileHelpers library was created to stop developers from continuing to parse CSV. If you are doing any kind of importing and exporting within your application using the CSV format to get data in or out, look no further.

You can strong type your flat file simply by coding up a class that maps a data type to each record. This way data consistency, and import / export reliability can be tightened up on quite a bit. Writing out to a new file is also pretty easy once you’ve created your base classes defining the structure. Great little library for your toolkit.

First define the structure class…

1._
2.Public Class Product
3.Public ProductName As String
4.Public ProductCode As Integer
5.etc..
6.End Class
Add a reference to the FileHelper.dll, and read from the file , casting to a array of product objects.

1.Dim engine As New FileHelperEngine(GetType(Product))
2.Dim myProduct As Product() = DirectCast(engine.ReadFile(“product.txt”), Product())
Perform actions on the array of Products.

1.For Each pro As Product In myProduct)
2.Response.Write(pro.ProductName)
3.Next
Elmah
URL: http://code.google.com/p/elmah/

Elmah stands for error logging module and handlers. It is a completely pluggable in system for error handling within your .NET app. It catches bot thrown and unhandled exceptions across the scope of your app, logs them, and allows you to browse the full stack trace, all without exposing the error to the users of your application. That’s useful for a number of reasons. Firstly you aren’t getting the performance hit of using debug=true within your application (which by the way you should never be using in a production environment anyway) – and it means you can still get to the bottom of little blips as and if they happen. Coolio.

Elmah works as an HTTP module, so it takes little or no effort to deploy on any project. Just configure a few bits and bobs, and away it goes. All of the configuration is performed in the configuration file – just telling it whether you want your errors logged in a database, in memory or in a txt file is as simple as changing some web config parameters. You can even grab recent errors via RSS and get notified like that.

Log4Net
URL: http://logging.apache.org/log4net/

Following in the same vein as Elmah – Log4Net is a port of the well known logging framework for Java log4J. Whilst Elmah concentrates on exceptions that are thrown, Log4Net allows a much more granualar approach to program debugging.

With log4net it is possible to enable logging at runtime without modifying the original application binary and without incurring a high performance cost. Multiple “levels” of logging can be set within your program as well, and so you can determine quickly where “fatal” errors occur, and where “warnings” occur that can be ignored in the safe running of your application.

Log4Net enables all of these things whilst providing the same level of control over the logging format and location as Elmah. You can decide whether you’d like your debug message sent to a database, a text file, or indeed a TCP port. Different “Appenders” define where and how to send the messages, so if there’s somewhere else you’d like to see errors, you can easily write your own appender to perform this. Again, the appenders are defined in the web.config file.

1.Imports log4net
2.Imports log4net.Config
3.Private Shared log As log4net.ILog
4.Public Sub Page_Load(Byval s as Object, Byval e As EventArgs) Handles MyBase.Load
5.log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
6.BasicConfigurator.Configure()
7.log.Debug(“Debug Message”)
8.log.Warn(“Warning Message”)
9.log.Fatal(“Fatal Message”)
10.End Sub
Enterprise DT FTP Library
URL: http://www.enterprisedt.com/products/edtftpnet/overview.html

Enterprise DT is a great little FTP library, that performs all the needful without you getting your hands too dirty. It works with both web and offline applications, and again is a port of a Java library. I’ve used it for automating FTP tasks at the command line, sending photos between two sites automatically via FTP, and for sending feeds to google. It’s really easy to use, and saves you from having to write your own FTP operations. Fire it up, pass some usernames and passwords to it, and away we go. As below:

1.Dim ftp as FTPConnection = new FTPConnection()
2.ftpConnection.ServerAddress = “myserver”
3.ftpConnection.UserName = userName
4.ftpConnection.Password = password
5.ftpConnection.Connect()
6.ftpConnection.UploadFile(localFilePath, remoteFileName)
7.ftp.Close()
HtmlAgilityPack
URL: http://www.codeplex.com/htmlagilitypack

The Html Agility Pack is a library for parsing HTML. It is particularly useful if you are doing any kind of scraping work, with the main object of the software to transform real world HTML into structured and parseable DOM structure. It supports plain XPATH or XSLT syntax for traversing through HTML, making loops and extraction of text a breeze. Knowing these two technologies isn’t a pre-requisite to using it, but it sure as heck helps. You don’t have to setup the WebRequest or anything to grab remote files, which is handy – as you’ll see from the example.

1.Dim hw As New HtmlAgilityPack.HtmlWeb
2.Dim doc As HtmlAgilityPack.HtmlDocument
3.doc = hw.Load(“http://blog.webdistortion.com”)
4.For Each s As HtmlAgilityPack.HtmlNode In doc.DocumentNode.SelectNodes(“//a[@href]“)
5.Dim att As HtmlAgilityPack.HtmlAttribute = s.Attributes(“href”)
6.Response.Write(att.Value & vbCrLf)
7.Next
OpenAuth Library
URL: http://code.google.com/p/oauth-dot-net/

Open Auth is slowly becoming the norm, with web apps many preferring its usage over other less secure forms of authentication. This library is a .NET implementation of OpenAuth, and is mighty useful if you need to get up and running quickly. You are sure to run into a web service that needs you to auth via it. Google, Yahoo, Netflix and Twitter all support OpenAuth to interact with their service. The code needed for open auth is more extensive than some of the other bits and bobs, and has been better explained by others. Some of these links are worth a look.

•Shannon Whitley offers this example: Code | Live demo
•Daniel Crenna’s examples:
OAuth Specification

The OAuth Workflow

OAuth Walkthrough

Microsoft AntiXSS library
URL: http://bit.ly/toCrt

This is one of the security packs that MS have released to help .NET developers write better, more secure code. Essentially it is an encoding library designed to help protect ASP.NET web-based applications from XSS attacks, and works on the principals of inclusion (white-listing) to accept valid characters. I’ve used it successfully on a couple of projects, and some of the pre-written methods have been rigourously tested by leading security experts.

1.Microsoft.Security.Application.AntiXss.HtmlEncode(strNotrust)
2.Microsoft.Security.Application.AntiXss.JavaScriptEncode(strNotrust)
C5 Collections – Collections for .NET
URL: http://www.itu.dk/research/c5/

C5 provides functionality and data structures not provided by the standard .Net System.Collections.Generic namespace, such as persistent tree data structures, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes. Also, it is more comprehensive than collection class libraries on other similar platforms, such as Java. Unlike many other collection class libraries, C5 is designed with a strict policy of supporting “code to interface not implementation”. Definitely worth a look.

Honourable Mentions
Dependency Injection/Inversion of Control

•Unity Framework – Microsoft
•StructureMap – Jeremy Miller
•Castle Windsor
•NInject
•Spring Framework
•Autofac
•Managed Extensibility Framework
Logging

•Logging Application Block – Microsoft
•NLog
Compression

•SharpZipLib
•DotNetZip
•YUI Compressor (CSS and JS compression/minification)
Ajax

•Ajax Control Toolkit – Microsoft
•AJAXNet Pro
Data Mapper

•XmlDataMapper
•AutoMapper
ORM

•NHibernate
•Castle ActiveRecord
•Subsonic
•XmlDataMapper
Charting/Graphics

•Microsoft Chart Controls for ASP.NET 3.5 SP1
•Microsoft Chart Controls for Winforms
•ZedGraph Charting
•NPlot – Charting for ASP.NET and WinForms
PDF Creators/Generators

•PDFsharp
•iTextSharp
Unit Testing/Mocking

•NUnit
•Rhino Mocks
•Moq
•TypeMock.Net
•xUnit.net
•mbUnit
•Machine.Specifications
Automated Web Testing

•Selenium
•Watin
URL Rewriting

•url rewriter
•UrlRewriting.Net
•Url Rewriter and Reverse Proxy – Managed Fusion
Controls

•Krypton – Free winform controls
•Source Grid – A Grid control
•Devexpress – free controls
Unclassified

•CSLA Framework – Business Objects Framework
•AForge.net – AI, computer vision, genetic algorithms, machine learning
•Enterprise Library 4.1 – Logging, Exception Management, Validation, Policy Injection
•Quartz.NET – Enterprise Job Scheduler for .NET Platform
•MiscUtil – Utilities by Jon Skeet
•Lucene.net – Text indexing and searching
•Json.NET – Linq over JSON
•Flee – expression evaluator
•PostSharp – AOP
•IKVM – brings the extensive world of Java libraries to .NET.
•FlickrNET – Flickr library for .NET
•PowerCollections – Power Collections for .NET
•Facebook.net – Facebook API interface.
Related Posts
•Sending SMS Messages using 24x and VB.NET
•A decade in web design
•29 awesome websites to promote your web based applications
•ASP.NET News management script released.
•NHibernate. (Another Guide). For Visual Studio 2005.
•Essential Utilities and Programs you need when re-installing Windows.

16/02/2010

MapWindow version WPF

Je viens de contribuer au projet MapWindow un outil de cartographie en Dotnet. Une très bonne illustration du développement collaboratif avec Dotnet et en multi langage. Effectivement une partie des sources sont en VB.Net, une autre en C#, et enfin l'ActiveX de base MapWinGis est lui developpé en C++.
Ma petite contribution est une encapsulation de cette ActiveX pour pouvoir l'utiliser dans une application WPF.
Les codes sources sont disponibles sur le site
www.mapwindow.org. Ma contribution est disponible dans subversion : MW4Playground/MW4_WPF.

05/11/2009

C# supprimer les accents d'une chaine

La formule magique :
string text = "éàéö";
System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(text))

L'explication du code sur :
http://www.clt-services.com/blog/post/Enlever-les-accents-dans-une-chaine-(proprement).aspx

29/10/2009

Lire des données dans Excel avec ADO.NET

L'exemple de code ci dessous permet de lire les données d'une feuille (Feuil1) dans un fichier Excel (Classeur1.xls).
La feuille contient une première ligne avec nom, prenom,et age qui forme le titre des colonnes, Les lignes suivantes contiennent des données.

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\Classeur1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
            using (DbConnection connection = factory.CreateConnection())
            {
                connection.ConnectionString = connectionString;
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT nom,prenom,age FROM [Feuil1$]";
                    connection.Open();

                    lstPers = new List();
                    using (DbDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            double d = dr.GetDouble(dr.GetOrdinal("age"));
                            lstPers.Add(new Person(dr["nom"].ToString(), dr["prenom"].ToString(), (Int32)d ));
                        }
                    }
                }
            }

16/09/2009

Diagramme de classe WPF et .Net Framework 3.5

Voici deux urls pour trouver les diagrammes de classes du Microsoft .Net Framework 3.5 et de WPF.

26/05/2009

Wiki-OS : Un nouveau concept, l'OS Wiki

L'idée est simple développer un OS en mode Wiki.
Le projet est vraiment sympa, il permet de développer des applications en Microsoft .NET 3, avec WPF, etc...
L'environnement de Wiki-OS vous permet donc de développer depuis un simple navigateur, bien sûr vous devez avoir un Microsoft .Net 3 sur votre poste.
C'est géniale, pas besoins d'installer Visual Studio sur votre poste.
Le lien : WIKI-OS

23/03/2009

Faire des histogrammes chart sous ASP.NET

Si vous avez besoins de faire des graphiques de type histogrammes, courbes, camberts, etc.
Vous avez la solution d'utiliser les services de base du charting control for ASP.NET 3.5 SP1. Mais cela implique que vous utilisez le framework 3.5 sur votre serveur.

Si comme moi vous n'avez pas le droit d'utiliser le framework 3.5, mais uniquement le 2.0 alors voici une solution plutôt sympa (bien documentée, avec des exemples) et en opensource. Il s'agit de zedGraph et couvre tout les graphiques 2D de base et reste trés simple à mettre en oeuvre. Voici un exemple.

10/03/2009

Sculture un générateur de code pour .Net OpenSource. MDA biensûr

Sculture est un générateur de code pour .Net OpenSource. Il est particulièrement bien adapté pour les applications basées sur les données. Il s'agit d'une extension de Visual Studio 2008 donc le GAX est nécessaire.
Il permet de générer du code pour DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows Forms, WPF, Silverlight, ASP.NET, ASP.NET MVC .
Voici le site : http://www.codeplex.com/Sculpture
Ici une petite vidéo de démo : http://www.dawliasoft.com/Sculpture/Beta2/Intro%2DPart1/

08/01/2009

Identification des versions du .Net Framework de 1.0 à 2.0

Voici un lien pour connaitre les versions existantes du Microsoft .Net Framework.
http://support.microsoft.com/kb/318785

En résumé :

  • .Net Framework 1.0
    1.0.3705.0 Version finale d'origine
    1.0.3705.209 .NET Framework Service Pack 1
    1.0.3705.288 .NET Framework Service Pack 2
    1.0.3705.6018 .NET Framework Service Pack 3
  • .Net Framework 1.1
    1.1.4322.573 Version finale d'origine
    1.1.4322.2032 .NET Framework Service Pack 1
    1.1.4322.2300 .NET Framework inclus avec Windows Server 2003 32 bits Service Pack 1
  • .Net Framework 2.0
    2.0.50727.42 Version finale d'origine

06/01/2009

Lucene.net framework indexation full text

Lucene.net est framework indexation full text qui correspond au portage 'brut' de Lucene en Java. C'est un framework donc pas d'application, mais des APIs pour faire de l'indexation et de la recherche full text.

La vesion actuelle est la 2.0.004.

13/10/2008

Pourquoi je n'utilise plus Acrobat Reader

Pour moi depuis longtemps maintenant, lorsque je pense PDF, je pense également Acrobat Reader.

Ah, Acrobat Reader, depuis longtemps aussi je peste devant la lenteur du chargement de l’application. Je ne parle pas du comportement étonnant de l’ActiveX dont les capacités de programmation sont aussi bonnes que les performances de chargement d’Acrobat Reader.
Eh, bien entre Acrobat et moi c’est fini. Si, si, il existe bien des solutions alternatives à ce produit.

En l’occurrence je suis passé à PDF-XChange Viewer http://www.docu-track.com/home/prod_user/PDF-XChange_Tools/pdfx_viewer ce produit est diffusé gratuitement par la société Tracker Software products http://www.docu-track.com/
Bien évidement, il est plus rapide au chargement de l’application. En termes de fonctionnalités il est également beaucoup plus riche. Comme par exemple la possibilité de faire des commentaires, ou d’écrire dans le fichier PDF, puis de sauvegarder vos modifications. Bien sur elles seront lisibles par un reader PDF autres.

Du côté de l’ActiveX c’est encore mieux. Toutes les fonctionnalités du produit sont disponibles, paramétrables, activables ou non. Bref il s’agit d’un vrai composant ActiveX (en revanche, il est payant : 1300 euro pour 25000 licences). Si vous avez besoins d’embarquer dans une application client riche un viewer de PDF dont vous maitrisés les fonctionnalités. Alors « The PDF-XChange Viewer SDK » est l’outil dont vous rêvez. http://www.docu-track.com/home/dev_tools/pdf/PDF-XChange_Viewer_SDK/



17/06/2008

Création d'un fichier PDF par API, grace à iTextSharp

iText# (iTextSharp) est le portage de la librairie open source iText écrite en Java en C#.
Cette librairie permet de générer des fichiers PDF par API.

Le site d’iTextSharp : http://sourceforge.net/projects/itextsharp/
Un tutorial en français : http://itext.ugent.be/articles/iTextSharp.doc
Le très bon site de tutorial et astuces (anglais) : http://itextdocs.lowagie.com/tutorial/
Il existe un livre, qui de faite est la bible :
http://www.amazon.com/dp/1932394796?tag=itisacatalofwebp&camp=14573&creative=327641&linkCode=as1&creativeASIN=1932394796&adid=1GSTB23N4QZGGGNKY5MD&

Un exemple simple de mise en œuvre.

using System;
using System.IO;
using iTextSharp ;
using iTextSharp.text ;
using iTextSharp.text.pdf ;

namespace TestiText
{
class Program
{
static void Main(string[] args)
{
Document pdfDoc = new Document();

try
{
PdfWriter.GetInstance (pdfDoc, new FileStream("fichier.pdf", FileMode.Create));
pdfDoc.Open();

int inblig=100;
int inbcol=5;
PdfPTable tableau = new PdfPTable(inbcol);
tableau.HeaderRows = 1; // La premiere ligne du tableau est egalement le titre

// Creation du titre
for (int icol = 0; icol < inbcol; icol++)
tableau.AddCell(String.Format("COL {0}", icol));

// Creation d'un tableau de 5 colonnes avec 100 lignes
// pour faire un test sur le titre lors d'un changement de page
for (int ilig = 0; ilig < inblig; ilig++)
for (int icol = 0; icol < inbcol; icol++)
tableau.AddCell(String.Format("CELL {0}.{1}",ilig,icol));

// Ajout du tableau dans le document
pdfDoc.Add(tableau);

// Ajout de paragraphe dans le document
for (int i = 0; i < 200; i++)
pdfDoc.Add(new Paragraph("Paragraphe N° "+i.ToString()));
}
catch (DocumentException de)
{
Console.WriteLine("error " + de.Message);
}
catch (System.IO.IOException ioe)
{
Console.WriteLine("error " + ioe.Message);
}

pdfDoc.Close();
}
}

}

Associer une extension de fichier à un exécutable

Cette article est une adaptation en C# de l'article (http://www.c2i.fr/code.aspx?IDCode=420) de Richard Clarck (http://www.c2i.fr/).

Comme le titre l'indique, le but est d'associer une extension de fichier à programme qui sera utilisé pour consulter/modifier les documents ayant cette extension. Il se compose principalement des méthodes suivantes :

  • RegisterShellExtension
  • UnRegisterShellExtension
  • CheckRegisterShellExtension
public const Int32 SHCNE_ASSOCCHANGED = 0x8000000;
public const Int32 SHCNF_IDLIST = 0x0;

[DllImport("shell32.dll")]
public static extern void SHChangeNotify(Int32 wEventId, UInt32 uFlags, UInt32 dwItem1, UInt32 dwItem2);

///
/// Enregistre l'extension de fichier XDF comme devant être ouvert par le programme ContractViewer
///

private static void RegisterShellExtension()
{
try
{
// Association entre l'extesion et le programme
RegistryKey oRegKey = Registry.ClassesRoot;
oRegKey = oRegKey.CreateSubKey(".xdf", RegistryKeyPermissionCheck.ReadWriteSubTree);
oRegKey.SetValue("", "ContractViewer Document");
oRegKey.Close();

// Extension du shell pour le programme ContractViewer
oRegKey = Registry.ClassesRoot;
RegistryKey oRegKeyOpenCommand;
oRegKeyOpenCommand = oRegKey.CreateSubKey(@"ContractViewer Document\shell\open\command", RegistryKeyPermissionCheck.ReadWriteSubTree);
oRegKeyOpenCommand.SetValue("", Application.ExecutablePath + " %1");
oRegKeyOpenCommand.Close();

// Association icone pour extension
RegistryKey oRegKeyDefaultIcon;
oRegKeyDefaultIcon = oRegKey.CreateSubKey(@"ContractViewer Document\DefaultIcon", RegistryKeyPermissionCheck.ReadWriteSubTree);
String sICO = Application.StartupPath + @"\app.ico";
oRegKeyDefaultIcon.SetValue("", sICO);
oRegKeyDefaultIcon.Close();

oRegKey.Close();

SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
catch
{
}
}

///
/// Supprime l'extension de fichier XDF comme devant être ouvert par le programme ContractViewer
///

private static void UnRegisterShellExtension()
{
if (CheckRegisterShellExtension() == false) return; // Rien à supprimer

RegistryKey oRegKey;
try
{
oRegKey = Registry.ClassesRoot;
oRegKey.DeleteSubKeyTree(".xdf");
oRegKey.Close();
}
catch
{
}

try
{
oRegKey = Registry.ClassesRoot;
oRegKey.DeleteSubKeyTree(@"ContractViewer Document");
oRegKey.Close();
}
catch
{
}

SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}

///
/// Verifie si la ShellExtension de ContractViewer est en place.
///

/// True si la shell extension de ContractViewer est en place
private static bool CheckRegisterShellExtension()
{
RegistryKey oRegKey = Registry.ClassesRoot;
oRegKey = oRegKey.OpenSubKey(".xdf",false);
if (oRegKey == null) return false;
oRegKey.Close();

oRegKey = Registry.ClassesRoot;
oRegKey = oRegKey.OpenSubKey("ContractViewer Document", false);
if (oRegKey == null) return false;
oRegKey.Close();

return true;
}

06/04/2008

MyGeneration un générateur de code OpenSource

MyGeneration est vraiment un super outil pour la génération de code. Si votre application est basée principalement sur son modèle de données, alors MyGeneration c'est pour vous.
Il vous permettra de générer du code à partir de template en VBScript, en itérant sur le modèle de données de votre base de données.
Vous pouvez trouver MyGeneration à l'url suivante ( http://www.mygenerationsoftware.com/portal/default.aspx)

Dans le cadre d'un projet de développement pour un client, j'ai implémenté des templates MyGeneration pour produire du code implémentent le pattern 'ActiveRecord'. Ces implémentations produisent du code C# pour Microsoft Entreprise Library V3 et pour les procédures stockées Oracle nécessaire à l’implémentation des méthodes CRUD des ActiveRecord
http://www.mygenerationsoftware.com/TemplateLibrary/Archive/?guid=7538c462-b796-467b-b454-aa4cd43c2a63

Le lien sur un ensemble de templates : http://www.mygenerationsoftware.com/templatelibrary/default.aspx

Le lien pour le telechargement de MyGeneration : http://www.download.com/sort/3150-10252_4-0-1-4.html??

Vous noterez que le site est développé en ASP.Net

09/03/2008

ObjectDataSource et champs caché

Lorsque l'on connecte une source de données ObjectDataSource avec une GridView, les champs cachés dans la grille sont passés à null dans la méthode Update.Hors ce n’est pas vraiment le cas d'emplois idéal.Par exemple avec une classe Contact composée des classiques informations d'un contact. Lorsque l'on affiche une grille pour cette objet a priori on ne va pas afficher toutes les donnés de la classe.Le problème c'est que l'appel fait par la GridView à la méthode Update de l'ObjectDataSource passe les valeurs des paramètres cachés de la grille à null.Du coup votre objet en modification ce fait supprimer des valeurs simplement parce qu’elles ne sont pas affichées !!!
Bon ça c'était pour le problème.

J'ai deux solutions au problème :

  • La solution est simple il faut utiliser des HiddenFields au lieu d'utiliser des BoundFields avec Visible ou Enable définit à false.
  • L'autre solution c'est de mettre tout les champs qui ne sont pas affichés dans le DataKeys de la GridView.De toutes façon lors de la mise à jour de l'objet, il connait de manière intresecte les champs qui son ses clés.

Je trouve tout de même que l'implémentation n'est pas propre, mais je n'ai rien trouvé d'autres.

Quelqu'un à une idée ?

18/01/2008

Exporter une liste génerique vers Excel depuis une page ASP.NET

Dans nos applications nous manipulons classiquement des ‘entités’ métiers dont on utilises les champs par des accessors (ou propriétés). Il est fréquent de devoir manipuler ces entités comme une collection d’entités, par exemple une liste de clients, ou une liste de communes.

L’exemple suivant illustre comment on peut utiliser la programmation par réflexion supporté par Dotnet pour écrire du code très générique.
Dans cet exemple j’ai une liste générique de ‘Commune’ que je souhaite exporter en ASCII dans un fichier Excel depuis une application ASP.NET.

La méthode ExportToASCII() met en place la logique nécessaire pour produire le fichier Excel à travers le pipe de réponse HTTP.

private void ExportToASCII()
{
List lst = GetAll();

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/ms-excel";
StringWriter stringWrite = Export(lst);
Response.Write(stringWrite.ToString());
Response.End();
}

La méthode Export() contient le cœur du problème à savoir introspecter la collection passée en paramètre pour produire le flux de données.

private StringWriter Export(Object objListGeneric)
{
StringWriter stringWrite = new StringWriter();
if (objListGeneric == null) return stringWrite;

Type typeListGeneric = objListGeneric.GetType();
if (typeListGeneric.IsGenericType == false) return stringWrite;

// recupere le type de l'objet generic (le parametre de la classe generic)
Type[] typeGen = typeListGeneric.GetGenericArguments();
Type theTypeGen = typeGen[0];

// ecriture header (le nom des properties de l'objet)
foreach (PropertyInfo pi in theTypeGen.GetProperties())
{
stringWrite.Write(pi.Name.ToString());
stringWrite.Write('\t');
}
stringWrite.Write('\n');

// ecriture des lignes de données
foreach (object item in (IEnumerable)obj)
{
foreach (PropertyInfo pi in theTypeGen.GetProperties())
{
object objValue = pi.GetValue(item, null);
stringWrite.Write(objValue.ToString());
stringWrite.Write('\t');
}
stringWrite.Write('\n');
}

return stringWrite;
}