Calendrier

Janvier 2010
L M M J V S D
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
             
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

ASP.NET - AJAX


Microsoft and Web 2.0 Resources (Kirk Allen Evan's Blog) 

http://blogs.msdn.com/kaevans/archive/2008/05/28/microsoft-and-web-2-0-resources.aspx
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

WEB SERVICE SOFTWARE FACTORY - DE L’INSTALLATION AU TEST DE SON PREMIER PROJET
Article + sources sur CodeS-SourceS

Bonsoir,

je viens de poster un tutotrial (qui est d'ailleurs plus un memento pour se rappeler l'ordre et les opérations chronoliquement que l'on doit réaliser avec Web Software Sevice Factory

il est disponible sur CodeS-SourceS ici
 

j'ai également poster une source exemple trés simple ici 

vous pouvez télécharger le document Word ici

  

pour rappel les étapes importantes sont (même quelques nuances sont possibles) :

Chronologie
1 – Ajout d’une nouvelle connexion (projet Host)
2 – Création des entités métiers (projet BusinessEntities)
3 – Création classes data repository (projet DataAccess)
4 – projet BusinessLogic – définition d’une classe « façade » Repositories
5 – définition d’un DataContract (projet DataContracts)
6 - Création des messages : Request ,Response (projet ServiceContracts)
7 - Création de l’interface de service du contrat (projet ServiceContracts)
8 – Implémentation de l’interface de service (projet ServiceImplementation)
9 - Remplir le corps de la méthode
10 – Exposer le service (projet Host)
11 – Ajouter une référence au service web (projet test)

++

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

"How to generate dynamic images for your web application" - blog de Calvin Hsia

http://blogs.msdn.com/calvin_hsia/archive/2007/09/11/4868515.aspx

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET]  - Créer des controls web ou Html dynamiquement

Default.aspx :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<%@ Register Src="MyWebUserControl.ascx" TagName="MyWebUserControl" TagPrefix="uc1" %>
 
<!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">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>
 
1 – Controls web
    protected void Page_Load(object sender, EventArgs e)
    {
 
        // 1 - System.Web.UI.WebControls
        ListBox listBox = new ListBox();
        listBox.Items.Add("item 1");
        listBox.Items.Add("item 2");
        // j'applique un evenement
        listBox.AutoPostBack = true;
        listBox.SelectedIndexChanged += new EventHandler(listBox_SelectedIndexChanged);
        form1.Controls.Add(listBox);
 
        Button button = new Button();
        button.Text = "OK";
        button.Click += new EventHandler(button_Click);
        form1.Controls.Add(button);
    }
 
    void button_Click(object sender, EventArgs e)
    {
        Label1.Text = "click on button";
    }
 
    void listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = (sender as ListBox).SelectedValue;
    }
 
2 –controls HTML
    protected void Page_Load(object sender, EventArgs e)
    {
        // 2 - System.Web.UI.HtmlControls
        HtmlTable table = new HtmlTable();
        HtmlTableRow row = new HtmlTableRow();
        HtmlTableCell cell1 = new HtmlTableCell();
        cell1.Controls.Add(listBox);
        HtmlTableCell cell2 = new HtmlTableCell();
        cell2.Controls.Add(button);
        row.Cells.Add(cell1);
        row.Cells.Add(cell2);
        table.Rows.Add(row);
 
        form1.Controls.Add(table);
       
    }
 
 
3 – Charger un control utilisateur web dynamiquement
J’ai un control utilisateur web MyWebUserControl que je vais ajouter dynamiquement à la page
protected void Page_Load(object sender, EventArgs e)
    {
 
        Control myWebUserControl1 = this.LoadControl("MyWebUserControl.ascx");
        form1.Controls.Add(myWebUserControl1);
 
    }

webcontrol.JPG
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET] Maitriser le HtmlTextWriter

