如何在使用C#BOT Framework SDK V4构建的瀑布对话框中调用AZURE DEVOPS rest API?

问题描述 投票:1回答:1

我拥有使用BOT Framework SDK V4通过C#创建的网络频道聊天机器人。它具有多个瀑布对话框,这些对话框根据在主对话框中选择的选项执行一组操作。

在对话框中,我的要求是用户输入一些数据,然后使用该数据,我应该在我的AZURE DEvOps项目中创建一个“工作项类型”任务以进行跟踪。我可以成功地从用户那里获取数据,但是在devops中创建WORK ITEM时却遇到了问题。我已经尝试了几件事,但是如果通过创建单独的C#控制台应用程序来执行,它们会起作用,但是如果我尝试通过安装相关的NuGET包或添加参考程序集来使用相同的代码,则会收到错误或警告。

尝试1:在BOTCode中使用与TFS相关的nuget包:

如果我尝试通过安装与TFS扩展客户端相关的Nuget软件包来使用代码,则在安装过程中会显示兼容性警告和我的参考程序集部分带有警告符号。通过我没有尝试在我的对话框类中执行这段代码,因为虽然它可能有工作,但是我不确定发布到AZURE后它可能会引起问题。

现在来尝试2尝试2:使用BOT代码使用AZURE DEVOPS REST API:

我已经编写了用于调用REST API的代码,我在Dialog类中使用了以下代码:

string token = "toekn";
        string type = "Task";
        string organization = org
        string project = "Project";
        int workitemid = 0;
        string url = $"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/${type}?api-version=5.0";

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(new object[]{new
        {
            op = "add",
            path = "/fields/System.Title",
            value = "Testing Workitem creation through API" 
        },
        new {
            op = "add",
            path = "/fields/System.Description",
            value = "Model Request ID#" + requestid + " from: "+ name + " requested from ChatBot" 
        },

        new {
            op = "add",
            path = "/fields/Priority",
            value = 1
        }

        });

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token))));

            var method = new HttpMethod("POST");

            var request = new HttpRequestMessage(method, url)
            {
                Content = new StringContent(json, Encoding.UTF8,
                    "application/json-patch+json")
            };


            var sendresult = client.SendAsync(request).Result;
            var result = sendresult.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Completed!");
            dynamic workitemdata = JsonConvert.DeserializeObject(result);
            workitemid = workitemdata.id;                
        };

现在,如果您在上面的代码中观察到一种方法-

JavaScriptSerializer序列化器=新的JavaScriptSerializer();

这需要一个称为:system.web.extensions.dll的程序集引用,我已经通过浏览此DLL来添加此引用,即使用System.Web.Script.Serialization;

现在执行此操作时,出现如下异常:捕获到异常:无法加载文件或程序集'System.Web.Extensions,版本= 4.0.0.0,区域性=中性,PublicKeyToken = 31bf3856ad364e35'。参考程序集不应该加载执行。它们只能在“仅反射”加载器上下文中加载。 (来自HRESULT的异常:0x80131058)

[当我在this博客中搜索此错误的修复程序时,他们说要从csproj文件中删除与targetframework相关的标签,该标签应能工作,但这会产生表明找不到targetframework的构建错误。

这是我卡住的地方。我还附上未经修改的csproj文件,以供参考。

[请注意,我已经在Azure中创建了一个基本的echo机器人,然后下载了该基本bot并根据需要在该基本bot之上从头开始构建了自己的水对话框。

[当我尝试了一些无效的操作后,请帮助我解除阻止该问题的权限。如果无法实现,请告诉我,以便我可以与团队沟通。在此先感谢您的帮助。

我也尝试使用以下来自this博客的代码,这也没有用。由于被阻止,我正在发布此查询以寻求帮助:

 static void Main(string[] args)
{
    CreateWorkItem();
}


public static void CreateWorkItem()
{
    string _tokenAccess = "************"; //Click in security and get Token and give full access https://azure.microsoft.com/en-us/services/devops/
    string type = "Bug";
    string organization = "type your organization";
    string proyect = "type your proyect";
    string _UrlServiceCreate = $"https://dev.azure.com/{organization}/{proyect}/_apis/wit/workitems/${type}?api-version=5.0";
    dynamic WorkItem = new List<dynamic>() {
            new
            {
                op = "add",
                path = "/fields/System.Title",
                value = "Sample Bug test"
            }
        };

    var WorkItemValue = new StringContent(JsonConvert.SerializeObject(WorkItem), Encoding.UTF8, "application/json-patch+json");
    var JsonResultWorkItemCreated = HttpPost(_UrlServiceCreate, _tokenAccess, WorkItemValue);
}


public static string HttpPost(string urlService, string token, StringContent postValue)
{
    try
    {
        string request = string.Empty;
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token))));
            using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(new HttpMethod("POST"), urlService) { Content = postValue })
            {
                var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
                if (httpResponseMessage.IsSuccessStatusCode)
                    request = httpResponseMessage.Content.ReadAsStringAsync().Result;
            }
        }
        return request;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

下面是csproj文件中的数据供参考:

 <Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.Bot.Builder.AI.QnA" Version="4.6.0" />
    <PackageReference Include="Microsoft.Bot.Builder.Dialogs" Version="4.6.0" />
    <PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.6.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="System.Data.SqlClient" Version="4.7.0" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="System.Web.Extensions">
      <HintPath>..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Web.Extensions.dll</HintPath>
    </Reference>
  </ItemGroup>

  <ItemGroup>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <Import Project="PostDeployScripts\IncludeSources.targets" Condition="Exists('PostDeployScripts\IncludeSources.targets')" />
  <Import Project="..\PostDeployScripts\IncludeSources.targets" Condition="Exists('..\PostDeployScripts\IncludeSources.targets')" />

</Project>
c# azure-devops botframework chatbot azure-devops-rest-api
1个回答
0
投票

我正在尝试通过post提出的主意,因此我正在关闭此查询。并且有效。

因此,正如我在Try 2代码中所解释的那样,将数据转换为JavascriptSerializer对象插入到称为JSON的字符串中,该代码从以下行开始:

JavaScriptSerializer serializer = new JavaScriptSerializer();

不是执行此操作,而是使用上面设置的博客创建了一个类,该类已设置;并获得带有变量的属性,如

OP路径值

 public class WorkItemData
    {
        public string op { get; set; } 
        public  string path { get; set; }
        public  string value { get; set; }
    }

在我实际的机器人代码中创建了一个列表变量:

List<WorkItemData> wiarray= new List<WorkItemData>;

将数据添加到类和数组中,如上面给出的博客链接所示,然后最终使用下面的代码行将其转换为Json并存储到变量中:

string wijsondata = JsonConvert.SerializeObject(wiarray);

并且使用剩下的代码,尝试在我原来的问题post 2中给出的try 2块,因为它现在代替了我通过wijsondata传递的Json变量

Content = new StringContent(wijsondata,Encoding.UTF8,“ application / json-patch + json”)

并且有效。

感谢博客,这篇文章或外部帖子中提供的所有帮助和想法,对于由此给任何人带来的任何不便,我们深表歉意。

© www.soinside.com 2019 - 2024. All rights reserved.