Overblog
Suivre ce blog Administration + Créer mon blog

Présentation

  • : Romagny13 - Du .NET,du pur .NET
  • : Cycle de progression Faire (quelque chose qui marche) -> comprendre ce que l’on fait/comment cela marche -> pousser plus loin les notions
  • Contact

Recherche

Articles RÉCents

4 septembre 2007 2 04 /09 /septembre /2007 19:02
Partager cet article
Repost0
4 septembre 2007 2 04 /09 /septembre /2007 00:43
[ASP.NET] – Quelques astuces

1 Conserver la position dans la page une fois celle-ci rechargée
  

Il suffit d’ajouter l’attribut  MaintainScrollPositionOnPostback="true" dans la directive de la page
<%@ Page Language="C#" MasterPageFile="~/maquette.master" Trace="true" AutoEventWireup="true" CodeFile="MaintainScrollPositionOnPostbackDemo.aspx.cs" Inherits="MaintainScrollPositionOnPostbackDemo" Title="Untitled Page" MaintainScrollPositionOnPostback="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphContenu" Runat="Server">
</asp:Content>
 
2 Tracer une page ou le site entier
A -Trace : de la page
Il suffit d’ajouter l’attribut Trace (réglé à true) dans la directive de la page désirée
<%@ Page Language="C#" MasterPageFile="~/maquette.master" Trace="true" AutoEventWireup="true" CodeFile="MaintainScrollPositionOnPostbackDemo.aspx.cs" Inherits="MaintainScrollPositionOnPostbackDemo" Title="Untitled Page" MaintainScrollPositionOnPostback="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphContenu" Runat="Server">
</asp:Content>
 
B -Du site
Dans le fichier de configuration principal  web.config du site(à la racine du site
<system.web>
 <trace enabled="true" traceMode="SortByCategory" localOnly="true"/>
(d’autres attributs sont disponibles tells requestLimit )
Il suffit ensuite d’aller à la page trace.axd du site (ce qui donne une url du type http://www.monsite.com/trace.axd ) pour avoir les informations 

Note : on peut bien entendu ajouter ses propres traces(exemple : Trace.Write("ma trace");)
3 Custom DataBound control
 
Créer un control web personnalisé qui tire parti des datasources (AccessDataSource,SqlDataSource ,etc.) de ASP.NET 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
 
namespace ControlLibrary
{
    [ToolboxData("<{0}:SimpleDataBoundColumn runat=server></{0}:SimpleDataBoundColumn>")]
    public class SimpleDataBoundColumn : DataBoundControl
    {
        public string DataTextField
        {
            get
            {
                object o = ViewState["DataTextField"];
                return ((o == null) ? string.Empty : (string)o);
            }
            set
            {
                ViewState["DataTextField"] = value;
                if (Initialized)
                {
                    OnDataPropertyChanged();
                }
            }
        }
        protected override void PerformSelect()
        {
            // si DataSourceID du control n'est pas définie
            if (!IsBoundUsingDataSourceID)
                this.OnDataBinding(EventArgs.Empty);
 
            GetData().Select(CreateDataSourceSelectArguments(),this.OnDataSourceViewSelectCallback);
 
            RequiresDataBinding = false;
            MarkAsDataBound();
 
            // declenchement evenement databound
            OnDataBound(EventArgs.Empty);
        }
 
        private void OnDataSourceViewSelectCallback(IEnumerable retrievedData)
        {
            // DataSourceID du control est définie
            if (IsBoundUsingDataSourceID)
                OnDataBinding(EventArgs.Empty);
 
            PerformDataBinding(retrievedData);
        }
 
        protected override void PerformDataBinding(IEnumerable retrievedData)
        {
            base.PerformDataBinding(retrievedData);
            int index = 0;
 
            if (retrievedData != null)
            {
                Table table = new Table();
                table.BorderWidth = 1;
 
                foreach (object dataItem in retrievedData)
                {
                    TableRow row = new TableRow();
                   
                    if (DataTextField.Length > 0)
                    {
                        TableCell cell = new TableCell();
                        cell.Text = DataBinder.GetPropertyValue(dataItem, DataTextField, null);
                        row.Cells.Add(cell);
                    }
                    else
                    {
                        PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties(dataItem);
                       
                        // création du header
                        if (index == 0)
                        {
                            TableRow headerRow = new TableRow();
                            headerRow.BackColor = System.Drawing.Color.LightGray;
                            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)
                            {
                                TableCell cell = new TableCell();
                                cell.Text = propertyDescriptor.Name;
                                headerRow.Cells.Add(cell);
                            }
                            table.Rows.Add(headerRow);
                            index += 1;
                        }
                        
                        // création des lignes de données
                        if (propertyDescriptors.Count >= 1)
                        {
                            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)
                            {
                                if (propertyDescriptor.GetValue(dataItem) != null)
                                {
 
                                    TableCell cell = new TableCell();
                                    cell.Text = propertyDescriptor.GetValue(dataItem).ToString();
                                    row.Cells.Add(cell);
                                }
                            }
                        }
                    }
                    table.Rows.Add(row);
                }
                this.Controls.Add(table);
            }
        }
 
 
    }
}
 
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<%@ Register Assembly="ControlLibrary" Namespace="ControlLibrary" TagPrefix="cc1" %>
 
