示例#1
0
        public void MakeInquiry_GivenAPartyId_ShouldReturnAPartyRelationshipInquiryResponse()
        {
            var stubApi     = Substitute.For <IAPI>();
            var stubLazyApi = new Lazy <IAPI>(() => stubApi);
            var credentials = new Credentials()
            {
                BaseUrl  = "https://some.bank.or.cu/api",
                Username = "******",
                Password = "******",
                Facility = "validFacility"
            };

            var session = new Session()
            {
                UserName       = "******",
                Password       = "******",
                Authentication = "CCM"
            };

            var fakeSessionResponse = JsonConvert.DeserializeObject <SessionResponse>("{'authToken':'cc6320b637beb3949d522d2c32341fe5'}");

            stubLazyApi.Value.Post <Session, SessionResponse>(session).Returns(fakeSessionResponse);
            var lazyApiValue = stubLazyApi.Value.Post <Session, SessionResponse>(session);

            string _authToken = fakeSessionResponse?.AuthToken;

            string fakeLogString = $"GetAuthToken(Session) _authToken = {_authToken}";

            var proxy = new RestProxy(stubLazyApi, credentials);

            proxy.MakeInquiry(new PartyRelationshipsInquiry());
        }
示例#2
0
 internal DynamicRestClient(string baseUrl, RestProxy parent, string name, DynamicRestClientDefaults defaults, Func <HttpRequestMessage, CancellationToken, Task> configure)
     : base(parent, name)
 {
     _baseUrl          = baseUrl;
     _defaults         = defaults ?? new DynamicRestClientDefaults();
     _configureRequest = configure;
 }
示例#3
0
        public async Task EscapeParameterName()
        {
            var client = new RestClient("http://congress.api.sunlightfoundation.com");

            client.AddDefaultHeader("X-APIKEY", CredentialStore.Key("sunlight"));

            dynamic proxy = new RestProxy(client);

            // this is the mechanism by which parameter names that are not valid c# property names can be used
            var parameters = new Dictionary <string, object>()
            {
                { "chamber", "senate" },
                { "history.house_passage_result", "pass" }
            };

            dynamic result = await proxy.bills.get(paramList : parameters);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.results != null);
            Assert.IsTrue(result.results.Count > 0);

            foreach (dynamic bill in result.results)
            {
                Assert.AreEqual("senate", (string)bill.chamber);
                Assert.AreEqual("pass", (string)bill.history.house_passage_result);
            }
        }
示例#4
0
        internal RestSharpProxy(IRestClient client, RestProxy parent, string name)
            : base(parent, name)
        {
            Debug.Assert(client != null);

            _client = client;
        }
        // [Test]
        public void InsertInventoryItem2()
        {
            string xml =
                @"<insertInventoryItem>
<inventoryItem uid=""0""> 
<code>LS3900</code>
<description>13-foot Heavy Duty Light  Stand</description> 
<isActive>true</isActive> 
<notes></notes> 
<isInventoried></isInventoried> 
<assetAccountUid></assetAccountUid> 
<stockOnHand></stockOnHand> 
<currentValue></currentValue> 
<isBought>false</isBought> 
<purchaseExpenseAccountUid></purchaseExpenseAccountUid> 
<purchaseTaxCode></purchaseTaxCode> 
<minimumStockLevel></minimumStockLevel> 
<primarySupplierContactUid></primarySupplierContactUid> 
<primarySupplierItemCode></primarySupplierItemCode> 
<defaultReOrderQuantity></defaultReOrderQuantity> 
<isSold></isSold> 
<saleIncomeAccountUid></saleIncomeAccountUid> 
<saleTaxCode></saleTaxCode> 
<saleCoSAccountUid></saleCoSAccountUid> 
<sellingPrice>105.00000</sellingPrice> 
<isSellingPriceIncTax></isSellingPriceIncTax> 
</inventoryItem> 
</insertInventoryItem>
";
            string url    = RestProxy.MakeUrl("Tasks");
            string result = HttpUtils.Post(url, xml);

            Console.WriteLine("Result:");
            Console.WriteLine(result);
        }
        // [Test]
        public void InsertContact2()
        {
            string xml =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
		<tasks>
		<insertContact>
		<contact uid=""0"">
			<salutation/>
			<givenName>fred</givenName>
			<familyName>person</familyName>
			<organisationName/>
			<organisationAbn/>
			<organisationWebsite/>
			<organisationPosition/>
			<email>[email protected]</email>
			<mainPhone>123456789</mainPhone>
			<homePhone/>
			<mobilePhone/>
			<tags>retail customer, retail, customer</tags>
			<isActive>true</isActive>
		</contact>
		</insertContact>
		</tasks>
		"        ;
            string url    = RestProxy.MakeUrl("Tasks");
            string result = HttpUtils.Post(url, xml);

            Console.WriteLine("Result:");
            Console.WriteLine(result);
        }