Je réfléchis à implémenter une libraire de gestion des feuilles styles CSS  un peu sur le même principe
          // 1 stringWriter va recevoir le texte généré par le htmlTextWriter
            System.IO.TextWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
 
            htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Html);
            htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Body);
 
 
            // A <a href="http://www.microsoft.com/" style="color:red;">Hello Micorsoft !!</a>
            //
            // 2 ajouter d'un attribut ceux ci doivent etre ajoutés avant la création de la balise d'ouverture
            htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.microsoft.com/");
 
            // 3 attribut style (il suffit d'ajouter les propriétés de l'attrbut style
            // car celui-ci sera généré automatiquemet ainsi que les ";" séparateurs
            htmlTextWriter.AddStyleAttribute(HtmlTextWriterStyle.Color, "red");
            htmlTextWriter.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, "Courier New");
 
            // création du tag d'ouverture (utilisation enum HtmlTextWriterTag)
            htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.A);
            // ecriture de la valeur texte entre les balises
            htmlTextWriter.WriteEncodedText("Hello Micorsoft !!");
            // fermeture de la balise
            htmlTextWriter.RenderEndTag();
 
 
            // <img src="/myImage.jpg" />
            //
            // B création d'un tag fermé
            htmlTextWriter.WriteBeginTag("img");
            htmlTextWriter.WriteAttribute("src", "myImage.gif");
            htmlTextWriter.Write(HtmlTextWriter.SelfClosingTagEnd);
 
            htmlTextWriter.RenderEndTag();
            htmlTextWriter.RenderEndTag();
 
            // j'affiche dans une richtextbox et dans un webbrowser le résultat
            rtbStyleSheet.Text = stringWriter.ToString();
            wbStyleSheet.DocumentText = stringWriter.ToString();

Le HTML généré
<html>
      <body>
            <a href="http://www.microsoft.com/" style="color:red;font-family:Courier New;">Hello Micorsoft !!</a><img src="myImage.gif" />
      </body>
</html>


en parlant feuilles de styles Web Designer dispose d'un excellent outil pour visualiser un aperçu , je connaissais Top styles et les outils Adobe mais la je suis bluffé 

styleswebdesigner.JPG
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[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
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
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
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[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>
    }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET 2.0] –
ObjectDataSource et Caching
 
après avoir activé la notification des tables grâce à l’utilitaire aspnet_regsql.exe
objectDataSource + Web.config
<form id="form1" runat="server">
    <div>
        <br />
        <asp:ObjectDataSource
                    ID="ObjectDataSource1"
                    runat="server"
                    OnSelecting="ObjectDataSource1_Selecting"
                    SelectMethod="GetContacts"
                    TypeName="ContactCaching.BLL.ContactCtrl"
                    EnableCaching="True"
                    SqlCacheDependency="ContactDB:Contact">
            </asp:ObjectDataSource>
 
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
            <Columns>
                <asp:BoundField DataField="ContactID" HeaderText="ContactID" SortExpression="ContactID" />
                <asp:BoundField DataField="Contactname" HeaderText="Contactname" SortExpression="Contactname" />
                <asp:BoundField DataField="ContactAge" HeaderText="ContactAge" SortExpression="ContactAge" />
                <asp:BoundField DataField="ContactCategoryID" HeaderText="ContactCategoryID" SortExpression="ContactCategoryID" />
            </Columns>
        </asp:GridView>
    </form>
 
-          EnableCaching : caching pris en charge sur True
-          SqlCacheDependency = « nombase :nomtable »
Si plusieurs tables séparer chaque couple db/table par un point virgule
 ex : SqlCacheDependency= “ContactDB :Contact ;ContactDB :ContactCategory »
Web.config
<?xml version="1.0"?>
<configuration>
      <appSettings/>
      <connectionStrings>
            <add name="connectionString1" connectionString="Data Source=.;Initial Catalog=ContactDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
      <system.web>
            <caching>
                <sqlCacheDependency enabled="true" pollTime="1000">
                     <databases>
                          <add name="ContactDB" connectionStringName="connectionString1"/>
                     </databases>
                </sqlCacheDependency>
          </caching>
            <compilation debug="true"/>
            <authentication mode="Windows"/>
      </system.web>
</configuration>
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET Futures] –Dynamic Data Web Site 
Créer tout un site communiquant avec une base de données en quelques clics

Pré requis
Disposer de Asp.Net futures
 
Démarche :
1 - créer un nouveau site > Dynamic Data Website
dynamicdatawebsite1.JPG
2 - ajout connectionstring (dans Web.config)
 
      <connectionStrings>
            <add name="connectionString1" connectionString="Data Source=.;Initial Catalog=ContactDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
      <dynamicDataControls showAllTables="false" connectionString="connectionString1">
            <nameMap>
                  <!--
            By default, Dynamic Data Controls use the name of the table as the folder name. This
            can be overridden by using a mapping here.
            Sample mappings:
            <add table="tasks" pathPrefix="~/MyTasksFolder" />
            -->
            </nameMap>
      </dynamicDataControls>
 
