DDD模型领域WF到领域层(十五)

时间:2023-03-08 23:36:33
DDD模型领域WF到领域层(十五)

实现超市的结算系统:

计算相应的优惠方式的接口

 public interface ICompute
{
double GetResultTotalMoney(double TotalMoney);
}

打折的算法类:

 public class DisCount : ICompute
{
private double discount;
public DisCount(double discount)
{
this.discount = discount;
} public double GetResultTotalMoney(double TotalMoney)
{
return TotalMoney *discount;
}
}

买多少送多少的类:

  public class ReturnBack : ICompute
{
private double musttotalmoney;
private double returnmoney;
public ReturnBack(double musttotalmoney,double returnmoney)
{
this.musttotalmoney = musttotalmoney;
this.returnmoney = returnmoney;
}
public double GetResultTotalMoney(double TotalMoney)
{
return TotalMoney - (TotalMoney / musttotalmoney) * returnmoney;
}
}

购买的业务逻辑:

 public class BuyBusinessService
{
ICompute icompute;
public double GetReturnMoney(string type,double totalmoney)
{
switch(type)
{
case "打三折":
icompute = new DisCount(0.3);
break;
case "满300送100":
icompute = new ReturnBack(300, 100);
break;
default:
icompute = new DisCount(1);
break;
} return getreturnbacktotalmoney(totalmoney);
} private double getreturnbacktotalmoney(double totalmoney)
{
return icompute.GetResultTotalMoney(totalmoney);
}
}

利用工作流的实现:(新建活动)

DDD模型领域WF到领域层(十五)

新建代码活动:MustReturnActivity

 public sealed class MustReturnActivity : CodeActivity
{
// 定义一个字符串类型的活动输入参数
//总价
public InOutArgument<double> TotalMoney { get; set; }
//折扣率
public InArgument<double> MustMoney { get; set; }
//返回的总价
public InArgument<double> Returnmoney { get; set; } protected override void Execute(CodeActivityContext context)
{
double mustmoney = context.GetValue(MustMoney);
double totalmoney = context.GetValue(TotalMoney);
double returnmoney = context.GetValue(Returnmoney);
ReturnBack returnback =
new ReturnBack(mustmoney,returnmoney);
context.SetValue(TotalMoney, returnback.GetResultTotalMoney(totalmoney)); }
}

DiscountAcitivity活动:

   public sealed class DiscountAcitivity : CodeActivity
{
// 定义一个字符串类型的活动输入参数
public InOutArgument<double> TotalMoney { get; set; }
public InArgument<double> Discount { get; set; } protected override void Execute(CodeActivityContext context)
{
double discount = context.GetValue(Discount);
double totalmoney = context.GetValue(TotalMoney); DisCount discountcls =
new DisCount(discount);
context.SetValue(TotalMoney, discountcls.GetResultTotalMoney(totalmoney)); }
}
}

窗体层的代码:

 public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} double totalmoney;
private void button1_Click(object sender, EventArgs e)
{
totalmoney = totalmoney + double.Parse(textBox1.Text) * double.Parse
(textBox2.Text);
listView1.Items.Add("单价:" + textBox1.Text + " 数量:" + textBox2.Text);
} private void button2_Click(object sender, EventArgs e)
{
//BuyBusinessService bs =
// new BuyBusinessService();
//label3.Text =
// bs.GetReturnMoney(comboBox1.SelectedItem.ToString(), totalmoney).ToString(); Dictionary<string, object> dics =
new Dictionary<string, object>();
dics.Add("Type", comboBox1.SelectedItem.ToString());
dics.Add("TotalMoney", totalmoney);
WorkflowApplication instance =
new WorkflowApplication(new CashWorkflow(),dics); //输出完成时
instance.Completed =
new Action<WorkflowApplicationCompletedEventArgs>(workflowcompleted); } private void workflowcompleted(WorkflowApplicationCompletedEventArgs args)
{
//label3.Text = args.Outputs["TotalMoney"].ToString();
SetTotalMoney(args.Outputs["TotalMoney"].ToString());
} delegate void SetTotalmoneyCallBack(string totalmoney); private void SetTotalMoney(string totalmoney)
{
if(this.label3.InvokeRequired)
{
SetTotalmoneyCallBack callbacks =
new SetTotalmoneyCallBack(SetTotalMoney);
this.label3.Invoke(callbacks, new object[] { totalmoney });
}
label3.Text = totalmoney;
}
}

添加事务:

创建Employee 表给Age 字段添加约束:

ALTER TABLE Employee
ADD CONSTRAINT ck_Employee_Age CHECK(age BETWEEN 20 AND 60)

创建:EmployeeInfoCreateActivity

  public sealed class EmployeeInfoCreateActivity : CodeActivity
{
// 定义一个字符串类型的活动输入参数
//定义输入的参数
public InArgument<string> Name { get; set; }
public InArgument<int> Age { get; set; } // 如果活动返回值,则从 CodeActivity<TResult>
// 并从 Execute 方法返回该值。
TestContainer dbcontext =
new TestContainer();
protected override void Execute(CodeActivityContext context)
{
var name = context.GetValue(Name);
var age = context.GetValue(Age);
var employee = new Employee
{
Id = Guid.NewGuid(),
Name = name,
Age = age
};
dbcontext.Set<Employee>().Add(employee);
dbcontext.SaveChanges();
}
}

未处理的异常:

 static void Main(string[] args)
{
WorkflowApplication instance =
new WorkflowApplication(new Workflow1());
instance.Completed =
new Action<WorkflowApplicationCompletedEventArgs>(workflowcompleted);
//未处理的异常
instance.OnUnhandledException =
new Func<WorkflowApplicationUnhandledExceptionEventArgs, UnhandledExceptionAction>(unhandledexception);
instance.Aborted =
new Action<WorkflowApplicationAbortedEventArgs>(abortexception);
instance.Run();
Console.ReadLine();
} static void workflowcompleted(WorkflowApplicationCompletedEventArgs args)
{
Console.WriteLine("流程完成状态:"+args.CompletionState);
} static UnhandledExceptionAction unhandledexception(WorkflowApplicationUnhandledExceptionEventArgs args)
{
Console.WriteLine("未处理异常:" + args.UnhandledException.Message);
return UnhandledExceptionAction.Terminate;
} static void abortexception(WorkflowApplicationAbortedEventArgs args)
{
Console.WriteLine(args.Reason);
}

添加事务的引用:using System.Transactions;

TranasctionControllerActivity

  public sealed class TranasctionControllerActivity : NativeActivity
{
/// <summary>
/// 控制事务的处理
/// </summary>
/// <param name="context"></param>
protected override void Execute(NativeActivityContext context)
{
//对工作流中事务进行的访问
RuntimeTransactionHandle transactionhandle
= new RuntimeTransactionHandle();
//获取事务中先关的信息
transactionhandle = context.Properties.Find(transactionhandle.ExecutionPropertyName)
as RuntimeTransactionHandle;
var transaction = transactionhandle.GetCurrentTransaction(context);
transaction.Rollback(new Exception("内部手工回滚"));
transaction.TransactionCompleted += Transaction_TransactionCompleted;
} private void Transaction_TransactionCompleted(object sender, TransactionEventArgs e)
{
Console.WriteLine("事务的隔离级别:"+e.Transaction.IsolationLevel);
Console.WriteLine("事务创建时间:" + e.Transaction.TransactionInformation.CreationTime);
}
}

调用外部的组件:

写一个外部调用的类库:

   public class Compute
{
public static int Add(int a,int b)
{
return a + b;
} public int AddI(int a,int b)
{
return a + b + 100;
} public string AddString(params string[] s)
{
string str="";
for(int i=0;i<s.Length;i++)
{
str = str + s[i];
}
return str;
} public void ChangeC(out int c)
{
c = 500;
} public int AddT<T>(T a,T b)
{
return int.Parse(a.ToString()) + int.Parse(b.ToString());
}
}

拖入一个Sequence放入InvokeMethod调用方法:

DDD模型领域WF到领域层(十五)

会签的工作流程演示代码:

  public sealed class ApprovalActivity : NativeActivity
{
public InArgument<string> BookMarkName { get; set; }
public OutArgument<string> ApprovalResult { get; set; } protected override bool CanInduceIdle
{
get { return true; }
}
protected override void Execute(NativeActivityContext context)
{
var bookmarkname = context.GetValue(BookMarkName);
context.CreateBookmark(bookmarkname,callback);
} private void callback(NativeActivityContext context,Bookmark bookmark,object obj)
{
context.SetValue(ApprovalResult, obj.ToString()); } }
 public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} WorkflowApplication instance;
private void button1_Click(object sender, EventArgs e)
{
instance = new WorkflowApplication(new Activity1());
instance.Idle =
new Action<WorkflowApplicationIdleEventArgs>(workflowidle);
//完成
instance.Completed =
new Action<WorkflowApplicationCompletedEventArgs>(workflowcompleted);
instance.Run();
} private void workflowidle(WorkflowApplicationIdleEventArgs args)
{
if(instance!=null)
{
if(args.Bookmarks.Count(p=>p.BookmarkName.Contains("BookMark1"))!=0)
{
SetLabel("等待审批", label1);
}
}
}
private void workflowcompleted(WorkflowApplicationCompletedEventArgs args)
{
SetLabel("第一位审批人:"+args.Outputs["ApprovalResult1"].ToString()+
" 第二位审批人:" + args.Outputs["ApprovalResult2"].ToString()+
" 第二位审批人:" + args.Outputs["ApprovalResult3"].ToString(), label2);
} delegate void SetLabelCallBack(string labstring, Label label);
private void SetLabel(string labstring,Label label)
{
SetLabelCallBack callback =
new SetLabelCallBack(SetLabel);
if(label.InvokeRequired)
{
label.Invoke(callback, new object[] { labstring, label });
}
label.Text = labstring;
} private void button2_Click(object sender, EventArgs e)
{
ResumeActivity("BookMark1", comboBox1.SelectedItem.ToString());
} private void ResumeActivity(string bookmarkname,string cb)
{
instance.ResumeBookmark(bookmarkname, cb);
} private void button3_Click(object sender, EventArgs e)
{
ResumeActivity("BookMark2", comboBox2.SelectedItem.ToString());
} private void button4_Click(object sender, EventArgs e)
{
ResumeActivity("BookMark3", comboBox3.SelectedItem.ToString());
}
}

DDD模型领域WF到领域层(十五)