示例#7
0
        //  [Ignore] // - this test requires user interaction
        public async Task UpdateCalendar()
        {
            await Authenticate();

            Assert.IsNotNull(_token);

            var client = new RestClient("https://www.googleapis.com/calendar/v3");

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_token);
            dynamic proxy = new RestProxy(client);
            var     list  = await proxy.users.me.calendarList.get();

            Assert.IsNotNull(list);

            string id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault();

            Assert.IsFalse(string.IsNullOrEmpty(id));

            var     guid     = Guid.NewGuid().ToString();
            dynamic calendar = new ExpandoObject();

            calendar.summary     = "unit_testing";
            calendar.description = guid;

            var result = await proxy.calendars(id).put(calendar);

            Assert.IsNotNull(result);

            list = await proxy.users.me.calendarList.get();

            Assert.IsNotNull(list);
            string description = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.description).FirstOrDefault();

            Assert.AreEqual(guid, description);
        }
示例#8
0
        //  [Ignore] // - this test requires user interaction
        public async Task DeleteCalendar()
        {
            await Authenticate();

            Assert.IsNotNull(_token);

            var client = new RestClient("https://www.googleapis.com/calendar/v3");

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_token);
            dynamic proxy = new RestProxy(client);
            var     list  = await proxy.users.me.calendarList.get();

            Assert.IsNotNull(list);

            string id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault();

            Assert.IsFalse(string.IsNullOrEmpty(id));

            var result = await proxy.calendars(id).delete();

            Assert.IsNull(result);

            list = await proxy.users.me.calendarList.get();

            Assert.IsNotNull(list);
            id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault();

            Assert.IsTrue(string.IsNullOrEmpty(id));
        }
        public void TwoSegmentProperties()
        {
            var     client = new RestClient("http://example.com");
            dynamic proxy  = new RestProxy(client);
            dynamic chain  = proxy.segment1.segment2;

            string s = chain.ToString();

            Assert.AreEqual("http://example.com/segment1/segment2", s);
        }
        public void EscapeTwoSequentialSegmentsThenProperty()
        {
            var     client = new RestClient("http://example.com");
            dynamic proxy  = new RestProxy(client);
            dynamic chain  = proxy.segment1("escaped")("escaped2").segment2;

            string s = chain.ToString();

            Assert.AreEqual("http://example.com/segment1/escaped/escaped2/segment2", s);
        }
示例#11
0
        public void Align()
        {
            _httpRequestFactoryMock    = new Mock <IHttpRequestFactory>();
            _restCallResultAdapterMock = new Mock <IRestCallResultAdapter>();
            _httpClientProxyMock       = new Mock <IHttpClientProxy>();

            _sut = new RestProxy(
                _httpRequestFactoryMock.Object,
                _restCallResultAdapterMock.Object,
                _httpClientProxyMock.Object);
        }
        public void EscapeSegmentAsInvokeContinueChaining()
        {
            var     client   = new RestClient("http://example.com");
            dynamic proxy    = new RestProxy(client);
            dynamic segment1 = proxy.segment1;
            dynamic chain    = segment1("escaped")("escaped2").segment2;

            string s = chain.ToString();

            Assert.AreEqual("http://example.com/segment1/escaped/escaped2/segment2", s);
        }
