Fluentapi is attracted by its smooth coding and good readability. There are many articles about fluentapi in the garden, I can't help but put a small library I recently wrote here to supplement the application scenarios of smooth APIs.
I wrote this small class library from my post yesterday. <Asp.net webform can also use Ajax -- My Ajax framework> later", Dark"For my suggestion, can I use the Framework to dynamically generate JS files? This is similar to the ajaxpro method. I thought it was a good suggestion, so I wrote it, it turns out that writing JavaScript data streams to response is messy and prone to errors.
My initial code is as follows: (I do this to generate a piece of JS Code ):
Response. Output. writeline ("<SCRIPT> ");
Response. Output. writeline ("Var powerajax = function (){};");
Response. Output. writeline ("powerajax. _ private = function (){};");
Response. output. writeline ("powerajax. asyncajax = function (methodname, paramarray, success, failure) {powerajax. _ private. ajax (methodname, paramarray, success, failure, true );}");
Response. output. writeline ("powerajax. syncajax = function (methodname, paramarray, success, failure) {powerajax. _ private. ajax (methodname, paramarray, success, failure, false );};");
Response. Output. writeline ("powerajax. _ private. Ajax = function (methodname, paramarray, success, failure, isasync ){");
Response. Output. writeline ("Var DATA = {};");
Response. Output. writeline ("Switch (paramarray. Length ){");
Response. Output. writeline ("case 0: Data = {'isaxaxrequest': True, 'methodname': methodname}; break ;");
Response. Output. writeline ("Case 1: Data = {'isaxaxrequest': True, 'methodname': methodname, 'param0': paramarray [0]}; break ;");
Response. Output. writeline ("}");
Response. Output. writeline ("Var url = Document. Location. href ;");
Response. Output. writeline ("};");
Response. Write ("</SCRIPT> ");
I feel that this is too unreliable, and I will often write errors, especially for the correspondence between the "{" and "}" symbols, which is really tangled, if you do not forget or forget, the Javascript cannot be opened at all. Some statements often forget to add a ";", so the Code cannot be executed because of the small ";" of the statement.
So I made a simple improvement and wrote a simple small class library to generate:
My idea is:: Divide all JS Code into two types: "General statement" and "from" {...} ", you can continue to write general statements and {...} in braces {.....}. It is like a function can continue to set N functions and N statements, so the following API is available.
First, let's look at the improved code:
ScriptFactory.CreateScript( new ScriptSentence("var PowerAjax = function () { }"), new ScriptSentence("PowerAjax.__Private = function () { }"), new ScriptContainer("PowerAjax.AsyncAjax = function (methodName, paramArray, success, failure)", new ScriptSentence("PowerAjax.__Private.Ajax(methodName, paramArray, success, failure, true)")), new ScriptContainer("PowerAjax.SyncAjax = function (methodName, paramArray, success, failure)", new ScriptSentence("PowerAjax.__Private.Ajax(methodName, paramArray, success, failure, false)")), new ScriptContainer("PowerAjax.__Private.Ajax = function(methodName, paramArray, success, failure,isAsync)", new ScriptSentence("var data = {}"), new ScriptContainer("switch (paramArray.length)", new ScriptSentence("case 0:data = { 'isAjaxRequest': true, 'MethodName': methodName };break"), new ScriptSentence("case 1:data = { 'isAjaxRequest': true, 'MethodName': methodName, 'param0': paramArray[0] }; break"),new ScriptSentence("var url = document.location.href"))));
Is it nice? I don't need to worry about all the statements, nor do I need to add a ing between {And.
A keen friend may already feel that this API is similar to linqtoxml to generate a piece of code, such:
XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement("xxxConfig", new XElement("a", s_LDAPEnabled), new XElement("b", s_ServerPath), new XElement("c", s_BaseDN), new XElement("d", s_UserCN)));
Advantages of this structure: it is not prone to errors, it is comfortable to write, and the layout is rigorous. It is easy to see the structural characteristics of the entire document from the code. Similarly, the JS Code I output clearly shows what the JS file generated in C # looks like?
The demonstration is here to publish the entire API and everyone will learn from each other:
* ******* Scriptfactory class ********
Purpose:Easy to call at the front end. Because it is loaded withTree StructureSo we need to use recursion to parse the data and generate JS Code.
Public sealed class scriptfactory {PrivateStatic string createscripttrue (Params iscriptbase [] scriptbases) {stringbuilder sb = new stringbuilder (); foreach (VAR scriptbase in scriptbases) {If (scriptbase is scriptsentence) {sb. append (scriptbase. scriptcontent + ";");} If (scriptbase is scriptcontainer) {sb. append (scriptbase. scriptcontent); sb. append ("{"); sb. append (createscripttrue (scriptcontainer) scriptbase ). children. toarray (); // recursive call to generate the JS tree structure sb. append ("};") ;}} return sb. tostring ();} public static string createscript (Params iscriptbase [] scriptbases) {return string. format ("<SCRIPT> {0} </SCRIPT>", scriptfactory. createscripttrue (scriptbases ));}}
* ******* Iscriptbase interface ********
Purpose: To provide content standards
public interface IScriptBase { string ScriptContent { get; set; } }
* ****** Scriptcontainer: iscriptbase ********
Purpose: To host statements containing the {} structure. {} may also contain statements and various statements. Therefore, a m_scriptbases is used to store all the structures.
public sealed class ScriptContainer : IScriptBase { private List<IScriptBase> m_ScriptBases = new List<IScriptBase>(); public IEnumerable<IScriptBase> Children { get { return this.m_ScriptBases; } } public string ScriptContent { get; set; } public ScriptContainer(string content, params IScriptBase[] scriptBeses) { this.ScriptContent = content; this.m_ScriptBse = scriptBeses.ToList(); } }
* ****** Scriptesentence: iscriptbase ********
Purpose: To carry general statements. A statement itself does not have a data structure, but only contains content.
public sealed class ScriptSentence : IScriptBase { public string ScriptContent { get; set; } public ScriptSentence(string content) { this.ScriptContent = content; } }
OK. The above is all the code. Is it very simple? What about code simplicity?
Key points of this API:Interface inheritance, Params usage, tree structure, and recursion. Pay attention to the usage of parameters in the constructor. The secret of this smooth API is here (Daniel can bypass it, huh, huh)
The above is a trial. It is intended to demonstrate the smooth API of this linqtoxml generation method. please correct me if there is anything wrong. Thank you very much.From the previous article, I learned a lot about your ideas.
If this article is helpful to you, please pin it with ^_^