2005/12/02

使用xml序列化 一个对象

使用xml序列化 一个对象
private void outObjectAsXml(object o)
    {
        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(o.GetType(), "http://feedsky.com/0.2/service");
        StringWriter sw = new StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        xw.Formatting = Formatting.Indented;
       
        xs.Serialize(xw, o);

        lt_output.Text = HttpUtility.HtmlEncode(sw.ToString()).Replace("\n", "<br/>").Replace(" ","&nbsp;") ;
    }

xml序列化的例子

xml序列化的例子
[System.ComponentModel.DefaultValueAttribute ("2002")]
 #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
        public void ReadXml(XmlReader reader)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            XmlAttribute xa = doc.Attributes["id"];
            if (xa != null)
                id = long.Parse(xa.Value);
            xa = doc.Attributes["uri"];
            if (xa != null)
                uri = xa.Value;
            xa = doc.Attributes["feedtype"];
            if (xa == null)
                feedtype = FeedSky.Services.feedtype.simple;
            XmlNode xn=doc.SelectSingleNode("feed/title");
            if (xn != null)
            {
                title=xn.Value;
            }
            xn = doc.SelectSingleNode("feed/tags");
            if (xn != null)
            {
                tags = xn.Value;
            }
            XmlNodeList xns = doc.SelectNodes("feed/sourcerss");
            if (xns != null && xns.Count > 0)
            {
                List<rss> srs = new List<rss>();
                foreach(XmlNode x in xns)
                {
                    rss r = new rss();
                    r.ReadXml(x.OuterXml);
                    srs.Add(r);
                }
                if (srs.Count > 0)
                    sourcerss = srs.ToArray();
            }
        }
        public void WriteXml(XmlWriter writer)
        {
           // writer.WriteStartElement("feed");
            if (id > 0)
            {
                writer.WriteAttributeString("id", id.ToString());
            }
            if (uri != null)
            {
                writer.WriteAttributeString("uri", uri);
            }
            if (feedtype != FeedSky.Services.feedtype.simple)
            {
                writer.WriteAttributeString("feedtype", feedtype.ToString());
            }
            if (title != null)
            {
                writer.WriteStartElement("title");
                writer.WriteCData(title);
                writer.WriteEndElement();
            }
            if (tags != null&&tags.Length>0)
            {
                writer.WriteStartElement("tags");
                writer.WriteCData(tags);
                writer.WriteEndElement();
            }
            if (sourcerss != null)
            {
                foreach (rss r in sourcerss)
                {
                    writer.WriteStartElement("sourcerss");
                    r.WriteXml(writer);
                    writer.WriteEndElement();
                }
            }
          //  writer.WriteEndElement();
        }
        #endregion
    public class feed:IXmlSerializable
    {
        public long id;
        public string uri;
        public string title;
        public feedtype feedtype;
        public string tags;
        public rss[] sourcerss;

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            XmlAttribute xa = doc.Attributes["id"];
            if (xa != null)
                id = long.Parse(xa.Value);

            xa = doc.Attributes["uri"];
            if (xa != null)
                uri = xa.Value;

            xa = doc.Attributes["feedtype"];
            if (xa == null)
                feedtype = FeedSky.Services.feedtype.simple;

            XmlNode xn=doc.SelectSingleNode("feed/title");
            if (xn != null)
            {
                title=xn.Value;
            }

            xn = doc.SelectSingleNode("feed/tags");
            if (xn != null)
            {
                tags = xn.Value;
            }

            XmlNodeList xns = doc.SelectNodes("feed/sourcerss");
            if (xns != null && xns.Count > 0)
            {
                List<rss> srs = new List<rss>();
                foreach(XmlNode x in xns)
                {
                    rss r = new rss();
                    r.ReadXml(x.OuterXml);
                    srs.Add(r);
                }
                if (srs.Count > 0)
                    sourcerss = srs.ToArray();
            }
        }

        public void WriteXml(XmlWriter writer)
        {
           // writer.WriteStartElement("feed");
            if (id > 0)
            {
                writer.WriteAttributeString("id", id.ToString());
            }
            if (uri != null)
            {
                writer.WriteAttributeString("uri", uri);
            }
            if (feedtype != FeedSky.Services.feedtype.simple)
            {
                writer.WriteAttributeString("feedtype", feedtype.ToString());
            }
            if (title != null)
            {
                writer.WriteStartElement("title");
                writer.WriteCData(title);
                writer.WriteEndElement();
            }
            if (tags != null&&tags.Length>0)
            {
                writer.WriteStartElement("tags");
                writer.WriteCData(tags);
                writer.WriteEndElement();
            }

            if (sourcerss != null)
            {
                foreach (rss r in sourcerss)
                {
                    writer.WriteStartElement("sourcerss");
                    r.WriteXml(writer);
                    writer.WriteEndElement();
                }
            }

          //  writer.WriteEndElement();
        }

        #endregion
    }

 

2005/12/01

.net webservice 概览 阅读asp.net的QuickStart

好久没有看web Service了 所以到 asp.net 上找篇文档看看
1、定义WebService
2、WS-I Basic Profile 1.1 支持
3、禁用压缩
4、使用Session
5、Schema 验证
6、service的异步调用
7、客户端调用时动态配置WebService的url
8、在Service中抛出SOAP的异常
9、使用SOAP Headers 添加附加信息(如:身份信息)
10、使用默认的网络身份验证

1、定义WebService
页面上
  使用WebService命令指定页面的类型为WebService和实现Service的类
  <%@ WebService Language="C#" CodeBehind="~/App_Code/BaseOne.cs" Class="BaseOne" %>
类定义
  使用WebService属性表示定义的Service Class
  [WebService(Namespace = "http://test.com/webservice")]
  使用WebMethod属性定义Service 方法
  [WebMethod(Description="test description!",MessageName="HelloWorld2")]

2、WS-I Basic Profile 1.1  支持
asp.net 2.0 实现了对 WS-I Basic Profile 1.1 Conformance 的支持,只需要在service class上使用WebServiceBinding 属性标示一下就可以了,虽然看了一会那个BP1.1也没看到什么所以然
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1, EmitConformanceClaims=true)]

3、禁用压缩
在客户端使用代理时设置
EnableDecompressionService service = new EnableDecompressionService();
service.EnableDecompression = true;
4、使用Session
//On the client you must add the following code (for session state only):
serviceName.CookieContainer = new System.Net.CookieContainer();
//Setting EnableSession to true allows state to be persisted per Session
   [WebMethod(EnableSession=true)]
   public String UpdateSessionHitCounter() {
      //update the session "HitCounter" here
      return Session["HitCounter"].ToString();
   }
5、Schema 验证
//create the validating reader
XmlTextReader tr = new XmlTextReader(input, XmlNodeType.Document, null);
XmlValidatingReader vr = new XmlValidatingReader(tr);

//add the schema and set the validation type to schema
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add("Microsoft.Samples.Web.Services", "insert location here...");
vr.Schemas.Add(schemas);
vr.ValidationType = ValidationType.Schema;

//add our event callback function to the event handler in case there is a validation error
vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);

try
{
    //if there is an error we will fall out of this while loop and our callback function will be called
    while (vr.Read())
    {
        //do nothing 
    }
}
catch (Exception exception)
{
    //an exception will be thrown if there are non-validation errors, e.g. in the case of malformed XML
}
6、service的异步调用
//First implement the HelloWorldCompleted method using the following signature:
//public void HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs args)

//Create the Web service
HelloWorldWaitService service = new HelloWorldWaitService();
//Add our callback function to the event handler
service.HelloWorldCompleted += this.HelloWorldCompleted;
//Call the Web service asynchronously
service.HelloWorldAsync("first call");
//when the Web service call returns the HelloWorldCompleted method will be called
7、客户端调用时动态配置WebService的url
<configuration>
   <appSettings>
      <add key="WSUrl" value="insert location here..." />
   </appSettings>