示例#13
0
        internal HttpClientProxy(HttpClient client, RestProxy parent, string name)
            : base(parent, name)
        {
            Debug.Assert(client != null);

            _client = client;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/x-json"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/javascript"));
        }
示例#14
0
        public async Task ExplicitGetInvoke()
        {
            var client = new RestClient("http://openstates.org/api/v1");

            client.AddDefaultHeader("X-APIKEY", CredentialStore.Key("sunlight"));

            dynamic proxy = new RestProxy(client);

            dynamic result = await proxy.metadata.mn.get();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.name == "Minnesota");
        }
示例#15
0
 /// <summary>
 /// 使用代理
 /// </summary>
 /// <param name="Proxy"></param>
 /// <returns></returns>
 public IRestHttpClient UseProxy(RestProxy Proxy)
 {
     if (Proxy.IP.IsNullOrEmpty() || Proxy.Port == -1)
     {
         return(this);
     }
     this.Options.Proxy = new WebProxy(Proxy.IP, Proxy.Port);
     if (!Proxy.UserName.IsNullOrEmpty() && !Proxy.PassWord.IsNullOrEmpty())
     {
         this.Options.Proxy.Credentials = new NetworkCredential(Proxy.UserName, Proxy.PassWord);
     }
     return(this);
 }
        /// <summary>
        /// Search contact by contact id (not contact uid).
        /// </summary>
        /// <param name="contactID"></param>
        /// <returns></returns>
        private contactListResponse SearchByContactID(string contactID)
        {
            NameValueCollection queries = new NameValueCollection();

            queries.Add("contactid", contactID);
            string url = RestProxy.MakeUrl("ContactList");

            url += "&" + Util.ToQueryString(queries);
            string xmlFragment           = HttpUtils.Get(url);
            contactListResponse response = (contactListResponse)XmlSerializationUtils.Deserialize(typeof(contactListResponse), xmlFragment);

            return(response);
        }
示例#17
0
        public async Task GetMethod2PathAsProperty2Params()
        {
            var client = new RestClient("http://openstates.org/api/v1");

            client.AddDefaultHeader("X-APIKEY", CredentialStore.Key("sunlight"));

            dynamic proxy = new RestProxy(client);

            var result = await proxy.legislators.geo.get(lat : 44.926868, _long : -93.214049);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count > 0);
        }
        public void GetPdfContactStatement()
        {
            NameValueCollection queries = new NameValueCollection();

            queries.Add("contactuid", this.MrSmith.Uid.ToString());             // Required.
            queries.Add("datefrom", "2000-07-01");                              // Required.
            queries.Add("dateto", "2008-06-30");                                // Required.
            queries.Add("format", "pdf");                                       // Required.
            string url = RestProxy.MakeUrl("contactstatementreport");

            url += "&" + Util.ToQueryString(queries);
            new WebClient().DownloadFile(url, "ContactStatement" + DateTime.Today.ToString("yyyyMMdd") + ".pdf");
        }
示例#19
0
        public async Task GetMethodSegmentWithArgs()
        {
            var client = new RestClient("http://openstates.org/api/v1");

            client.AddDefaultHeader("X-APIKEY", CredentialStore.Key("sunlight"));

            dynamic proxy = new RestProxy(client);

            var result = await proxy.bills.mn("2013s1")("SF 1").get();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.id == "MNB00017167");
        }
示例#20
0
        private async Task <dynamic> RefreshAccessToken(dynamic access)
        {
            Assert.IsNotNull((string)access.refresh_token);

            dynamic key = CredentialStore.JsonKey("google").installed;

            var     client   = new RestClient("https://accounts.google.com");
            dynamic proxy    = new RestProxy(client);
            var     response = await proxy.o.oauth2.token.post(client_id : key.client_id, client_secret : key.client_secret, refresh_token : access.refresh_token, grant_type : "refresh_token");

            Assert.IsNotNull(response);

            return(response);
        }
