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

2005/11/18

看到webleon的blog,发现了flickr&del.icio.us的新东西

看到webleon的blog,发现了flickr&del.icio.us的新东西
www.flickr.com
-------------------------------------
<div class="flickrimg">
  <script type="text/javascript" src="http://www.flickr.com/badge_code.gne
?nsid=44124393928%40N01&
amp;count=5&
amp;display=latest&
amp;name=0&amp;size=square&amp;raw=1"></script>
  </div>
---------
js
---------
// make sure they're declared

var flickr_badge_border;
var flickr_badge_width;
var flickr_badge_background_color;
var flickr_badge_text_font;
var flickr_badge_image_border;
var flickr_badge_link_color;

// format them as we need them

var flickr__dbr = flickr_badge_border?'border: '+flickr_badge_border+';':'';
var flickr__wth = flickr_badge_width?'width: '+flickr_badge_width+';':'';
var flickr__bg  = flickr_badge_background_color?'background-color: '+flickr_badge_background_color+';':'';
var flickr__fnt = flickr_badge_text_font?'font: '+flickr_badge_text_font+';':'';
var flickr__bdr = flickr_badge_image_border?'border: '+flickr_badge_image_border+';':'';
var flickr__lnk = flickr_badge_link_color?'color: '+flickr_badge_link_color+';':'';

// write the badge

// document.write('<img style="border:0; display:block; height:0; width:0; margin:0; padding:0" alt="" src="http://www.flickr.com/images/spaceout.gif?0927089001132293688" height="0" width="0" border="0" /><img style="border:0; display:block; height:0; width:0; margin:0; padding:0" alt="" src="http://b.flickr.yahoo.com/b?s=792600101&rand=bdaba29d1941499b4e45ab37143e978a" height="0" width="0" border="0" />');
document.write('<div style="padding: 6px 4px; '+flickr__bg+flickr__wth+flickr__dbr+'">');
document.write(' <table cellspacing="0" cellpadding="4" style="'+flickr__wth+'">');
document.write('  <tr align="center"><td style="'+flickr__fnt+'"><a href="http://www.flickr.com/photos/webleon/6769807/"><img src="http://static.flickr.com/8/6769807_8fe58869f4_t.jpg" style="'+flickr__bdr+'" /></a></td></tr>');
document.write('  <tr><td style="'+flickr__fnt+'" align="center" valign="top"><a href="http://www.flickr.com" style="'+flickr__lnk+'">www.<strong><font color="#3993ff">flick</font><font color="#ff1c92">r</font></strong>.com</a></td></tr>');
document.write(' </table>');
document.write('</div>');
-------------------------------------
del.icio.us
-------------------------------------
<script type="text/javascript" src="http://del.icio.us/feeds/js/tags/webleon?count=60;size=12-32;color=ffe6bf-b36b00"></script>
---------
js
---------
(function(){ var ts={"ads":43,"ajax":40,"api":16,"apple":43
,"blog":438,"blogger":12,"bookmark":40
,"browser":68,"business":284,"china":15
,"copyright":23,"Delicious":11,"design":13
,"digital":34,"email":23,"feed":14,"firefox":124
,"flickr":33,"folksonomy":26,"fun":14,"geo":17
,"gmail":49,"google":329,"hardware":23,"im":61
,"internet":183,"ipod":17,"linux":12,"media":31
,"microsoft":269,"mobile":67,"msn":29,"news":18
,"opensource":15,"p2p":27,"podcast":59,"podcasting":23
,"resource":17,"resources":10,"rss":298,"search":332
,"security":28,"seo":10,"skype":25,"sns":114,"software":44
,"spam":13,"standard":10,"tags":11,"tech":60,"tips":18
,"tools":573,"video":28,"voip":39,"web2.0":85,"webdesign":43
,"wiki":22,"xml":10,"yahoo":48}
var ta=9,tz=564
function s(a,b,i,x){if(a>b){var m=(a-b)/Math.log(x),v=a-Math.floor(Math.log(i)*m)}else{var m=(b-a)/Math.log(x),v=Math.floor(Math.log(i)*m+a)};return v}
document.write('<style type="text/css">.delicious-tags{font-family:arial,sans-serif}.delicious-tags a{text-decoration:none}.delicious-tags a:hover{text-decoration:underline}.delicious-tags ul{list-style-type:none;margin:0;padding:0; text-align:justify}.delicious-cloud li{display:inline;text-align:justify;background-image:none !important;padding:0;margin:0}.delicious-cloud .delicious-tag-count{padding-left:0.2em;font-size:12px}.delicious-cloud li:before{content:"" !important}</style>')
var ca=[255,230,191],cz=[179,107,0],c=[]
document.write('<div class="delicious-tags" id="delicious-tags-webleon"><ul class="delicious-cloud">')
for(var t in ts){
 for (var i=0;i<3;i++) c[i]=s(ca[i],cz[i],ts[t]-ta,tz)
var fs = s(12,32,ts[t]-ta,tz)
document.write('<li style="font-size:'+fs+'px;line-height:1;"><a style="color:rgb('+c[0]+','+c[1]+','+c[2]+')" href="http://del.icio.us/webleon/'+encodeURIComponent(t)+'">'+t+'</a> </li>');
}
document.write('</ul></div>') })()
-------------------------------------