J’utilise ici une base SQL Server 2005 trés simple ayant deux tables

dynamicdatawebsite2-copie-1.jpg
3 - Ajout pages Dynamic Data Web Form
il faut absolument que les pages aient le nom exact de la table de la base de données visée :
exemple ici je vais donc créer une page "Contact.aspx" et une page "ContactCategory.aspx"
  dynamicdatawebsite3.JPG
4 - tester ! le code des pages est généré automatiquement !!
on peut consulter,ajouter,modifier,supprimer et filtrer
- un GridView permettant édition et suppression
- des dropdowlists pour filtrer sur chaque relation de la table
- un control pour l'ajout 
Une unique balise est ajoutée dans chaque page
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DynamicAutoData id="AutoData1" runat="server" />
    </div>
    </form>
</body>
 
  dynamicdatawebsite4.JPG  
On dispose également d'un onglet dédié à Dynamic Data dans la boite à outils
dynamicdatawebsite5.jpg  
Court descriptif de ses éléments
 <form id="form1" runat="server">
    <div>
        <!-- DynamicAutoData génére tous les controls (GridView,DropDownLists,... pour la table de la page) -->
        <asp:DynamicAutoData id="AutoData1" runat="server" />
        <!-- DynamicList ne génére qu'un GridView (avec toujours edition,suppression de lignes)-->
        <asp:DynamicList ID="DynamicList1" runat="server" />
        <!-- DynamicInsert permet uniquement insertion de nouveaux enregistrements dans la table de la page-->
        <asp:DynamicInsert ID="DynamicInsert1" runat="server" />
        <!-- DynamicDetails permet édition ,affiche le detail d'un enregistrement -->
        <asp:DynamicDetails ID="DynamicDetails1" runat="server" />
          <!-- DynamicFilter : on indique la clé étrangère automatiquement les valeurs à afficher vont etre cherchées dans la table mère -->
        <asp:DynamicFilter ID="DynamicFilter1" runat="server" ColumnName="ContactCategoryID" />
        <!-- DynamicNavigator est un menu permettant la navigation dans les pages du "site" -->
        <asp:DynamicNavigator ID="DynamicNavigator1" runat="server" />
        <!-- DynamicRssLink ajoute un lien rss à la page -->
        <asp:DynamicRssLink ID="DynamicRssLink1" runat="server" />
    </div >      
    </form>
 
Florent Santin(Azra) parle de Dynamic Data sur son blog
Il a apparemment même fait un webcast (qu’il faudra que je suive :p)
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET] les custom controls

Avant d’aborder les custom controls
une notion qui est bien à avoir assimiler c’est qu’une page aspx affichée dans le navigateur du client n’affiche que du html et du javascript, toutes les balises <asp :> sont « traduites » par le serveur asp.net
… une simple ouverture de la source de la page affichée dans le navigateur permet de le constater
 Les custom controls sont un peu l'équivalent des components(composants) en Windows Forms
1 – créer le site web
2 – ajouter un nouveau projet de type « bibliotheque de controls web »
custom1.JPG
C’est dans ce projet que l’on pourra ajouter des custom controls (ou controls web personnalisés)
Ici je vais créer un custom control DropDownList
C’est la que ce que j’ai expliqué au début est important dans la methode RenderContents je vais renvoyer le Html à insérer comme ici c’est un control de type liste je fais une boucle sur les items,
Si le custom control avait dérivé par exemple une textbox c’est la propriété text qu’il aurait fallu retourner ,etc.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebControlLibrary1
{
    [DefaultProperty("Items")]
    [ToolboxData("<{0}:CustomDropDownList runat=server></{0}:CustomDropDownList>")]
    public class CustomDropDownList : DropDownList
    {
        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(BuildHtml());
        }
 
        public String BuildHtml()
        {
            string result = string.Empty;
            bool selected = true;
            foreach (ListItem item in this.Items)
                if (selected)
                {
                    result += "<option selected="selected" value="" + item.Value + "">" + item.Text + "</option>";
                    selected = false;
                }
                else
                    result += "<option value="" + item.Value + "">" + item.Text + "</option>";
 
            return result;
        }
    }
}
 