示例#21
0
        public async Task GetMethod1PathArg1Param()
        {
            var client = new RestClient("http://openstates.org/api/v1");

            client.AddDefaultHeader("X-APIKEY", CredentialStore.Key("sunlight"));

            dynamic proxy = new RestProxy(client);

            var result = await proxy.bills.get(state : "mn", chamber : "upper", status : "passed_upper");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Count > 0);
            Assert.IsTrue(result[0].chamber == "upper");
        }
示例#22
0
        //  [Ignore] // - this test requires user interaction
        public async Task GetUserProfile()
        {
            await Authenticate();

            Assert.IsNotNull(_token);

            var client = new RestClient("https://www.googleapis.com");

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_token);
            dynamic proxy   = new RestProxy(client);
            var     profile = await proxy.oauth2.v1.userinfo.get();

            Assert.IsNotNull(profile);
            Assert.AreEqual((string)profile.family_name, "Kackman");
        }
示例#23
0
        //  [Ignore] // - this test requires user interaction
        public async Task GetCalendarList()
        {
            await Authenticate();

            Assert.IsNotNull(_token);

            var client = new RestClient("https://www.googleapis.com/calendar/v3");

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_token);
            dynamic proxy = new RestProxy(client);
            var     list  = await proxy.users.me.calendarList.get();

            Assert.IsNotNull(list);
            Assert.AreEqual((string)list.kind, "calendar#calendarList");
        }
        // [Test]
        public void InsertItemSaleQuote()
        {
            string xml =
                @"<insertInvoice> 
<invoice uid=""0""> 
<transactionType>S</transactionType> 
<date>2011-03-24</date> 
<contactUid>2681</contactUid> 
<shipToContactUid></shipToContactUid> 
<folderUid></folderUid>
<tags></tags> 
<reference></reference> 
<summary></summary> 
<notes>test</notes> 
<requiresFollowUp></requiresFollowUp> 
<dueOrExpiryDate></dueOrExpiryDate> 
<layout>I</layout> 
<status>Q</status> 
<invoiceNumber>&lt;Auto Number&gt;</invoiceNumber> 
<purchaseOrderNumber></purchaseOrderNumber> 
<ccy>AUD</ccy> 
<autoPopulateFxRate>true</autoPopulateFxRate> 
<fcToBcFxRate></fcToBcFxRate> 
<invoiceItems> <itemInvoiceItem> 
<quantity>1</quantity> 
<inventoryItemUid>637345</inventoryItemUid> 
<description>13-foot Heavy Duty Light  Stand</description> 
<taxCode>GST</taxCode> 
<unitPriceInclTax>115.50</unitPriceInclTax> 
<percentageDiscount></percentageDiscount> 
</itemInvoiceItem> <itemInvoiceItem> 
<quantity>1</quantity> 
<inventoryItemUid>637346</inventoryItemUid> 
<description>Shipping for Joomla / Virtuemart sales</description> 
<taxCode>GST</taxCode> 
<unitPriceInclTax>38.5</unitPriceInclTax> 
<percentageDiscount></percentageDiscount> 
</itemInvoiceItem> 
</invoiceItems> 
</invoice> 
</insertInvoice>
			"            ;
            string url    = RestProxy.MakeUrl("Tasks");
            string result = HttpUtils.Post(url, xml);

            Console.WriteLine("Result:");
            Console.WriteLine(result);
        }
        /// <summary>
        /// Search contact, Carl O'Neil from O'Neil Capital.
        /// </summary>
        /// <returns></returns>
        private contactListResponse SearchCarl()
        {
            NameValueCollection queries = new NameValueCollection();

            queries.Add("givenname", "carl");                   // AKA first name.
            queries.Add("familyName", "o'neil");                // AKA last name.
            queries.Add("organisationName", "o'neil capital");  // AKA organisation, company.
            string url = RestProxy.MakeUrl("ContactList");

            url += "&" + Util.ToQueryString(queries);

            string xmlFragment           = HttpUtils.Get(url);
            contactListResponse response = (contactListResponse)XmlSerializationUtils.Deserialize(typeof(contactListResponse), xmlFragment);

            return(response);
        }
