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

mercredi 11 mars 2015

MutliCheck DropDownList ASP.NET

Résultat : ASP.NET MultiCheckList DropDown

ASP.NET MultiCheckList DropDown
ASP.NET MultiCheckList DropDown

Download : MultiCheckDropDownList

mardi 10 mars 2015

Exemple AngularJS Asp.net WebForms

Dans cet article je vous présente un exemple de AngularJS en asp.net avec l'utilisation de WebService.

CRUD Application Sample Using AngularJS and Asp.net
Exemple Angular JS en Asp.net





Employe.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MajEmploye.aspx.cs" Inherits="GestEmployes.MajEmploye" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
   <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="Scripts/jquery-1.8.3.min.js"></script>
    <script src="script.js"></script>
    <style>
        body
        {
            background-color:cadetblue;
        }
    </style>
</head>
<body>
    <div ng-app="myApp">
      <div ng-controller="EmpCtrl">
        <div style="font-family: Verdana; font-size: 12px; margin-left: auto;margin-right:auto; width:700px; text-align:center">
            <table>
                <tr>
                    <td>
                          <table style="margin-left: auto;margin-right:auto;">
                            <tr>
                                <td style="text-align: right;">Id :
                                </td>
                                <td>
                                    <input type="text" id="txtEmpID" ng-model="EmpID" />
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right;">Nom :
                                </td>
                                <td>
                                    <input type="text" id="txtEmpNom" ng-model="EmpNom" />
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right;">Prénom :
                                </td>
                                <td>
                                    <input type="text" id="txtEmpPrenom" ng-model="EmpPrenom" />
                                </td>
                            </tr>
                             <tr>
                                <td style="text-align: center;">
                       
                                </td>
                                 <td> <input type="submit" id="btnSubmit" value="Enregistrer" ng-click="save()" /></td>
                            </tr>
                        </table>
                    </td>

                    <td>
                          <input type="button" id="btnListeEmployes" value="Liste des employés" ng-click="getEmployee()" />
                            Filtre : <input type="text" ng-model="search" />
                            <table border="1" style="font-family: Verdana; font-size: 12px; margin-left: auto;margin-right:auto; width:400px; margin-top:5px">
                                <tr style="background-color:olive;color:white">
                                    <td>ID
                                    </td>
                                    <td>Nom
                                    </td>
                                    <td>Prénom
                                    </td>
                               </tr>
                               <tr ng-repeat="e in items | filter:search"">
                                    <td>{{e.ID}}
                                    </td>
                                    <td>{{e.Nom}}
                                    </td>
                                    <td>{{e.Prenom}}
                                    </td>
                              </tr>
                            </table>
                    </td>
                </tr>

            </table>
       
    </div>
     </div>  

  </div>

</body>
</html>

EmpService.asmx


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Collections;
using System.Web.Script.Serialization;


namespace GestEmployes
{

    /// <summary>
    /// Summary description for EmpService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]

    public class EmpService : System.Web.Services.WebService
    {
        string connection = @"Data Source=ServerName;Initial Catalog=Employe;Integrated Security=SSPI;";

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string InsertEmploye(string empID, string nom, string prenom)
        {

            SqlConnection con = new SqlConnection(connection);
            SqlCommand cmd;
            try
            {
                con.Open();
                cmd = con.CreateCommand();
                cmd.CommandText = "INSERT INTO Employe(ID,Nom,Prenom) VALUES(@ID,@nom,@prenom)";
                cmd.Parameters.AddWithValue("@ID", empID);
                cmd.Parameters.AddWithValue("@nom", nom);
                cmd.Parameters.AddWithValue("@prenom", prenom);
                cmd.ExecuteNonQuery();
                return "Employé ajouté avec succés";
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<Employe> ListeEmployes()
        {
            SqlConnection con = new SqlConnection(connection);
            SqlCommand cmd;
            try
            {
                con.Open();
                cmd = con.CreateCommand();
                cmd.CommandText = "Select * from employe";
                SqlDataReader sdr=cmd.ExecuteReader();
                List<Employe> ListEmployes = new List<Employe>();
                Employe emp;
                while (sdr.Read())
                {
                    emp = new Employe();
                    emp.ID = Convert.ToInt32(sdr[0]);
                    emp.Nom = sdr[1].ToString();
                    emp.Prenom = sdr[2].ToString();
                    ListEmployes.Add(emp);
                }
                sdr.Close();
                return ListEmployes;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

            }
        }
    }
}

Employe.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GestEmployes
{
    public class Employe
    {
        public int ID;
        public string Nom;
        public string Prenom;
    }
}

script.js


var app = angular.module('myApp', []);
function EmpCtrl($scope,$http) {

    $scope.getEmployee = function () {
        var httpRequest = $http({
            method: 'POST',
            url: 'EmpService.asmx/ListeEmployes',
            data: "{}",

        }).success(function (data, status) {
            $scope.items = data.d;
        });
    };

    $scope.save = function () {
        $.ajax({
            type: "POST",
            url: "EmpService.asmx/InsertEmploye",
            data: "{'empID':'" + $scope.EmpID + "','nom':'" + $scope.EmpNom + "','prenom':'" + $scope.EmpPrenom + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg.d);
                console.log(msg.d);
            },
            error: function (msg) {
                alert(msg.d);
                console.log(msg.d);
            }
        });

    };

}


Download :VS2012Demo

lundi 15 décembre 2014

Url Routing avec ASP.NET WebForm

Qu'est ce que le Routage ASP.NET

Nous accédons à notre application web en utilisant une URL qui est normalement le chemin physique des pages. Donc URL de routage est un moyen de fournir notre propre URL au lieu du chemin physique de la page. Une autre façon, de routage nous permet un moyen de configurer notre application pour accepter une URL demandée qui fait ne correspond pas à des fichiers physiques. Du point de vue de la sécurité de l'application, ce est important parce que l'on peut facilement connaître la structure de la solution de l'application.

Pourquoi utilisé le Routage ASP.NET


  • Un nom de domaine qui est facile à retenir et facile à épeler
  • URL courtes
  • Facile à taper les URL
  • URLs qui visualisent la structure du site
  • URL persistants qui ne changent pas



Exemple d'utilisation

  1. Commençant par la définition les routes par la methode  RegisterRoutes sur global.asax:


     void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("DemoRoute1",
            "Demo/{year}",
            "~/demo_routing1.aspx");
            routes.MapPageRoute("DemoRoute2",
                "Demo/{lang}/{year}",
                "~/demo_routing2.aspx");
        }
 
     2.  Enregistrer les routes sur la méthode Application_Start


      void Application_Start(object sender, EventArgs e)
        {
     
            RegisterRoutes(RouteTable.Routes);
        }
   

   3. Création des liens sur une page demo.aspx

  • URL codées en dur
        <asp:HyperLink ID="HyperLink1" runat="server" target="_blank"
            NavigateUrl="~/Demo/2014">
            Demo 1
        </asp:HyperLink>
          </br>
        <asp:HyperLink ID="HyperLink2" runat="server" target="_blank"
            NavigateUrl="~/Demo/FR/2014">
            Demo 2
       </asp:HyperLink>


  • URL générées automatiquement en utilisant du balisage


 <asp:HyperLink ID="HyperLink4" runat="server" target="_blank"
            NavigateUrl="<%$RouteUrl:annee=2014,routename=DemoRoute1%>">>
            Demo 3
        </asp:HyperLink>
          </br>
        <asp:HyperLink ID="HyperLink5" runat="server" target="_blank"
            NavigateUrl="<%$RouteUrl:lang=FR,annee=2015,routename=DemoRoute2%>">
            Demo 4
        </asp:HyperLink>
  • URL générées automatiquement en utilisant du code

RouteValueDictionary parameters =
            new RouteValueDictionary  
                { 
                    {"year", "2014" }
                };
            VirtualPathData vpd =RouteTable.Routes.GetVirtualPath(null, "ExpensesRoute", parameters);
            HyperLink6.NavigateUrl = vpd.VirtualPath;



 4. Résultat:

Mon Url réel est http://localhost:54742/demo_routing2.aspx/lang=FR&annee=2014,et le routage m'a donné:

lundi 8 décembre 2014

Utilisation Bundling et minification ASP.NET 4 WebForms

Bundling et Minification sont deux techniques que vous pouvez utiliser dans ASP.NET 4 pour améliorer la performance. Bundling et Minification améliore le temps de chargement en réduisant le nombre de requêtes vers le serveur.
Bundling vous permet de combiner plusieurs JavaScript ou CSS fichiers en un seul package.
Minify réduise le nombre de requêtes HTTP que les navigateurs ont à faire, ce qui réduit la taille des fichiers, et améliorer la performance de l'ensemble du site.

Ajouter de référence à la bibliothèque System.Web.Optimization:


System.Web.Optimization n'est pas une partie du FrameWork .NET 4 . Mais vous pouvez l'ajouter avec NuGet Package.

Pour lancer NuGet Package Boutton droite sur le projet => Manage NuGet Package

Installation NuGet Package ASP.NET



Rechercher et installer Microsoft.AspNet.Web.Optimization sur NuGet Package


Installation NuGet Package ASP.NET



Les nouveau Références ajoutés :


Add réference ASP.NET

Création des Bundles:

  1. Créer un dossier App_Start (si n'exist pas)
  2. Créer un classe BundleConfig sur le dossier App_Start.
     Script et CSS Bundles
       Ici on crée un bundles pour le fichier jquery-1.7.1.js et le fichier site.css


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace Bundles_Minification
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {

            bundles.Add(new ScriptBundle("~/bundles/js").Include(
                "~/Scripts/jquery-1.7.1.js"));
            bundles.Add(new StyleBundle("~/Styles/css").Include("~/Styles/site.css"));
        }
    }
}

 

     3. Aller sur le fichier Global.asax puis modifier la fonction Application_Start
     inscrire les bundles :



  void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }


     4.  Maintenant, vous pouvez ajouter le style et les scripts bundles que vous avez créés ci-dessus à la page comme indiqué ci-dessous:



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo.aspx.cs" Inherits="Bundles_Minification.demo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server">     
          <%: Scripts.Render("~/bundles/js") %>

          <%: Styles.Render("~/Styles/css") %> 
    </asp:PlaceHolder> 
</head>
<body class="maroonbg">
    <form id="form1" runat="server">
    <div>
            Demo utilisation Bundling et Minifiation ASP.NET 4 WebForms
    </div>
    </form>
</body>
</html>



Notes:
    Vous devez activer le mode debug sur le web.config et ajouter ces namesspaces:

<system.web>
    <compilation debug="true" targetFramework="4.5.3" />
    <httpRuntime targetFramework="4.5.3" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>







Code source : Bundling_Minification_Asp.netVS2012