最近项目的一些心得(纯贴代码)

唉,眼看着ASP.NET第一步已经出版2年了,这2年貌似自己进步也不是很大,最近完成了一个项目,分享一点代码吧,以后要复制粘贴自己也方便点,因为主要是给自己看的,大家看不懂别见怪。

1、WCF中统一处理异常,并自动包装为 FaultException 返回给客户端:

先建立这么一个ServiceBehavior特性:
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    
public sealed class ErrorHandlingBehaviorAttribute : Attribute, IServiceBehavior
    {
        
#region IServiceBehavior Members

        
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
           
        }

        
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            IErrorHandler handler 
= new ErrorHandler();

            
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(handler);
            }
        }

        
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            
        }

        
#endregion
    }

然后呢,需要实现啊这么一个自定义的ErrorHandler:
    public class ErrorHandler : IErrorHandler
    {
        
#region IErrorHandler Members
        
        
/// <summary>
        
/// Log exception
        
/// </summary>
        
/// <param name="error"></param>
        
/// <returns></returns>
        public bool HandleError(Exception error)
        {
            
// Ignore communication exception, only log business logic exception
            if (error is CommunicationException)
                
return true;

            Log.LogException(error);
            
return true;
        }

        
/// <summary>
        
/// Warp Exception with FaultException
        
/// </summary>
        
/// <param name="error"></param>
        
/// <param name="version"></param>
        
/// <param name="fault"></param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            FaultException faultException 
= new FaultException(error.Message);
            MessageFault m 
= faultException.CreateMessageFault();
            fault 
= Message.CreateMessage(version, m, faultException.Action);
        }

        
#endregion
    }

Log类代码就不写了,爱怎么记录就怎么记录,最后只要把这个特性应用到Service的类上即可。

2、把XML结构转换为span包装的HTML,这样就可以直接为XML的各个层次应用样式啦:

        /// <summary>
        
/// Convert <infs><inf>a</inf><inf>b</inf></infs> to <span class="infs"><span class="inf">a</span><span class="inf">b</span></span>
        
/// </summary>
        
/// <param name="xml"></param>
        
/// <returns></returns>
        public static string ConvertXmlToHtml(this string xml)
        {
            
if (string.IsNullOrEmpty(xml))
                
return string.Empty;

            XElement root 
= XElement.Parse(string.Format("<root>{0}</root>", xml));

            
foreach (var el in root.DescendantsAndSelf())
                el.AddAnnotation(
                    
new XElement("span",
                        
new XElement("ApplyTransforms"),
                        
new XAttribute("class", el.Name)
                    )
                );

            XElement newRoot 
= XForm(root);
            
return newRoot.ToString();
        }

XForm的代码如下:

       private static XElement XForm(XElement source)
        {
            
if (source.Name == "a"return source;

            
if (source.Annotation<XElement>() != null)
            {
                XElement anno 
= source.Annotation<XElement>();
                
return new XElement(anno.Name,
                    anno.Attributes(),
                    anno.Nodes().Select((XNode n) 
=>
                    {
                        XElement annoEl 
= n as XElement;
                        
if (annoEl != null)
                        {
                            
return (object)(source.Nodes().Select((XNode n2) =>
                            {
                                XElement e2 
= n2 as XElement;
                                
if (e2 == null)
                                    
return n2;
                                
else
                                    
return XForm(e2);
                            }));
                        }
                        
else
                            
return n;
                    })
                );
            }
            
else
            {
                
return new XElement(source.Name,
                    source.Attributes(),
                    source.Nodes().Select(n 
=>
                    {
                        XElement el 
= n as XElement;
                        
if (el == null)
                            
return n;
                        
else
                            
return XForm(el);
                    })
                );
            }
        }

3、LINQ TO XML来更新和删除XML:

        /// <summary>
        
/// Remove unwanted embedded translation according to culturecode
        
/// </summary>
        
/// <param name="text"></param>
        
/// <param name="cultureCode"></param>
        
/// <returns></returns>
        public static string RemoveTranslationFromNotePanel(string text, string cultureCode)
        {
            var xml 
= XDocument.Parse(text);
            var translationList 
= from t in xml.Descendants("trans")
                                  select t;
            
if (cultureCode == "cs")
                translationList 
= translationList.Where(t => t.Attribute("lang").Value == "CN");
            
if (cultureCode == "ch")
                translationList 
= translationList.Where(t => t.Attribute("lang").Value == "CNS");
            translationList.Remove();

            
return xml.ToString();
        }

        
/// <summary>
        
/// Separate out title in notepanel xml
        
/// </summary>
        
/// <param name="text"></param>
        
/// <param name="title"></param>
        
/// <returns></returns>
        public static string RemoteTitleFromNotePanelAndGetTitle(string text, ref string title)
        {
            var xml 
= XDocument.Parse(text);
            var titleElement 
= (from t in xml.Descendants("title") select t).FirstOrDefault();
            
if (titleElement != null)
            {
                title 
= titleElement.Value;
                titleElement.Remove();
            }
            
return xml.ToString();
        }

        
/// <summary>
        
/// Handle <gl></gl>,<nondv></nondv> and <x></x> tags
        
/// </summary>
        
/// <param name="text"></param>
        
/// <returns></returns>
        public static string FormatSenseDefinition(string text)
        {
            var xml 
= XDocument.Parse(text);
            
            
// <gl>content here</gl> -> <gl>(= content here)</gl>
            var glTag = (from t in xml.Descendants("gl") select t).ToList();
            glTag.ForEach(gl 
=> gl.Value = string.Format("(= {0})", gl.Value));

            
// <x refurl="guidewordblock_id">content here</x> -> <x refurl="guidewordblock_id"><a title="headword">content here</a></x>
            var xTag = (from t in xml.Descendants("x"where t.Attribute("refurl"!= null select t).ToList();
            
for (int i = 0; i < xTag.Count; i++)
            {
                var x 
= xTag[i];
                
int guidewordID = 0;
                
if (int.TryParse(x.Attribute("refurl").Value, out guidewordID))
                {
                    
if (guidewordID != 0)
                    {
                        var headwordText 
= ContentHelper.GetHeadwordTextFromGuidewordID(guidewordID);
                        
if (!string.IsNullOrEmpty(headwordText))
                        {
                            x.ReplaceAll(
new XElement("a", x.Value, new XAttribute("title", headwordText)));
                        }
                    }
                    
else
                        x.ReplaceAll(
new XElement("a", x.Value, new XAttribute("title", x.Value)));
                }
            }

            
// <nondv refurl="guidewordblock_id">content here</nondv> -> <nondv refurl="guidewordblock_id"><a title="headword">content here</a></nondv>
            var nondvTag = (from t in xml.Descendants("nondv"where t.Attribute("refurl"!= null select t).ToList();
            
for (int i = 0; i < nondvTag.Count; i++)
            {
                var nondv 
= nondvTag[i];
                
int guidewordID = 0;
                
if (int.TryParse(nondv.Attribute("refurl").Value, out guidewordID))
                {
                    
if (guidewordID != 0)
                    {
                        var headwordText 
= ContentHelper.GetHeadwordTextFromGuidewordID(guidewordID);
                        
if (!string.IsNullOrEmpty(headwordText))
                        {
                            nondv.ReplaceAll(
new XElement("a", nondv.Value, new XAttribute("title", headwordText)));
                        }
                    }
                    
else
                        nondv.ReplaceAll(
new XElement("a", nondv.Value, new XAttribute("title", nondv.Value)));
                }
            };

            
return xml.ToString();
        }


posted @ 2009-07-19 19:56 lovecherry 阅读(...) 评论(...) 编辑 收藏