3 – Ajouter une référence au site web pointant sur le projet contenant le custom control … générer le site web
Le custom control est désormais disponible dans la boite à outils il suffit donc de le glisser sur la page aspx désirée
Le code du control est de la forme :
<cc1:CustomDropDownList ID="CustomDropDownList1" runat="server"></cc1:CustomDropDownList>
 
Il suffit ensuite d’ajouter des éléments au custom control comme on le ferait avec une dropdownlist classique
  custom2.JPG
Voila un exemple de source de la page générée , on voit bien que la DropDownList est convertie en « select » html
<!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><title>
                Test customDropDownList
</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTMyNDcyODMzOA9kFgICAw9kFgQCAQ8PFgIeBFRleHQFEzAxLzA4LzIwMDcgMjA6Mjc6NDJkZAIHDxBkDxYCZgIBFgIQBQdwcmVtaWVyBQdwcmVtaWVyZxAFBnNlY29uZAUGc2Vjb25kZxYBZmRkRjfX3GI5C/+nuCitxM8iYw/QSYw=" />
</div>
 
    <div>
        <span id="Label1">01/08/2007 20:27:42</span>
        <input name="TextBox1" type="text" value="second" id="TextBox1" />
        <input type="submit" name="Button1" value="Button" id="Button1" />&nbsp;
        <select name="CustomDropDownList1" id="CustomDropDownList1">
                <option selected="selected" value="premier">premier</option><option value="second">second</option>
</select>
    </div>
   
<div>
 
                <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKeqdrbDwLs0bLrBgKM54rGBid26Ir5YurgmN0Kn2uAx5BkSjfz" />
</div></form>
</body>
</html>
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET] LinqDataSource
Je dois avouer que si je ne suis pas trop encore convaincu par Linq To SQL pour une utilisation avec une « grosse » application de bureau, pour les applications Web il me semble particulièrement bien adapté
Préparation
1 – Ajouter un fichier Linq To SQL au site web
2 – bizarrement avec la beta 2 de VS2008 on n’a plus le constructeur par défaut dans le DataContext
 
Donc j’ajoute un constructeur par défaut (si on ne veut pas se prendre une exception) qui va aller lire la connectionString dans le fichier de configuration Web.config
public ContactDataContext() :
        base((WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection).ConnectionStrings["ContactDBConnectionString"].ConnectionString)
    {
        OnCreated(); 
    }
 
I dans le code de la page ASP.NET

LinqDataSource1-copie-1.JPG

LinqDataSource2-copie-1.JPG
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ContactWithSQLDataSource.aspx.cs" Inherits="ContactWithSQLS" %>
 
<!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>Demo LinqDataSource</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:LinqDataSource
            ID="LinqDataSource1"
            runat="server"
            ContextTypeName="ContactDataContext"
            EnableDelete="True"
            EnableInsert="True"
            EnableUpdate="True"
            TableName="Contacts">
        </asp:LinqDataSource>
        <asp:GridView
                ID="GridView1"
                runat="server"
                AutoGenerateColumns="False"
                DataKeyNames="ContactID"
                DataSourceID="LinqDataSource1" AllowPaging="True" AllowSorting="True">
            <Columns>
                <asp:commandfield ShowDeleteButton="True" ShowEditButton="True">
                </asp:commandfield>
                <asp:boundfield DataField="ContactID" HeaderText="ContactID"
                    InsertVisible="False" ReadOnly="True" SortExpression="ContactID">
                </asp:boundfield>
                <asp:boundfield DataField="Contactname" HeaderText="Contactname"
                    SortExpression="Contactname"></asp:boundfield>
                <asp:boundfield DataField="ContactAge" HeaderText="ContactAge"
                    SortExpression="ContactAge"></asp:boundfield>
                <asp:boundfield DataField="ContactCategoryID" HeaderText="ContactCategoryID"
                    SortExpression="ContactCategoryID"></asp:boundfield>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
 
 
LinqDataSource3.JPG

II dans le code-behind de la page
Pour démonstration(car je pense que si c’est pour coder dans le code behind de la page mieux vaut carrément attaquer directement le DataContext sans passer par une LinqDataSource) on peut également définir une datasource en C# dans le code behind
(Attention toutefois si vous désirez permettre la modification dans le gridView il faudra gérer en plus les événements RowUpdating,RowDeleting et RowEditing)
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections;
 
