dsl boo3个例子 9

简介: ƒ The Message-Routing DSL is an example of an imperative DSL. It’s executed to perform some goals. ƒ The Authorization DSL is a more declarative example (but still mostly impera- tive).

ƒ The Message-Routing DSL is an example of an imperative DSL. It’s executed to

perform some goals.

ƒ The Authorization DSL is a more declarative example (but still mostly impera-

tive). It’s executed to produce a value, which is later used.

ƒ The Quote-Generation DSL is a mostly declarative example. It produces an

object graph that’s later taken up by the processing engine.

Message-Routing DSL

The main reason that we want to use a DSL here is to keep the system flexible and

make it easy to add new messages and transformations. This DSL will be used by tech-

nical people, most probably the developers on the project. This, in turn, means that

we can use a technical DSL here. Each script using this DSL will probably have the fol-

lowing responsibilities:

ƒDeciding whether the script can handle the message

ƒTransforming the message to the internal message representation

ƒDeciding where to dispatch the message

clip_image001

RouteNewOrder.boo DSL定义

# decide if this message match this DSL script

return if msg.type != "NewOrder" and msg.version == "1.0"

# decide which handle is going to handle it

HandleWithNewOrderHandler:

# define a new list

lines = []

# add order lines to the list

for line in msg.order_lines:

lines.Add(OrderLine( line.product, line.qty ) )

# create internal message representation

returnNewOrderMessage(

msg.customer_id,

msg.type,

lines.ToArray(OrderLine) )

clip_image003

IQuackFu it allows us to handle unknown method calls at runtime in asmart fashion.

RoutingBaseThe Message-Routing DSL script will be compiled into a class thatinherits from RoutingBase, and all the code in the script
 will go into the Route()method, while the  msg field will contain the current message during execution
RoutingDslEnginecompile this DSL. We do it using a DSL engine
RouterThe Routerclass hook it up to the Routerclass

使用:

// translate from the post body to a json object
byte[] bytes = context.Request.BinaryRead(context.Request.TotalBytes);
string json = Encoding.UTF8.GetString(bytes);
JsonSerializer jsonSerializer = new JsonSerializer();
JsonReader reader = new JsonReader(new StringReader(json)); JavaScriptObject javaScriptObject = (JavaScriptObject)jsonSerializer.Deserialize(reader);

// send the json object to be routed
string scriptsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
string returnMessage = Router.Route(scriptsPath,
new JsonMessageAdapter(javaScriptObject));
context.Response.Write(returnMessage);

context.Response.Write(returnMessage);

JsonMessageAdapter class is responsible for translating the JavaScriptObject into an IQuackFu, which is what we expect in the MessageRouting DSL

using Boo.Lang;
using Newtonsoft.Json;
public class JsonMessageAdapter : IQuackFu
{
private readonly JavaScriptObject js;
public JsonMessageAdapter(JavaScriptObject js)
    {
this.js = js;
    }
public object QuackGet(string name, object[] parameters)
    {
object value = js[name];
JavaScriptArray array = value as JavaScriptArray;
if(array!=null)
        {
return array.ConvertAll(delegate(object obj)
            {
return new JsonMessageAdapter((JavaScriptObject) obj);
            });
        }
return value;
    }

 
 

Authorization DSL

clip_image005

ƒThe CheckAuthorization() method and the Operation property are both

abstract, so derived classes (and our DSL) have to implement them.

ƒThe Allow() and Deny() methods are the only ways for the derived class to

affect the state of the rule. Both methods accept a reason string, which means

that we’re automatically documenting the reason for the decision.

operation "/account/login"

if Principal.IsInRole("Administrators"):
        Allow("Administrators can always log in")
        return

if date.Now.Hour < 9 or date.Now.Hour > 17:
        Deny("Cannot log in outside of business hours, 09:00 - 17:00")

e make use of the Boo date keyword

to reference System.DateTime, which we haven’t seen before, but that isn’t very

interesting.

There is one interesting thing here: the first line isn’t something that we’ve seen so

far. We know that we need to provide an implementation of the Operation property,

but how can we do it?

It’s done using a macro, which takes the first argument of the macro, generates a

property, and returns that argument from the property.

使用

 WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool? allowed = Authorization.IsAllowed(principal, "/account/login");
Console.WriteLine("Allowed login: {0}", allowed);
Console.WriteLine(Authorization.WhyAllowed(principal, "/account/login"));

The Quote-Generation DSL

clip_image007

The first is that we use astrange naming convention for some of the methods (requires, same_machine_as,specification, and users_per_machine do not follow the standard .NET namingconvention). This is the easiest way to get keywords in the DSL.

Note that thespecification() method accepts a delegate as the last parameter, so we’re using

anonymous blocks again, like we did in the Message-Routing DSL Handle method.

The second thing to note is all the @ signs scattered through the DSL (listing 4.16).

Those are called symbols, and they translate to string literals without the annoying

The last thing that’s worth noting about the QuoteGeneratorRule class is that itaccepts a RequirementsInformation class. This allows it to understand what context itruns in, which will be important later on.

The QuoteGeneratorRule class is responsible for building the object model thatwill later be processed by the quote-generation engine.

specification @vacations:
        requires @scheduling_work
        requires @external_connections
       
specification @salary:
        users_per_machine 150
       
specification @taxes:
        users_per_machine 50

specification @pension:
        same_machine_as @health_insurance
相关文章
|
10月前
|
人工智能 自然语言处理 机器人
2026年阿里云OpenClaw(原Moltbot)零门槛部署指南:三大方式+百炼API配置实操
2026年,OpenClaw(原Moltbot/Clawdbot)作为阿里云生态下的明星零代码RPA平台,凭借与大语言模型的深度集成能力,成为办公自动化、智能客服、多平台协同场景的首选工具。它无需编写复杂脚本,通过自然语言指令即可实现邮件管理、文档处理、网页操作等自动化任务,更能打造具备持久记忆、主动执行功能的定制化AI助理,像“7×24小时不下班的AI员工”一样持续创造价值。
1018 6
|
11月前
|
数据采集 人工智能 监控
什么是数据治理?2026年数据治理的五大核心目标
2026年,数据治理跃升为驱动数字化转型的核心引擎。市场规模破860亿元,金融、政务、交通成主战场。瓴羊Dataphin以OneID/OneModel/OneService架构,融合AI实现智能元数据、质量监控与敏感识别,支撑全域协同、资产入表与实时决策,让治理真正创造业务价值。(239字)
什么是数据治理?2026年数据治理的五大核心目标
|
11月前
|
传感器 人工智能 安全
从“遥控器”到“智能管家”:手把手教你打造会思考的IoT大模型Agent
你好,我是maoku,专注用通俗语言讲透AI技术。本文带你零基础打造“会思考”的物联网智能管家:基于ReAct架构,通过微调(LoRA)、动态技能库与白盒SOP,让大模型从“聊天高手”升级为能主动感知、推理决策、安全执行的IoT Agent。实操仅需3步,门槛低、效果实!
|
11月前
|
消息中间件 人工智能 NoSQL
[高并发架构] 挑战百万级Token吞吐:智能体来了(西南总部)深度解析AI调度官的流量削峰与分级治理策略
传统的 API Gateway 已经失效。我们需要一种专为 AI 设计的流量治理组件。 本文将基于 智能体来了(西南总部) 技术团队的实战经验,深度解析企业级 “AI 调度官” (AI Dispatcher) 的架构设计。我们将探讨如何利用 消息队列(MQ)削峰、优先级队列调度、以及基于语义的自适应限流,构建一个高可用的百万级 Token 吞吐系统。
|
11月前
|
人工智能 NoSQL 关系型数据库
阿里云试用点是什么?如何免费获取解决方案试用点?
阿里云试用点是用于免费体验解决方案的权益单位,完成实名认证可领100点,有效期1年。每完成一个解决方案试用可再获10点,最多10次。试用点可用于抵扣AI、数据库、迁移等场景资源消耗,助力用户零成本验证技术方案。
|
JavaScript API 微服务
探索现代后端开发:关键技术和最佳实践
【10月更文挑战第6天】探索现代后端开发:关键技术和最佳实践
|
Web App开发 前端开发 JavaScript
JavaScript Web Full Stack 全栈开发者路线及内容推荐
本文详细介绍了一条全面的JavaScript全栈开发者学习路径,涵盖基础知识、前端和后端开发、数据库与API、MERN Stack与React Native、工程化与部署、安全与测试、未来趋势等方面。推荐了HTML5、CSS3、JavaScript(ES6+)、Node.js、React.js、Vue.js、Svelte、Tailwind CSS、Web Components等关键技术,并提供了丰富的书籍、博主和在线资源。此外,还回顾了JavaScript的历史,并推荐了多个活跃的社区和平台,帮助开发者紧跟技术前沿。
|
Python 机器学习/深度学习 人工智能
手把手教你从零开始构建并训练你的第一个强化学习智能体:深入浅出Agent项目实战,带你体验编程与AI结合的乐趣
【10月更文挑战第1天】本文通过构建一个简单的强化学习环境,演示了如何创建和训练智能体以完成特定任务。我们使用Python、OpenAI Gym和PyTorch搭建了一个基础的智能体,使其学会在CartPole-v1环境中保持杆子不倒。文中详细介绍了环境设置、神经网络构建及训练过程。此实战案例有助于理解智能体的工作原理及基本训练方法,为更复杂应用奠定基础。首先需安装必要库: ```bash pip install gym torch ``` 接着定义环境并与之交互,实现智能体的训练。通过多个回合的试错学习,智能体逐步优化其策略。这一过程虽从基础做起,但为后续研究提供了良好起点。
2890 4
手把手教你从零开始构建并训练你的第一个强化学习智能体:深入浅出Agent项目实战,带你体验编程与AI结合的乐趣
|
负载均衡 数据库 开发工具
|
存储 缓存 数据挖掘
数据库冗余
【7月更文挑战第28天】数据库冗余
1134 8