michelc Blog

Just <strong>another</strong> WordPress.com weblog

Archive for the ‘.net’ Category

VS2003 – Echec de l’actualisation du projet

leave a comment »

Après avoir fermé toutes les session de Visual Studio, Passer dans l’explorateur de fichier et aller dans le sous-répertoire :

  • – Documents and Settings
  • – – « userlogin » (login de l’utilisateur)
  • – – – VSWebCache
  • – – – – « hostname » (nom de la machine)

Et supprimer le cache du projet qui pose problème (ou éventuellement de tous les projets).

(Publié à l’origine sur http://www.bigbold.com/snippets/posts/show/1937)

Written by michel

19 avril 2006 at 9:52

Publié dans .net, Code Snippets

Un MapPath() plus souple

with 2 comments

La méthode MapPath() renvoie le chemin d’accès physique qui correspond à l’url qui lui est passé en argument.

Le problème est que Server.MapPath() n’accepte que les répertoires virtuels comme paramètre, qu’il s’agisse d’une url absolue (here/myfile.txt) ou relative (../yourdir/yourfile.txt) ou même d’une url commençant par un tilde (~/ourdir/ourfile.txt).

Mais elle provoque une erreur dès que son argument est une url complète (http://www.example.com/mydir/myfile.txt) ou correspond déjà à une adresse physique (D:\websites\example.com\mydir\myfile.txt).

Pour simplifier l’utilisation de la méthode MapPath() et éviter de tester ses arguments à chaque appel, ajout d’une méthode MapPath() améliorée à la classe Common.cs. :

///
/// Same as Server.MapPath but don't hang on physical path
///
public static string MapPath (string path) {
   string temp = path;
   try {
      temp = System.Web.HttpContext.Current.Server.MapPath(path);
   } catch (Exception ex) {
      try {
         System.Uri utemp = new System.Uri(path);
         if (utemp.IsFile == true) {
            temp = utemp.LocalPath;
         } else {
            temp = System.Web.HttpContext.Current.Server.MapPath(utemp.LocalPath);
         }
      } catch {
         throw ex;
      }
   }
   return (temp);
}

Màj du 19/03 : gère le cas où l’url passée en argument comprend des paramètres (here/myflash.swf?file=test.mp3).

public static string MapPath (string path) {
   string temp = path + "?";
   temp = temp.Split('?')[0];
   try {
      temp = Context.Server.MapPath(temp);
   } catch (Exception ex) {
      try {
         Uri utemp = new Uri(temp);
         if (utemp.IsFile == true) {
            temp = utemp.LocalPath;
         } else {
            temp = Context.Server.MapPath(utemp.LocalPath);
         }
      } catch {
         throw ex;
      }
   }
   return (temp);
}

Written by michel

14 mars 2006 at 7:51

Publié dans .net, QC

HTTP 301 – Moved Permanently

with one comment

<script runat="server">
private void Page_Load(object sender, System.EventArgs e) {
  Response.Status = "301 Moved Permanently";
  Response.AddHeader("Location", "http://www.new-url.com");
}
</script>

(Publié à l’origine sur http://www.bigbold.com/snippets/posts/show/1295)

Written by michel

24 janvier 2006 at 1:13

VistaDB 2.1 database for .NET has been released

leave a comment »

This 2.1 update includes over 60 improvements, including new support for .NET 2.0 and Visual Studio 2005 VistaDB is a small-footprint, embedded SQL database alternative to Jet/Access, MSDE and SQL Server Express 2005 that enables developers to build .NET 1.1 and .NET 2.0 applications. Features SQL-92 support, small 500KB embedded footprint, free 2-User VistaDB Server for remote TCP/IP data access, royalty free distribution for both embedded and server, Copy ‘n Go! deployment, managed ADO.NET Provider, data management and data migration tools. Free trial is available for download.

C’est pas vraiment sûr que ça marche parce que :

  1. c’est peut-être un peu tard pour s’y mettre,
  2. mon blogue n’est pas connu,
  3. j’écris en français.

Et pourtant,

  1. j’en ai quand même plus besoin que lui,
  2. ça me serait bien pratique pour mes tests.

Si ça marche et qu’on peut utiliser la version « embeded » avec ASP.NET (et chez eux) alors on peut espérer qu’une future version de Quick-Content soit compatible VistaDB 🙂

Written by michel

12 janvier 2006 at 6:32

Publié dans .net

Comment résoudre le problème du « double-clic » en asp.net

with one comment

Une méthode générique pour pallier au problème du « double-clic » quand un utilisateur double clique au lieu de simplement cliquer une fois pour valider un formulaire, ce qui risque de le soumettre 2 fois. Pour contourner ça, le bouton qui a été cliqué est caché une fois que l’utilisateur a cliqué dessus.

Pour que ça fonctionne avec tous les formulaires, la bidouille est appliqué au niveau de l’évènement Render de la page.

protected override void Render(HtmlTextWriter output) {
    // Get normal html ouput
    StringBuilder stringBuilder = new StringBuilder();
    StringWriter stringWriter = new StringWriter(stringBuilder);
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    base.Render(htmlWriter);
    string html = stringBuilder.ToString();
    // Enhance submit buttons
    string onclick1 = "\"if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();";
    string onclick2 = "\"this.style.display='none';";
    html = html.Replace("onclick=" + onclick1, "onclick=" + onclick2 + onclick1.Substring(1));
    // Render updated html
    output.Write(html);
}

(Publié à l’origine sur http://www.bigbold.com/snippets/posts/show/975)

Written by michel

14 décembre 2005 at 7:32

Publié dans .net, Code Snippets

Correction problème double click

leave a comment »

Certains utilisateurs cliquent plusieurs fois sur le bouton [OK] (à cause d’un problème de souris ou parce qu’ils ont l’habitude de double-cliquer pour valider). Lorsque l’on ne teste pas si les données saisies sont uniques (cas des messages d’un forum par exemple), cela conduit à créer deux enregistrements au lieu d’un.

Pour contourner ce problème, le bouton de validation est caché via l’évènement client « onclick ». Et pour éviter de mettre à jour les boutons de chaque formulaire, la modification est gérée de façon globale au niveau de l’évènement serveur « Render » de default.aspx.cs :

protected override void Render(HtmlTextWriter output) {
    // Get normal html ouput
    StringBuilder stringBuilder = new StringBuilder();
    StringWriter stringWriter = new StringWriter(stringBuilder);
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    base.Render(htmlWriter);
    string html = stringBuilder.ToString();
    // Enhance submit buttons
    string onclick1 = "\"if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();";
    string onclick2 = "\"this.style.display='none';";
    html = html.Replace("onclick=" + onclick1, "onclick=" + onclick2 + onclick1.Substring(1));
    // Render updated html
    output.Write(html);
}

Note: la modification de default.aspx.cs est suffisante étant donné qu’il s’agit de la seule « vrai » page de Quick-Content et que toutes les autres pages ne sont que de l’url rewriting.

Voir aussi : How to work around the « double-click » problem

Written by michel

14 décembre 2005 at 3:37

Publié dans .net, QC

Générer GoogleSearchService.dll à partir de GoogleSearch.wsdl

leave a comment »

Pour générer la source C#, taper :

wsdl GoogleSearch.wsdl

Cele crée un fichier GoogleSearchService.cs, à compiler par :

csc /target:library GoogleSearchService.cs

Ou pour Mono par :

mcs /target:library GoogleSearchService.cs

Ce qui produit l’assembly : GoogleSearchService.dll
(Publié à l’origine sur http://www.bigbold.com/snippets/posts/show/976)

Written by michel

14 décembre 2005 at 8:29

Publié dans .net, Code Snippets

Authentification SMTP

leave a comment »

Pour certains serveurs SMTP il est nécessaire de faire une connexion POP avant de pouvoir envoyer un mél (« POP before SMTP » Authentication). Apparement, cela inscrit l’adresse IP de la machine effectuant la connexion dans une table de façon à ensuite autoriser les connexions SMTP (au coup par coup, temporairement ou à vie ?).

Etant donné qu’il n’existe pas de classe System.Pop en ASP.NET 1.1, il reste à trouver une classe POP qui fasse l’affaire. Voir éventuellement l’article « How to POP3 in C# » de Randy Charles Morin.

Written by michel

30 novembre 2005 at 2:24

Publié dans .net, QC

Un formulaire simple pour tester l’envoi de mail

leave a comment »

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Mail" %>
<script runat="server">    
void btnSubmit_Click(Object sender, EventArgs e) {
  MailMessage mail = new MailMessage();
  mail.To = txtTo.Text;
  mail.From = txtFrom.Text;
  mail.Subject = txtSubject.Text;
  mail.Body = txtMessage.Text;
  mail.Priority = MailPriority.High;
  mail.BodyFormat = MailFormat.Text;
  SmtpMail.SmtpServer = txtSmtpServer.Text;
  if (txtSmtpUsername.Text.Trim() != "") {
    if (txtSmtpPassword.Text.Trim() != "") {
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", txtSmtpUsername.Text);
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", txtSmtpPassword.Text);
    }
  }
  try {
    SmtpMail.Send(mail);
    Response.Write("OK!");
  } catch (Exception ex) {
    Response.Write("KO: " + ex.ToString());
  }
}
</script>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Mail test</title>
  </head>
  <body>
    <form runat="server">
      <ul>
        <li>Smtp Server : <asp:TextBox id="txtSmtpServer" runat="server"></asp:TextBox></li>
        <li>Smtp Username : <asp:TextBox id="txtSmtpUsername" runat="server"></asp:TextBox></li>
        <li>Smtp Password : <asp:TextBox id="txtSmtpPassword" runat="server"></asp:TextBox></li>
        <li>From : <asp:TextBox id="txtFrom" runat="server"></asp:TextBox></li>
        <li>To : <asp:TextBox id="txtTo" runat="server"></asp:TextBox></li>
        <li>Subject : <asp:TextBox id="txtSubject" runat="server"></asp:TextBox></li>
        <li>Message : <asp:TextBox id="txtMessage" TextMode="MultiLine" runat="server"></asp:TextBox></li>
      </ul>
      <asp:Button runat="server" id="btnSubmit" OnClick="btnSubmit_Click" Text="Send"></asp:Button>
    </form>
  </body>
</html>

(Publié à l’origine sur http://www.bigbold.com/snippets/posts/show/906)

Written by michel

23 novembre 2005 at 4:30

Publié dans .net, Code Snippets