<!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>Page sans titre</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <cc1:SimpleDataBoundColumn ID="SimpleDataBoundColumn1" runat="server" DataSourceID="SqlDataSource1"
            DataTextField="" />
        &nbsp;
        <br />
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactDBConnectionString %>"
            SelectCommand="SELECT [ContactID], [ContactName], [ContactFirstName], [ContactAge], [ContactCategoryID] FROM [Contact]">
        </asp:SqlDataSource>
        &nbsp;<br />
        <br />
       
    </div>
    </form>
 


databound.JPG
http://msdn2.microsoft.com/fr-fr/library/ms366539(VS.80).aspx
Partager cet article
Repost0
3 septembre 2007 1 03 /09 /septembre /2007 22:41
Débugger son JavaScript avec  Microsoft Expression Web Designer

On peut débugger son JavaScript avec Visual Studio 2005 (ou 2008) mais cela peut être utile aussi  d’avoir la possibilité de debugger avec Web Designer
1 – au cours de l’installation ou en ajout (si Web Designer est déjà installé) 

webdesign1.JPG
2 – Dans Web Designer lancer Script Editor

3 – le débogage est désormais possible
Note : penser à décocher dans les propriétés d’internet explorer « désactiver le débogage des scripts (autres applications) » et « désactiver le débogage des scripts (internet explorer) »

webdesign3.JPG
Partager cet article
Repost0
1 septembre 2007 6 01 /09 /septembre /2007 22:54
[ASP.NET] - HtmlTextWriter 2 approches
 

Avec  HtmlTextWriter on peut :
-              soit avoir une approche "objet", en utilisant des méthodes (AddAttribute,RenderBeginTag,...) et des enum (HtmlTextWriterAttribute,HtmlTextWriterTag,...)
-              soit écrire précisément les élements(tag,attributs,...) un peu comme on le fait avec un XmlWriter
 
exemple:
 
   protected override void Render(HtmlTextWriter writer)
    {
        // 1 approche "objet"
        writer.AddAttribute(HtmlTextWriterAttribute.Style, "font-size:XX-Large");
        writer.RenderBeginTag(HtmlTextWriterTag.Span);
        HttpUtility.HtmlEncode(_text, writer);
        writer.RenderEndTag();
 
        // 2
        writer.WriteBeginTag("Span"); //<Span
        writer.WriteAttribute("style", "font-size:XX-Large");// Style="font-size:XX-Large"
        writer.Write(">"); // ou writer.Write(HtmlTextWriter.TagRightChar); 
        writer.WriteEncodedText(_text); // le texte
        writer.WriteEndTag("Span");// </Span>
    }
 