</configuration>
HelloWorldService service = new HelloWorldService();
//Change the location of the Web service in machine.config if desired
service.Url = System.Configuration.ConfigurationSettings.AppSettings["WSUrl"];
output.Text = service.HelloWorld();
8、在Service中抛出SOAP的异常
//assume that there was an error validating the SOAP Message
if(true)
{
    XmlDocument doc = new XmlDocument();
    //insert your own XML into the XmlDocument,
    //this will go into the Detail element of the SOAP fault
    string errorMsg = "An error was received...";
    //the SOAP fault will contain a human-readable error message,
    //the fault code, the SOAP actor, and the detail element   
    SoapException exc = new SoapException(errorMsg, SoapException.ClientFaultCode, "", detail);
    throw exc;
}
9、使用SOAP Headers 添加附加信息(如:身份信息)
客户端调用
// On the server, create the AuthHeader class which extends from SoapHeader
public class AuthHeader : SoapHeader {
    public string Username;
    public string Password;
}
  
// On the client, create a new instance of the AuthHeader class
AuthHeader myHeader = new AuthHeader();

//WARNING: This sample is for demonstration purposes only.  Username/password information is sent in plain text,
//which should never be done in a real application. It is not secure without modification. 
myHeader.Username = "JaneDoe";
myHeader.Password = "password";

// Set the AuthHeader public member of the Web service instance to myHeader
service.AuthHeaderValue = myHeader;
   
// Call the Web service, which automatically sends the header with the request
string answer = service.HelloWorld();
服务器端接收
// AuthHeader class extends from SoapHeader
    public class AuthHeader : SoapHeader {
        public string Username;
        public string Password;
    }

    [WebService(Description="Simple sample to demonstrate use of SOAP Headers", Namespace="Microsoft.Samples.XmlMessaging.WebServices")]
    public class HeaderService {

        public AuthHeader sHeader;

        [WebMethod(Description="This method requires a custom soap header set by the caller")]
        [SoapHeader("sHeader")]
        public string SecureMethod() {

            if (sHeader == null)
              return "ERROR: Please supply credentials";

            string usr = sHeader.Username;
            string pwd = sHeader.Password;

            if (AuthenticateUser(usr, pwd)) {
                 return "SUCCESS: " + usr;
            }
            else {
                 return "ERROR: Could not authenticate";
            }
        }

        private bool AuthenticateUser(string usr, string pwd) {

            if ((usr != null)&&(pwd != null)) {
                // could query a database here for credentials...
                return true;
             }
            return false;
        }
    }
10、使用默认的网络身份验证
UseDefaultCredentialsService service = new UseDefaultCredentialsService();
service.UseDefaultCredentials = true;

使用XmlSchema验证xml的正确性

XmlTextReader
XmlValidatingReader
XmlSchemaCollection
ValidationType = ValidationType.Schema;
vr.ValidationEventHandler +=
new ValidationEventHandler (ValidationHandler);


code in quickstart from asp.net

<%@ Webservice Language="C#" Class="MessageValidationService" %>


using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.IO;

[WebService(Namespace="Microsoft.Samples.XmlMessaging.WebServices")]
public class MessageValidationService {

   private string returnMessage = "Success! Validation was successful.";
   
   [WebMethod]
   public string SendToValidator(string input)
   {
      XmlTextReader tr = new XmlTextReader(input, XmlNodeType.Document, null);
      XmlValidatingReader vr = new XmlValidatingReader(tr);

      XmlSchemaCollection schemas = new XmlSchemaCollection();
      schemas.Add("Microsoft.Samples.Web.Services", "http://66.129.71.130/quickstartv20/ webservices/samples/ MessageValidation/Book.xsd");
      vr.Schemas.Add(schemas);
      vr.ValidationType = ValidationType.Schema;
      vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);

      try
      {
          while (vr.Read())
          {
              //do nothing 
          }
      }
      catch (Exception exception)
      {
          returnMessage = "Failure. An Exception was received, most likely indicating malformed XML. Message: " + exception.Message;
      }
      return returnMessage;      
   }

   public void ValidationHandler(object sender, ValidationEventArgs args)
   {
      returnMessage = "Failure. Validation was not successful. Message: " + args.Message;  
   }  
}

参考:Validate Messages QuickStart in Asp.net