示例#26
0
        private async Task <dynamic> GetNewAccessToken()
        {
            dynamic key = CredentialStore.JsonKey("google").installed;

            var     client   = new RestClient("https://accounts.google.com");
            dynamic proxy    = new RestProxy(client);
            var     response = await proxy.o.oauth2.device.code.post(client_id : key.client_id, scope : "email profile https://www.googleapis.com/auth/calendar");

            Assert.IsNotNull(response);

            Debug.WriteLine((string)response.user_code);

            // use clip.exe to put the user code on the clipboard
            Process p = new Process();

            p.StartInfo.FileName  = "cmd.exe";
            p.StartInfo.Arguments = string.Format("/c echo {0} | clip", response.user_code);
            p.Start();

            // this requires user permission - open a broswer - enter the user_code which is now in the clipboard
            Process.Start((string)response.verification_url);

            int expiration = response.expires_in;
            int interval   = response.interval;
            int time       = interval;

            dynamic tokenResonse = null;

            // we are using the device flow so enter the code in the browser - poll google for success
            while (time < expiration)
            {
                Thread.Sleep(interval * 1000);
                tokenResonse = await proxy.o.oauth2.token.post(client_id : key.client_id, client_secret : key.client_secret, code : response.device_code, grant_type : "http://oauth.net/grant_type/device/1.0");

                if (tokenResonse.access_token != null)
                {
                    break;
                }
                time += interval;
            }

            Assert.IsNotNull(tokenResonse);
            return(tokenResonse);
        }
        // [Test]
        public void InsertContact()
        {
            string xml =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<tasks>
  <insertContact>
    <contact uid=""0"">
      <salutation>Mr.</salutation>
      <givenName>John</givenName>
      <familyName>Smith</familyName>
      <organisationName>Saasy.tv</organisationName>
      <organisationAbn>777888999</organisationAbn>      
      <organisationPosition>Director</organisationPosition>
      <email>[email protected]</email>
      <mainPhone>02 9999 9999</mainPhone>
      <mobilePhone>0444 444 444</mobilePhone>
      <contactID>XYZ123</contactID>
      <tags>Gold Prospect, Film</tags>
      <postalAddress>
        <street>3/33 Victory Av</street>
        <city>North Sydney</city>
        <state>NSW</state>
        <country>Australia</country>
      </postalAddress>
      <otherAddress>
        <street>111 Elizabeth street</street>
        <city>Sydney</city>
        <state>NSW</state>
        <country>Australia</country>
      </otherAddress>
      <isActive>true</isActive>
      <acceptDirectDeposit>false</acceptDirectDeposit>
      <acceptCheque>false</acceptCheque>
      <customField1>This is custom field 1</customField1>
      <customField2>This is custom field 2</customField2>
    </contact>
  </insertContact>
</tasks>
";

            string url    = RestProxy.MakeUrl("Tasks");
            string result = HttpUtils.Post(url, xml);
        }
示例#28
0
        public void GetAuthToken_WhenGivenValidCredentials_ShouldGetAnAuthTokenFromSessionsEndpoint()
        {
            // ARRANGE
            var stubApi     = Substitute.For <IAPI>();
            var stubLazyApi = new Lazy <IAPI>(() => stubApi);
            var credentials = new Credentials()
            {
                BaseUrl  = "https://some.bank.or.cu/api",
                Username = "******",
                Password = "******",
                Facility = "validFacility"
            };

            var header = new Header()
            {
                ContentType = "application/json"
            };

            var session = new Session()
            {
                UserName       = credentials.Username,
                Password       = credentials.Password,
                Authentication = "CCM"
            };

            var sessionResponse = new SessionResponse()
            {
                AuthToken = "abc123"
            };

            stubLazyApi.Value.URL = $"{credentials.BaseUrl}/v1/ccmservice/sessions";

            stubLazyApi.Value.Post <Session, SessionResponse>(session).Returns(sessionResponse);

            var mockProxy = new RestProxy(stubLazyApi, credentials);

            // ACT
            var authToken = mockProxy.GetAuthToken(session);

            // ASSERT
            Assert.IsNotEmpty(authToken);
            Assert.AreEqual(sessionResponse.AuthToken, authToken);
        }
示例#29
0
        // [Ignore] // - this test requires user interaction
        public async Task CreateCalendar()
        {
            await Authenticate();

            Assert.IsNotNull(_token);

            var client = new RestClient("https://www.googleapis.com/calendar/v3");

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_token);
            dynamic proxy = new RestProxy(client);

            dynamic calendar = new ExpandoObject();

            calendar.summary = "unit_testing";

            var list = await proxy.calendars.post(calendar);

            Assert.IsNotNull(list);
            Assert.AreEqual((string)list.summary, "unit_testing");
        }
        // [Test]
        public void InsertInventoryItem()
        {
            string id  = DateTime.Now.Ticks.ToString();
            string xml =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<tasks>
  <insertInventoryItem>
    <!-- NOTE: Replaced all Uids with the ones from your file. -->
    <inventoryItem uid=""0"">
      <code>CODE_" +
                id + @"</code>
      <description>Description for " + id +
                @"</description>
      <isActive>true</isActive>
      <notes>Notes for CODE_0c8-4ab2-9333-0890659b5d51</notes>
      <isInventoried>true</isInventoried>
      <assetAccountUid>87346</assetAccountUid> 
      <stockOnHand>0</stockOnHand>
      <currentValue>0</currentValue>
      <isBought>true</isBought>
      <purchaseExpenseAccountUid>0</purchaseExpenseAccountUid>
      <purchaseTaxCode>G11</purchaseTaxCode>
      <minimumStockLevel>99</minimumStockLevel>
      <primarySupplierContactUid>205235</primarySupplierContactUid>
      <primarySupplierItemCode>S_CODE</primarySupplierItemCode>
      <defaultReOrderQuantity>20</defaultReOrderQuantity>
      <isSold>true</isSold>
      <saleIncomeAccountUid>87349</saleIncomeAccountUid>
      <saleTaxCode>G1</saleTaxCode>
      <saleCoSAccountUid>87348</saleCoSAccountUid>
      <sellingPrice>7.75</sellingPrice>
      <isSellingPriceIncTax>true</isSellingPriceIncTax>
    </inventoryItem>
  </insertInventoryItem>
</tasks>
";

            string url    = RestProxy.MakeUrl("Tasks");
            string result = HttpUtils.Post(url, xml);
        }
示例#31
0
        static void Main(string[] args)
        {
            var serverUrlEnvVar = Environment.GetEnvironmentVariable(ENV_P_PRO_SERVER_URL);
            String serverUrl;
            if (serverUrlEnvVar == null)
            {
                Console.WriteLine("Server URL not set via the {0} environment variable, using default ({1}).", ENV_P_PRO_SERVER_URL, DEFAULT_SERVER_URL);
                serverUrl = DEFAULT_SERVER_URL;
            }
            else
            {
                serverUrl = serverUrlEnvVar;
            }

            var random = new Random();
            var jobInstanceBlackList = new HashSet<Guid>();

            using (IRestProxy restProxy = new RestProxy(serverUrl))
            {
                while (true)
                {
                    JobInstance[] unassignedJobInstance;

                    try
                    {
                        unassignedJobInstance = restProxy.Query<JobInstance>("AgentId".Eq(Guid.Empty.ToString())).Result.ToArray();
                    }
                    catch (RestProxyException e)
                    {
                        Console.Error.WriteLine("HTTP error while trying to query for unassigned jobs: " + e.Message);
                        Console.Error.WriteLine("Trying again in a few seconds...");
                        Thread.Sleep(TimeSpan.FromSeconds(5));
                        continue;
                    }

                    foreach (var jobInstance in unassignedJobInstance)
                    {
                        if (jobInstanceBlackList.Contains(jobInstance.Id))
                            continue;

                        JobDescription jobDescription;

                        try { jobDescription = restProxy.Get<JobDescription>(jobInstance.JobDescriptionId).Result; }
                        catch (RestProxyException e)
                        {
                            if (e.StatusCode == HttpStatusCode.NotFound)
                            {
                                restProxy.Create(new JobInstanceLogEntry()
                                {
                                    Id = Guid.NewGuid(),
                                    JobInstanceId = jobInstance.Id,
                                    LocalTimeStamp = DateTime.UtcNow,
                                    Text = ""
                                });
                                Console.Error.WriteLine("Encountered invalid job instance: " + jobInstance.Id);
                                Console.Error.WriteLine("=> JobDescription not found.");
                                jobInstanceBlackList.Add(jobInstance.Id);
                            }
                            else
                            {
                                Console.Error.WriteLine("HTTP error while trying to retrieve job description for job instance: " + e.Message);
                            }

                            continue;
                        }

                        Agent[] agents = null;
                        while (agents == null)
                        {
                            try
                            {
                                agents = restProxy.GetAll<Agent>()
                                    .Result
                                    .Where(a => AgentMatchesJobRequirements(a, jobDescription))
                                    .ToArray();
                            }
                            catch (RestProxyException e)
                            {
                                Console.Error.WriteLine("HTTP error while trying to retrieve agent list: " + e.Message);
                                Console.Error.WriteLine("Retrying in a moment...");

                                Thread.Sleep(TimeSpan.FromSeconds(10));
                            }
                        }

                        var selectedAgentId = agents[random.Next(0, agents.Length)].Id;
                        jobInstance.AgentId = selectedAgentId;

                        while(true) try 
                        { 
                            restProxy.Update(jobInstance);
                            break;
                        }
                        catch (RestProxyException e)
                        {
                            if (e.StatusCode == HttpStatusCode.NotFound)
                            {
                                Console.Error.WriteLine("Could not find job instance with id " + jobInstance.Id + " again. May have been deleted.");
                                break;
                            }
                            else
                            {
                                Console.Error.WriteLine("HTTP error while trying to update job instance: " + e.Message);
                                Console.Error.WriteLine("Retrying in a moment...");

                                Thread.Sleep(TimeSpan.FromSeconds(10));
                            }
                        }
                    } 

                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            }
        }
示例#32
0
        public void Test_EmptyJob()
        {
            var agentId = Guid.NewGuid();
            var agentFriendlyName = "TestAgent1"; 

            var jobDescription = new JobDescription 
            {
                Id = Guid.NewGuid(),
                FriendlyName = "P.PRO TEST JOB",
                CommandArray = new [] {
                    new JobCommandDescription {
                        PrepareCommand = "",
                        RunCommand = "",
                        CleanUpCommand = "", 
                    }
                }
            };

            var jobInstance = new JobInstance 
            { 
                AgentId = agentId,
                CurrentState = JobInstance.State.NotYetStarted,
                Id = Guid.NewGuid(),
                JobDescriptionId = jobDescription.Id
            };

            var restProxy = new RestProxy("http://localhost:26679/testing/");
            restProxy.Create(jobDescription).Wait();
            restProxy.Create(jobInstance).Wait();

            new Daemon(agentId, agentFriendlyName, restProxy).Run(1);

            Thread.Sleep(1000);

            var jobInstanceAfter = restProxy.Get<JobInstance>(jobInstance.Id).Result;

            Assert.AreEqual(jobInstance.JobDescriptionId, jobInstanceAfter.JobDescriptionId);
            Assert.AreEqual(jobInstance.ResultDestination, jobInstanceAfter.ResultDestination);
            Assert.AreEqual(jobInstance.AgentId, jobInstanceAfter.AgentId);
            Assert.AreEqual(JobInstance.State.Finished, jobInstanceAfter.CurrentState);
        }