Partager cet article
Repost0
26 août 2007 7 26 /08 /août /2007 10:19
Partager cet article
Repost0
23 août 2007 4 23 /08 /août /2007 10:15

[WPF] - UIElement3D extensibility - 3D Video Carousel

exemple visual studio 2008 fourni

"Concepts you can see in practice with this sample include:

  • Creating interactive 3D controls as interactive containers on non-interactive 3D models (Hint - Leverage existing 3D Xaml with little effort)
  • Creating a Custom Visual3D container type
  • Use of StaticResources from Application.Resources to separate mesh details from overall structure
  • Databinding a mesh texture to consume a local DP exposed as a URI, via a data binding type converter
  • 3D Layout - Cylinder Layout Helper class
  • Playing Video as a material on 3D"
http://blogs.msdn.com/pantal/archive/2007/08/22/uielement3d-extensibility-dvd-keep-case-player-cylindrical-carousel-layout.aspx
Partager cet article
Repost0
22 août 2007 3 22 /08 /août /2007 09:48

Open XML - Création de fichiers XML ouverts Office et
Open XML et les schémas métier : un aperçu


1 - Création de fichiers XML ouverts Office
bien que les exemples de codes soient en VB.NET,ils sont plutot interessants  : visionneuse de package,exemples de documents(templates,..),generation de docx,generation de lettre
un article donc tres bien pour decouvrir Open XML (avec word)

http://msdn.microsoft.com/msdnmag/issues/07/02/officespace/default.aspx?loc=fr


2 - Open XML et les schémas métier : un aperçu

http://msdn2.microsoft.com/fr-fr/library/880C55B0-BEB3-48f1-A3D8-ED5BB63B5023.aspx

Partager cet article
Repost0
17 août 2007 5 17 /08 /août /2007 01:12
Quelques astuces
1 - operateur ternaire
// resultat = condition? valeur retour condition vraie : valeur retour condition fausse
            // ex: int
            int i=11;
            int nResult = (i > 10) ? i * 2 : i;
2 – System.Enum
   Priority priority = Priority.Normal;
            // exemple : retourne "Normal"
            string result = System.Enum.Format(typeof(Priority), priority, "D"); //G ou g renvoie le nom (ex:"Normal"),D ou d renvoie la valeur (ex "2")
            string name = System.Enum.GetName(typeof(Priority), priority);//retourne "Normal
            // retourne les noms dans un tableau de string
            string[] priorities = System.Enum.GetNames(typeof(Priority));
            bool isDefined = System.Enum.IsDefined(typeof(Priority),"High");// retourne true
            // ... voir les autres membres
        

public enum Priority
{
None = 0,
Low = 1,
Normal=2,
High = 3,
NotRemovable = 4
}

3 – Délégués
Appeler plusieurs methods avec un délégué
Récuypèrer la liste des méthodes à appeler grace à System.Delegate
       private delegate void doActionEventHandler();
        private doActionEventHandler doAction;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //doAction +=new doActionEventHandler(DoFirstAction);
            //doAction +=new doActionEventHandler(DoSecondAction);
            // OU (inference de type)
            doAction += DoFirstAction;
            doAction += DoSecondAction;
 
 
            System.Delegate[] delegatesOfDoAction = doAction.GetInvocationList();
 
          // appeler un delegue de maniere asynchrone , attention le delegue ne doit avoir qu'une seule cible dans ce cas
            doAction.BeginInvoke(null, null);
        }
 
        public void DoFirstAction()
        { }
        public void DoSecondAction()
        { }
Partager cet article
Repost0
17 août 2007 5 17 /08 /août /2007 00:13
[ Caching ] - Une classe d’expiration basée sur Sql Dependency pour SQL Server
 
Je me développe ma propre librairie de Caching(celle-ci devra permettre plusieurs types d’expirations :
-          Absolue : le cacheItem devra être supprimé à la date fixée
-          Relative (sliding) : le cacheItem ajouté au cache devra être supprimé dans un temps déterminé
-          Pour SQL Server : je me base sur SqlDependency(pour applications de bureaux),pour le web il faudra que je vois si j’utilise SqlCacheDependency
-          Pour Access : ce sera juste FileSystemWatcher qui « observera » le fichier de base de données *.mdb (ou *.accdb)
Je présente ici ma classe d’expiration basée sur SqlDependency
Cette classe devrait même être utilisable avec Enterprise Library vu que je me base sur les patterns and practices (donc il faudra que je teste mais simplement en l’ajoutant dans les expirations du projet Caching)
public class SqlDependencyExpiration : ICacheItemExpiration
    {
        private bool isExpired;
 
        public SqlDependencyExpiration(SqlCommand command)
        {
            SqlDependency.Stop(command.Connection.ConnectionString);
            SqlDependency.Start(command.Connection.ConnectionString);
 
            command.Notification = null;
            SqlDependency sqlDependency = new SqlDependency(command);
            sqlDependency.OnChange += new OnChangeEventHandler(OnChanged);
 
            if (command.Connection.State == ConnectionState.Closed)
                command.Connection.Open();
 
            command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        void OnChanged(object sender, SqlNotificationEventArgs e)
        {
            SqlDependency sqlDependency = sender as SqlDependency;
            sqlDependency.OnChange -= OnChanged;
            isExpired = true;
        }
 
        #region ICacheItemExpiration Membres
 
        public bool HasExpired()
        {
            return isExpired;
        }
 
        #endregion
 
    }
 
Utilisation :
 private void button1_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
 
            if (manager.Get("1") != null)
            {
                dataTable =(DataTable) manager.Get("1").Value;
                label1.Text = "from cache";
            }
            else
            {
                SqlCommand sqlCommand = new SqlCommand("Select ContactID,Contactname from dbo.[Contact]", new SqlConnection("Data Source=.;Initial Catalog=ContactDB;Integrated Security=SSPI;"));
                sqlCommand.Connection.Open();
                dataTable.Load(sqlCommand.ExecuteReader());
                label1.Text = "from sql server";
               
                manager.Add("1", dataTable, new ICacheItemExpiration[] { new SqlDependencyExpiration(sqlCommand) });
 
            }
            dataGridView1.DataSource = dataTable;
}
 
 
C’est donc un début lorsque tout sera en place peut être que je présenterais plus en détails, sachant qu’à terme cette librairie devrait être ajoutée à un de mes projets > CS2GEN (disponible sur Codeplex et CodeS-SourceS)
Partager cet article
Repost0
16 août 2007 4 16 /08 /août /2007 11:07
System.Threading.Timer –
un timer pour la gestion des expirations d’un cache
 
Cette classe a pour objectif de permettre la gestion des expirations des éléments d’un cache(ces expirations peuvent etre de plusieurs types : absolues,relatives,notifications)
Très simple on utilise un timer,qui sera appelé périodiquement pour vérifier chaque cacheItem du cache n’a pas pas expiré
Logiquement une instance de cette classe devrait etre créée et le timer lancé en même temps que l’on instancie le cache manager
 public class PollTimer :IDisposable
    {
        private System.Threading.Timer timer;
 
        public void StartPolling(TimerCallback callbackMethod, int period)
        {
            if (callbackMethod == null)
                throw new ArgumentNullException("callbackMethod");
            if (period <= 0)
                throw new Exception("period");
 
            timer = new System.Threading.Timer(callbackMethod, null, 1000, period);
        }
 
         public void StopPolling()
        {
            if (timer == null)
                throw new InvalidOperationException("");
 
            Dispose();
        }
 
        #region IDisposable Membres
 
        public void Dispose()
        {
            timer.Dispose();
            timer = null;
        }
 
        #endregion
    }
 
Exemple(code de la form) :
Le timer sera appelé toutes les secondes et affichera un message
 
        PollTimer pollTimer = new PollTimer();
 
        private void button1_Click(object sender, EventArgs e)
        {
            pollTimer.StartPolling(Message, 1000);
        }
 
 
        public void Message(object obj)
        {
            MessageBox.Show("now");
        }
 
 
Partager cet article
Repost0