public partial class _Default : System.Web.UI.Page
{
    LinqDataSource ContactDataSource = new LinqDataSource();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        ContactDataSource.ContextTypeName = "ContactDataContext";
        ContactDataSource.TableName = "Contacts";
        ContactDataSource.EnableInsert = true;
        ContactDataSource.EnableUpdate = true;
        ContactDataSource.EnableDelete = true;
 
        GridView1.DataSource = ContactDataSource;
        GridView1.DataBind();
    }
}
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ASP.NET 2.0] - Quelques utilisations du cache – chargement asynchrone avec SQL Server 2005
I - Mise en cache de la page :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Outputcache Duration="60" VaryByParam="none" %>
 
 
La page est mise en cache pour une minute ici
II - Mise en cache de données :
protected void Page_Load(object sender, EventArgs e)
    {
 
System.Data.OleDb.OleDbDataAdapter oOleDbDataAdapter = new                                      System.Data.OleDb.OleDbDataAdapter();
System.Data.DataTable oDataTable = new DataTable();
 
        try
        {
            if (Cache["ContactsKey"] == null)
            {
                oOleDbDataAdapter.SelectCommand = new System.Data.OleDb.OleDbCommand();
                oOleDbDataAdapter.SelectCommand.Connection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Documents and SettingsromagnyMes documentsAccessContactsDb.mdb;");
                oOleDbDataAdapter.SelectCommand.CommandType = CommandType.Text;
                oOleDbDataAdapter.SelectCommand.CommandText = "SELECT * FROM Contact";
 
                oOleDbDataAdapter.SelectCommand.Connection.Open();
                oOleDbDataAdapter.Fill(oDataTable);
                Cache["ContactsKey"] = oDataTable;
            }
 
            GridView1.DataSource = Cache["ContactsKey"];
            GridView1.DataBind();
        }
        catch (System.SystemException ex)
        {
            //
            lblMessage.Text = ex.Message;
        }
        finally
        {
            if (oOleDbDataAdapter != null)
                if (oOleDbDataAdapter.SelectCommand != null)
                    if (oOleDbDataAdapter.SelectCommand.Connection.State == ConnectionState.Open)
                        oOleDbDataAdapter.SelectCommand.Connection.Close();
        }
 
    }
 
III - Avec cachedependency
1 er exemple : avec un fichier ici je « branche sur la base de données Acces, si des changemeents interviennent alors le cache concerné sera vidé
protected void Page_Load(object sender, EventArgs e)
    {
 
        System.Data.OleDb.OleDbDataAdapter oOleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter();
        System.Data.DataTable oDataTable = new DataTable();
 
        try
        {
            if (Cache["ContactsKey"] == null)
            {
                oOleDbDataAdapter.SelectCommand = new System.Data.OleDb.OleDbCommand();
                oOleDbDataAdapter.SelectCommand.Connection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Documents and SettingsromagnyMes documentsAccessContactsDb.mdb;");
                oOleDbDataAdapter.SelectCommand.CommandType = CommandType.Text;
                oOleDbDataAdapter.SelectCommand.CommandText = "SELECT * FROM Contact";
 
                oOleDbDataAdapter.SelectCommand.Connection.Open();
                oOleDbDataAdapter.Fill(oDataTable);
                System.Web.Caching.CacheDependency oCacheDependency = new System.Web.Caching.CacheDependency(@"C:Documents and SettingsromagnyMes documentsAccessContactsDb.mdb");
 
                Cache.Insert("ContactsKey", oDataTable, oCacheDependency);
            }
 
            GridView1.DataSource = Cache["ContactsKey"];
            GridView1.DataBind();
        }
        catch (System.SystemException ex)
        {
            //
            lblMessage.Text = ex.Message;
        }
        finally
        {
            if (oOleDbDataAdapter != null)
                if (oOleDbDataAdapter.SelectCommand != null)
                    if (oOleDbDataAdapter.SelectCommand.Connection.State == ConnectionState.Open)
                        oOleDbDataAdapter.SelectCommand.Connection.Close();
        }
 
    }
 
2 eme exemple : avec SQL Server
A - Dans Web.config
<configuration>
      <appSettings/>
 <connectionStrings>
    <add name="ContactsDbConnectionString"
         connectionString="Data Source=.;Initial Catalog=ContactsDB;Integrated Security=SSPI;"
         providerName="System.Data.SqlClient"
         />
 </connectionStrings>
   
      <system.web>
    <caching>
      <sqlCacheDependency enabled="true">
        <databases>
          <add name="ContactsDbSqlConnection"
               connectionStringName="ContactsDbConnectionString"
               pollTime="500"
               />
        </databases>
      </sqlCacheDependency>
    </caching>
 