2005/11/17

sql中使用指定字符分离长字符串,并以table形式输出

以前记得有这么一个方法,但是找不到了 所以只好自己写一个了
sql中使用指定字符分离长字符串,并以table形式输出

例子
select * from SplitString('abc,aadd,asdf,,asdf,,asdf',',')

结果
substr                                                                                                                                                                           
------------------------------------------------------------------------------------------------------------------------abc
aadd
asdf
asdf
asdf
(5 row(s) affected)
--------------------------------------

方法代码
-----------------
Create FUNCTION SplitString
(
 @string as nvarchar(2048),
 @split as nvarchar(50)
)
RETURNS @reports TABLE(substr nvarchar(2048))
AS
begin
declare @start_location as int
declare @begin as int
declare @end as int
declare @substr as nvarchar(255)

set @start_location=0

while(len(@string)>0)
begin
 select @begin=Charindex(@split,@string,@start_location)
 select @end=Len(@split)
 if(@begin>0)
 begin
  select @substr = Substring(@string,0,Charindex(@split,@string,@start_location))
  select @string = Substring(@string,@begin+@end,len(@string))
 end
 else
 begin
  select @substr=@string
  select @string='';
 end
 if(@substr!='')
  insert @reports select @substr
end
RETURN
end
--------------------------------

2005/11/16

feedsky今日更新

1、修改feed访问错误方式
如: http://feed.feedsky.com/error
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>错误页</title>
        <link>http://www.feedsky.com/error.aspx</link>
        <description>访问feed页面时发生异常</description>
        <item>
        <title>访问的feed不存在!</title>
        <link />
        <pubDate>2005-11-16 16:16:08</pubDate>
        <guid isPermaLink="false">ae578baf-9810-4dd3-96b2-52277239df87</guid>
        <description>当前访问的feed不存在或处理超时</description>
        </item>
    </channel>
</rss>
2、新的企业登陆界面发布

2005/11/15

整理了一下我的blog

整理了一下我的blog
加上flickr和del.icio.us能找到的竟然有9个
呵呵,真不知道我弄了这么多空间要干什么

在我的飞扬轻狂上列了一下 http://fallseir.blogspot.com/

测试使用semagic发布日志到blogger上

测试使用semagic发布日志到blogger上
偶然看到semagic的server选项
所以就试试这个 呵呵

2005/05/30

my first

hello every one!
this's my first blog for blogger.com.
delight with have a blog in this site!
so i am send first post to test.