我正在尝试使用C#使用命令行步骤创建SQL代理作业。Web API正在调用包含该方法的类,当逐步浏览代码时,没有任何错误,所有变量都有值,但是在查看我的SQL实例时并未创建作业(我正在运行SQL Server 2016的本地实例(。我在同一类中有2种方法;createJob((和addCommandLinestep((。目前的源代码看起来像这样:
类方法
public SQLAgentJobHelper CreateJob(string JobName)
{
// Create Job
foreach (Job job in jobServer.Jobs)
{
if (job.Name.Equals(JobName))
{
job.Drop();
break;
}
}
server.ConnectionContext.BeginTransaction();
job = new Job(jobServer, JobName);
job.Create();
job.ApplyToTargetServer(server.Name);
server.ConnectionContext.CommitTransaction();
return this;
}
public void AddCommandLineStep(string StepName, string Executable, string CommandLine, List<NameValue> paramList, bool isLast = false)
{
try
{
if (job == null)
throw new Exception("First call CreateJob before adding steps");
var jobStep = new JobStep(job, StepName);
var paramString = CommandLine;
paramList.ForEach(param => paramString += $"/{param.Name} {param.Value} ");
jobStep.Command = $""{Executable}" {paramString}";
jobStep.SubSystem = AgentSubSystem.CmdExec;
if (isLast)
jobStep.OnSuccessAction = StepCompletionAction.QuitWithSuccess;
else
jobStep.OnSuccessAction = StepCompletionAction.GoToNextStep;
jobStep.OnFailAction = StepCompletionAction.QuitWithFailure;
jobStep.Create();
lastJobStep = jobStep;
}
catch (Exception ex)
{
}
}
API调用
jobHelper.CreateJob(jobName)
jobHelper.AddCommandLineStep("Step 1", @"C:Program FilesMicrosoft SQL Server130DTSBinnDTEXEC.exe", @"C:SSISCopyDataView.dtsx", Enumerable.Empty<NameValue>().ToList());
我知道空的捕获物,路径将被变量替换,这只是使代码根据需要运行的粗略尝试。
[update]
我可以肯定地说,在进行单元测试时,我可以在同一SQL实例上创建作业。在对这个问题进行了更详细的了解之后,我看到大约有。解决方案中的30个项目。另一个项目中是否有一些DLL导致创建工作失败?
API现在正常工作!在这种情况下,有必要明确完成API交易。使用TransactionsCope名称空间和.complete((方法,该代码现在类似于:
using (var txscope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
using (SQLAgentJobHelper jobHelper = new SQLAgentJobHelper(ServerConnection))
{
jobHelper.CreateJob(jobName)
jobHelper.AddCommandLineStep("Step 1", @"C:Program FilesMicrosoft SQL Server130DTSBinnDTEXEC.exe", C:SSISCopyDataView.dtsx", Enumerable.Empty<NameValue>().ToList());
}
txscope.Complete();
return Ok(1);
}
catch (Exception ex)
{
txscope.Dispose();
return Ok(ex.StackTrace.ToString());
}
}