B – Attention il faut avoir activer la notification des tables grace à l’utilitaire aspnet_regsql.exe (C:/WINDOWS/Microsoft.NET/Frameworkv2.0.50727)
Ce qui donne quelque chose du style :
aspnet_regsql.exe –S DONJR –U sa –d ContactsDB -ed
Puis pour chaque table
aspnet_regsql.exe –S DONJR –U sa –d ContactsDB  -t Contact -et
-          DONJR > c’est le nom du serveur
-          sa > nom de l’utilisateur (ajouter le mot de passe avec –p)
-          ContactsDB > c’est la base de données
-          Contact > c’est le nom d’une des tables à activer
C - Code
protected void Page_Load(object sender, EventArgs e)
    {
 
System.Data.SqlClient.SqlDataAdapter oSqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
        System.Data.DataTable oDataTable = new DataTable();
 
        try
        {
            if (Cache["ContactsKeySql"] == null)
            {
                oSqlDataAdapter.SelectCommand = new System.Data.SqlClient.SqlCommand();
                oSqlDataAdapter.SelectCommand.Connection = new System.Data.SqlClient.SqlConnection(@"Data Source=.;Initial Catalog=ContactsDB;Integrated Security=SSPI;");
                oSqlDataAdapter.SelectCommand.CommandType = CommandType.Text;
                oSqlDataAdapter.SelectCommand.CommandText = "SELECT * FROM Contact";
 
                oSqlDataAdapter.SelectCommand.Connection.Open();
                oSqlDataAdapter.Fill(oDataTable);
 
                Cache.Insert("ContactsKeySql", oDataTable, new System.Web.Caching.SqlCacheDependency("ContactsDbSqlConnection", "Contact"));
            }
 
            GridView1.DataSource = Cache["ContactsKeySql"];
            GridView1.DataBind();
        }
        catch (System.SystemException ex)
        {
            //
            lblMessage.Text = ex.Message;
        }
        finally
        {
            if (oSqlDataAdapter != null)
                if (oSqlDataAdapter.SelectCommand != null)
                    if (oSqlDataAdapter.SelectCommand.Connection.State == ConnectionState.Open)
                        oSqlDataAdapter.SelectCommand.Connection.Close();
        }
}
 
IV - Chargement Asynchrone avec SQL Server
protected void Page_Load(object sender, EventArgs e)
    {
PageAsyncTask oPageAsyncTask = new PageAsyncTask(BeginInvokeMethod, EndInvokeMethod, EndTimeOutInvoke, null);
 
Page.RegisterAsyncTask(oPageAsyncTask);
    }
 
System.Data.SqlClient.SqlConnection oSqlConnection;
    System.Data.SqlClient.SqlCommand oSqlCommand;
 
    public IAsyncResult BeginInvokeMethod(object sender, EventArgs e, AsyncCallback callBack, object stateObject)
    {
        oSqlConnection = new System.Data.SqlClient.SqlConnection(@"async=true;Data Source=.;Initial Catalog=ContactsDB;Integrated Security=SSPI;");
        oSqlCommand = new System.Data.SqlClient.SqlCommand();
        oSqlCommand.Connection = oSqlConnection;
        oSqlCommand.CommandType = CommandType.Text;
        oSqlCommand.CommandText = "SELECT * FROM Contact";
 
        oSqlConnection.Open();
       return oSqlCommand.BeginExecuteReader(callBack, stateObject, CommandBehavior.CloseConnection);
    }
    public void EndInvokeMethod(IAsyncResult result)
    {
        System.Data.SqlClient.SqlDataReader oSqlDataReader = oSqlCommand.EndExecuteReader(result);
        if (oSqlDataReader != null)
        {
            GridView1.DataSource = oSqlDataReader;
            GridView1.DataBind();
        }
    }
    public void EndTimeOutInvoke(IAsyncResult result)
    {
        if (oSqlConnection != null)
            if (oSqlConnection.State == ConnectionState.Open)
                oSqlConnection.Close();
    }
 
Méthodes disponibles en asynchrone :
-          BeginExecuteNonQuery()
-          BeginExecuteReader()
-          BeginExecuteXmlReader()
+
-          EndExecuteNonQuery()
-          EndExecuteReader()
-          EndExecuteXmlReader()
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus