学习Altas 笔记[JS简单调用服务端方法]

时间:2022-04-23
本文章向大家介绍学习Altas 笔记[JS简单调用服务端方法],主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

      在Ajax框架中,Asp.net方面最强当属Altas最强,以前使用AjaxPro.Net和MagicAjax. 最几个都比较好用。这几个月来Altas已经进入CTP版本,是开始学习研究Altas的时机了。准备利用Altas为 http://www.yupsky.com 开发成员之间在线通讯的类似于MSN这样的功能。今天初步的学习了一下Altas,最基础的学习内容就是使用javascript调用服务端代码。

     Altas和AjaxPro.Net类似,但比AjaxPro.Net强大很多。学习结果记录如下:

     程序的原型来自http://weblogs.asp.net/scottgu/archive/2005/09/14/425131.aspx,但是这个是beta版时候的教程。

     1、下载altas框架,到http://www.asp.net/default.aspx?tabindex=8&tabid=47上去下载,上面有很多内容

     2、使用VS2005创建一个WebSite或者Web Application.

     3、配置Web.config如下:

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="microsoft.web" type="Microsoft.Web.Configuration.MicrosoftWebSectionGroup">
      <section name="converters" type="Microsoft.Web.Configuration.ConvertersSection" requirePermission="false" />
      <section name="webServices" type="Microsoft.Web.Configuration.WebServicesSection" requirePermission="false" />
      <section name="authenticationService" type="Microsoft.Web.Configuration.AuthenticationServiceSection" requirePermission="false" />
      <section name="profileService" type="Microsoft.Web.Configuration.ProfileServiceSection" requirePermission="false" />
    </sectionGroup>
  </configSections>
  
  <!-- 
      The microsoft.web section defines items required for the Atlas framework.
  -->
  <microsoft.web>
    <converters>
      <add type="Microsoft.Web.Script.Serialization.Converters.DataSetConverter"/>
      <add type="Microsoft.Web.Script.Serialization.Converters.DataRowConverter"/>
      <add type="Microsoft.Web.Script.Serialization.Converters.DataTableConverter"/>
    </converters>
    <webServices enableBrowserAccess="true" />
    <authenticationService enabled="true" />
    <!-- The example application needs the profileService to be enabled and to specify the dragOverlayPosition property. -->
    <profileService
      enabled="false" 
      setProperties="dragOverlayPosition" 
      getProperties="dragOverlayPosition" />
  </microsoft.web>

  <connectionStrings >
    <remove name="LocalSqlServer" />
    <add name="LocalSqlServer" connectionString="Data Source=.SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf" />
    <add name="AltasMsn" connectionString="Data Source=localhost;user id=sa;password=;initial catalog=msn" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>

    <pages>
      <controls>
        <add namespace="Microsoft.Web.UI" assembly="Microsoft.Web.Atlas" tagPrefix="atlas"/>
        <add namespace="Microsoft.Web.UI.Controls" assembly="Microsoft.Web.Atlas" tagPrefix="atlas"/>
      </controls>
    </pages>

    <compilation debug="false">
      <buildProviders>
        <add extension=".asbx" type="Microsoft.Web.Services.BridgeBuildProvider" />
      </buildProviders>
    </compilation>
    
    <membership>
      <providers>
        <remove name="AspNetSqlMembershipProvider" />
        <add name="AspNetSqlMembershipProvider" 
                     type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
                     connectionStringName="LocalSqlServer" 
                     enablePasswordRetrieval="false" 
                     enablePasswordReset="true" 
                     requiresQuestionAndAnswer="false" 
                     applicationName="/" 
                     requiresUniqueEmail="false" 
                     passwordFormat="Hashed" 
                     maxInvalidPasswordAttempts="100" 
                     passwordAttemptWindow="10"
                     minRequiredPasswordLength="1" 
                     minRequiredNonalphanumericCharacters="0" 
                     passwordStrengthRegularExpression="" />
      </providers>
    </membership>
    
    <!-- The SimpleList application needs profile to be enabled, and to allow anonymous users access to the property. -->
    <profile enabled="false">
      <properties>
        <add allowAnonymous="true" name="dragOverlayPosition" defaultValue="" serializeAs="String" />
      </properties>
    </profile>

    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" type="Microsoft.Web.Services.ScriptHandlerFactory" validate="false"/>
      <add verb="*" path="*.asbx" type="Microsoft.Web.Services.ScriptHandlerFactory" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="Microsoft.Web.Services.ScriptModule"/>
      <add name="BridgeModule" type="Microsoft.Web.Services.BridgeModule"/>
      <add name="WebResourceCompression" type="Microsoft.Web.Services.WebResourceCompressionModule"/>
    </httpModules>

        <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
        <authentication mode="Forms" />
        <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>

Step 1: 产生一个Web服务 推荐使用WebService  atlas使用webService时,对于webService并没有特殊要求

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace AltasMsn
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class LapService : System.Web.Services.WebService
    {
        [WebMethod]
        public ProcessData[] GetProcesses()
        {

            return this.GetAllProcesses().ToArray();

        }


        [WebMethod]
        public ProcessData[] MatchProcesses(string expression)
        {

            List<ProcessData> data = this.GetAllProcesses();

            if (String.IsNullOrEmpty(expression))
            {

                return data.ToArray();

            }

            string[] words = expression.Split(' ');

            return data.FindAll(new Predicate<ProcessData>(delegate(ProcessData process)
            {

                return System.Text.RegularExpressions.Regex.IsMatch(process.Name, expression);

            })).ToArray();

        }



        private List<ProcessData> GetAllProcesses()
        {

            List<ProcessData> data = new List<ProcessData>();

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();

            foreach (System.Diagnostics.Process process in processes)
            {

                data.Add(new ProcessData(process.ProcessName, process.WorkingSet64, process.Threads.Count));

            }



            return data;

        }
        

    }



    public class ProcessData
    {

        private string _name;

        private long _workingSet;

        private int _threadCount;



        public string Name
        {

            get { return _name; }

            set { _name = value; }

        }



        public long WorkingSet
        {

            get { return _workingSet; }

            set { _workingSet = value; }

        }



        public long WorkingSetInMB
        {

            get { return _workingSet / (1024 * 1000); }

            private set { }

        }



        public int ThreadCount
        {

            get { return _threadCount; }

            set { _threadCount = value; }

        }



        public ProcessData() { }



        public ProcessData(string name, long workingSet, int threadCount)
        {

            _name = name;

            _workingSet = workingSet;

            _threadCount = threadCount;

        }

    }

}

这个服务用于查询当前系统中正在活动进程。 Step2 : Simple Invocation of the Web Service 使用很简单,使用Javascript调用远程服务。 页面代码如下:

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

<!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>Untitled Page</title>
</head>
  <atlas:ScriptManager id="scriptManager1" runat="server">
    <Services>
        <atlas:ServiceReference Path="~/LapService.asmx" />
    </Services>
  </atlas:ScriptManager> 

  <script language="javascript" type="text/javascript"> 

        function Button1_onclick() {

            var text1 = document.getElementById("Text1");

            AltasMsn.LapService.MatchProcesses(text1.value, onSearchComplete);
        }      

        function onSearchComplete(results) {

            var searchResults = document.getElementById("searchResults");           

            for (var i=0; i<results.get_length(); i++) {
              searchResults.innerHTML += results[i].Name + "<br>";
            }
        }

  </script>

<body>
    <form id="form1" runat="server">
     <div id="logo">
      Process Explorer

    </div>
    <div id="header">
      Search:
      <input id="Text1" type="text" />
      <input id="Button1" type="button" value="Search" onclick="Button1_onclick();" />

    </div>
    <div id="content">
      <div class="left">
        <span id="searchResults"></span>
      </div>   
    </div>
    </form>
</body>
</html>

示例的结果如下: