Giter Site home page Giter Site logo

cypress-dotnet-sdk's Introduction

Cypress .NET SDK

Installing the SDK

Option 1: DLL

  • Copy cypress-dotnet-sdk.dll and cypress-dotnet-sdk.dll.config to a known location
  • Add the DLL as a reference to your project

Option 2: Import project

  • Copy the whole repository, and import the cypress-dotnet-sdk.csproj as an existing project

Option 3: Re-generate code

Required libraries:

Nuget:

  • Newtonsoft.Json
  • RAML.Api.Core (v0.10.1)
  • Microsoft ASP.NET Web API 2.2 Client Libraries (Microsoft.AspNet.WebApi.Client)

Assemblies references:

  • System.Net.Http
  • System.Net.Http.Formatting

Using the SDK

Sample Code

Connecting to the Server

System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.BaseAddress = new Uri("http://cypress-location.url/");
var auth = System.Text.Encoding.ASCII.GetBytes("username:password");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(auth));
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

CypressClient client = new CypressClient(httpClient);

Getting the Cypress Version (Endpoint now available in Cypress 6.2)

var cypress_version = await client.CypressVersion.Get();
Console.WriteLine(cypress_version.Content.Version);

Validating a QRDA file (Endpoint now available in Cypress 6.2)

string year = "2022";
string qrda_type = "qrdaIII";
string implementation_guide = "hl7";

var postContent = new MultipartFormDataContent();

var fileContent = File.ReadAllBytes("C:\\Users\\jsmith\\Desktop\\Sample_QRDA_III.xml");
postContent.Add(new ByteArrayContent(fileContent), "file", "Sample_QRDA_III.xml");

var submitQrdaValidationRequest =
	new QrdaValidationsPostRequest(new QrdaValidationsUriParameters { Year = year, Qrda_type = qrda_type, Implementation_guide = implementation_guide },
		postContent);

var validationResults = await client.QrdaValidations.Post(submitQrdaValidationRequest);
var errorlist = validationResults.Content.QrdaValidationsPostCreatedResponseContent.Execution_errors;

foreach (ExecutionErrors error in errorlist)
{
	Console.WriteLine(error.Message);
}

Creating a Vendor

var vendorCreateResponse =
	await client.Vendors.Post(new VendorsPostRequestContent { Name = "Vendor Name" });

if (vendorCreateResponse.StatusCode == HttpStatusCode.Created)
{
	// vendor created successfully
	string vendorID = vendorCreateResponse.RawHeaders.Location.Segments.Last();
} else if ((int) vendorCreateResponse.StatusCode == 422)
{
    var errors = vendorCreateResponse.Content.VendorsPost422ResponseContent;
    foreach (var error in errors.Errors)
    {
        Console.WriteLine("{0}: {1}", error.Field, string.Join(", ", error.Messages));
    }
}

Creating a Product

var bundles = client.Bundles.Get().Result.Content;

// assume for now there's only 1 bundle

string bundleID = bundles[0].Links.First(link => link.Rel == "self").Href.Split('/').Last();

var measures = client.Bundles.Measures.Get(bundleID).Result.Content;

IList<string> measureIDs = new List<string>();
measureIDs.Add(measures[2].Hqmf_id);
measureIDs.Add(measures[3].Hqmf_id);
measureIDs.Add(measures[5].Hqmf_id);

string newProductName = "Example Product Name";

var product = new VendorsIdProductsPostRequestContent { Name = newProductName, C1_test = true, Bundle_id = bundleID, Measure_ids = measureIDs };

var productCreateResponse = await client.Vendors.Products.Post(product, vendorID);
if (productCreateResponse.StatusCode == HttpStatusCode.Created)
{
	// product created successfully
	string productID = productCreateResponse.RawHeaders.Location.Segments.Last();
} else if ((int) productCreateResponse.StatusCode == 422)
{
    var errors = productCreateResponse.Content.VendorsIdProductsPost422ResponseContent;
    foreach (var error in errors.Errors)
    {
        Console.WriteLine("{0}: {1}", error.Field, string.Join(", ",error.Messages));
    }
    return;
}

Getting Patients for a Product Test

var allProductTests = client.ProductsProductIdProductTests.Get(productID).Result.Content;

foreach (var pTest in allProductTests)
{
	string productTestID = pTest.Links.First(link => link.Rel == "self").Href.Split('/').Last();

	var prodTest = client.ProductsProductIdProductTests.GetById(productTestID, productID).Result.Content; ;

	while (prodTest.State != "ready")
	{
		Thread.Sleep(10000);

		prodTest = client.ProductsProductIdProductTests.GetById(productTestID, productID).Result.Content;
	}

	string patientsURL = prodTest.Links.First(link => link.Rel == "patients").Href;

	string patientsFile = "C:\\<location_to_save_file>";

	using (var wc = new WebClient())
	{
		wc.BaseAddress = httpClient.BaseAddress.ToString();
		wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", Convert.ToBase64String(auth));
		wc.DownloadFile(patientsURL, patientsFile);
	}

Uploading Results Files

var tasks = client.ProductTestsProductTestIdTasks.Get(productTestID).Result.Content;

foreach (var t in tasks)
{
	string taskID = t.Links.First(link => link.Rel == "self").Href.Split('/').Last(); ;

	var task = client.ProductTestsProductTestIdTasks.GetById(taskID, productTestID).Result.Content;

	var postContent = new MultipartFormDataContent();

	var fileContent = File.ReadAllBytes("C:\\Users\\jsmith\\Desktop\\Sample_QRDA_III.xml");
	postContent.Add(new ByteArrayContent(fileContent), "results", "Sample_QRDA_III.xml");

	var submitTestExecutionRequest =
		new TasksTaskIdTestExecutionsPostRequest(new TasksTaskIdTestExecutionsUriParameters { Task_id = taskID },
			postContent);

	var testExecution = await client.TasksTaskIdTestExecutions.Post(submitTestExecutionRequest);
	var testExecutionID = testExecution.RawHeaders.Location.Segments.Last();

Viewing Test Execution Status

var testEx = await client.TasksTaskIdTestExecutions.GetById(testExecutionID, taskID);

var testExResult = testEx.Content;

while (testExResult.State != "passed" && testExResult.State != "failed")
{
	Console.WriteLine(testExResult.State);
	Thread.Sleep(10000);
	var res = client.TasksTaskIdTestExecutions.GetById(testExecutionID, taskID).Result;
	testExResult = res.Content;
}

if (testExResult.Execution_errors != null)
{
	foreach (var error in testExResult.Execution_errors)
	{
		Console.WriteLine(error.Message);
	}
}

License

Copyright 2016 The MITRE Corporation

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

cypress-dotnet-sdk's People

Contributors

dczulada avatar dehall avatar laclark22 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

kukuandroid

cypress-dotnet-sdk's Issues

Upload Results throws error on file that works with manual upload

Hello-
Retooled our unit test using the cypress-dotnet.dll update against Cypress 6.2.2.1 instance and getting error in response from call _client.TasksTaskIdTestExecutions.Post().
Error message from 422 Response: "results invalid file upload. upload a zip for QRDA Category I or XML for QRDA Category III"

Same file uploaded directly thru Cypress works fine. Attached example file.

Also confirmed this code works against a different Cypress instance running v 6.1.1 with successful result upload.

Method for upload below, very similiar to the documented guidance.

        internal async void UploadResults(string vendorID, string productID, string resultsPath, QRDAFileType qrdaType, List<string> measures)
        {
            var allProductTests = _client.ProductsProductIdProductTests.Get(productID).Result.Content;

            foreach (var productTest in allProductTests.Where(t => t.Type.Equals("measure", StringComparison.CurrentCultureIgnoreCase)))
            {
                string productTestID = ParseLinkToID(productTest.Links);
                var prodTest = _client.ProductsProductIdProductTests.GetById(productTestID, productID).Result.Content; 
                while (prodTest.State != "ready")
                {
                    Thread.Sleep(10000);

                    prodTest = _client.ProductsProductIdProductTests.GetById(productTestID, productID).Result.Content;
                }
                if (measures.Contains(prodTest.Measure_id) == false) continue;
                var cmsid = prodTest.Cms_id;
                var testType = qrdaType == QRDAFileType.QRDA1ZIP ? "C1" : "C2";
                var tasks = _client.ProductTestsProductTestIdTasks.Get(productTestID).Result.Content;
                var task = tasks.Where(t => t.Type == testType).FirstOrDefault();
                if (task != null)
                {
                    string taskID = ParseLinkToID(task.Links); // t.Links.First(link => link.Rel == "self").Href.Split('/').Last(); ;
                    var postContent = new MultipartFormDataContent();

                    var testFileName = string.Format("{0}.cpm.{1}.{2}", cmsid,
                        (qrdaType == QRDAFileType.QRDA3XML ? "Q3" : "Q1"),
                        (qrdaType == QRDAFileType.QRDA3XML ? "xml" : "zip"));
                    string[] files = Directory.GetFiles(Path.Combine(resultsPath), testFileName);
                    foreach (string file in files)
                    { 
                        var fileName = Path.GetFileName(file);
                        var fileContent = File.ReadAllBytes(file);
                        var byteContent = new ByteArrayContent(fileContent);
                        byteContent.Headers.Add("Content-Type", "application/octet-stream");
                        postContent.Add(byteContent, "results", fileName);
                        var submitTestExecutionRequest =
                            new TasksTaskIdTestExecutionsPostRequest(new TasksTaskIdTestExecutionsUriParameters { Task_id = taskID },
                                postContent);

                        Debug.WriteLine("Uploading results for test " + prodTest.Name + " file " + fileName);

                        var testExecution = _client.TasksTaskIdTestExecutions.Post(submitTestExecutionRequest).Result;
                        if ((int)testExecution.StatusCode == 422)
                        {
                            var errors = testExecution.Content.TasksTaskIdTestExecutionsPost422ResponseContent.Errors;
                            foreach (var error in errors) Debug.WriteLine($"Upload response error={error.Field} {string.Join(", ", error.Messages)}");
                        }
                        else
                        { var testExecutionID = testExecution.RawHeaders.Location.Segments.Last(); }

                    }
                }
            }
        }

Thank you.


``
[CMS2v11.CPM.Q1.zip](https://github.com/projectcypress/cypress-dotnet-sdk/files/7961981/CMS2v11.CPM.Q1.zip)
`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.