簡體   English   中英

How to call AZURE DEVOPS rest API in the water fall dialog built using C# BOT Framework SDK V4?

[英]How to call AZURE DEVOPS rest API in the water fall dialog built using C# BOT Framework SDK V4?

我有通過 C# 使用 BOT 框架 SDK V4 創建的 web 頻道聊天機器人。 它有多個瀑布對話框,根據在主對話框中選擇的選項執行一組操作。

在其中一個對話框中,我的要求是用戶輸入一些數據,然后使用該數據在我的 AZURE DEvOps 項目中創建一個類型任務的工作項以進行跟蹤。 我能夠成功地從用戶那里獲取數據,但是在 devops 中創建 WORK ITEM 時我遇到了問題。 我從我這邊嘗試了幾件事,但是如果通過創建單獨的 C# 控制台應用程序來執行它們,它們就可以工作,但是如果我嘗試通過安裝相關的 NuGET 包或添加參考程序集來使用相同的代碼,我會收到錯誤或警告。

嘗試1:在BOTCode中使用TFS相關的nuget包:

如果我嘗試通過安裝與 TFS 擴展客戶端相關的 Nuget 軟件包來使用代碼,那么在安裝期間它會顯示兼容性警告,並且我的參考程序集部分有一個警告符號。 通過我沒有嘗試在我的對話框 class 中執行這段代碼,因為雖然它可能有工作但我不確定在發布到 AZURE 后它可能會導致問題。

現在來試試2試試2:在BOT代碼中使用AZURE DEVOPS REST API:

我已經編寫了用於調用 REST API 的代碼,因為我在我的對話框 class 中使用了以下代碼:

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 序列化器 = new JavaScriptSerializer();

This needs a assembly reference called: system.web.extensions.dll to be used i have added this reference by browsing this DLL ie using System.Web.Script.Serialization;

現在,當我執行此操作時,我得到如下異常:異常捕獲:無法加載文件或程序集'System.Web.Extensions,版本 = 4.0.0.0,文化 = 中性,PublicKeyToken = 31bf3856ad364e35'。 不應加載引用程序集以供執行。 它們只能在 Reflection-only loader 上下文中加載。 (HRESULT 異常:0x80131058)

當我在博客中搜索此錯誤的修復程序時,他們說要從 csproj 文件中刪除與 targetframework 相關的標簽,這應該可以工作,但這會產生構建錯誤,指出未找到 targetframework。

這就是我卡住的地方。 我還附上了我未修改的 csproj 文件以供參考。

請注意,我在 Azure 中創建了一個基本的回聲機器人,然后下載了這個基本的機器人,並根據我的要求在這個基本的機器人之上從頭開始構建我自己的水對話。

請幫助我解除阻止問題,因為我嘗試了一些不起作用的方法。 如果這無法實現,請讓我知道,以便我可以與我的團隊溝通。 在此先感謝您的幫助。

我還嘗試使用取自博客的以下代碼,但這也不起作用。 由於我被阻止,我發布此查詢以尋求幫助:

 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>

我正在關閉這個查詢,因為我通過嘗試帖子中的想法得到了這個想法。 它奏效了。

因此,正如我在我的 Try 2 代碼中解釋的那樣,將數據轉換為 JavascriptSerializer object 到稱為 JSON 的字符串,作為從行開始的給定代碼:

JavaScriptSerializer serializer = new JavaScriptSerializer();

我沒有這樣做,而是使用上面給出的博客創建了一個 class ; 並獲取具有變量的屬性

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>;

如上面給出的博客鏈接所示,將數據添加到 class 和數組,然后最后使用下面的代碼行將其轉換為 Json 並存儲到變量中:

字符串 wijsondata = JsonConvert.SerializeObject(wiarray);

並使用我原來的問題中給出的 try 2 塊的剩余部分代碼,稱為 post 方法,因為它現在不是 Json 變量,我通過了 wijsondata

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

它奏效了。

感謝您在博客或這篇文章或外部文章中提供的所有幫助和想法,並對可能給任何人造成的任何不便表示歉意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM