internal static List <string> ResolveFieldForUsers(
            RestApi restApi,
            List <string> users,
            string profileFieldQualifiedName)
        {
            if (string.IsNullOrEmpty(profileFieldQualifiedName))
            {
                return(null);
            }

            string[] profileFieldsPath = profileFieldQualifiedName.Split(
                new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            List <string> result = new List <string>();

            foreach (string user in users)
            {
                string solvedUser;

                if (!TryResolveUserProfileValue(
                        restApi, user, profileFieldsPath, out solvedUser))
                {
                    Add(user, result);
                    continue;
                }

                Add(solvedUser, result);
            }

            return(result);
        }
Example #2
0
        public async Task <List <NewsModel> > ListNewsTaskAsync(int pageIndex, string newsType)
        {
            string url     = DomainUrl + string.Format(NewsPathUrl, pageIndex, newsType);
            string results = await RestApi.GetHtmlTaskAsync(url);

            // fetch the news data list
            var resultList = HtmlHelper.DescendantsPath(results, "//table/tr", node =>
            {
                bool?result = node.Attributes["style"]?.Value?.StartsWith("background-color:");
                return(result.GetValueOrDefault(false));
            }
                                                        , node =>
            {
                string time           = HtmlHelper.ReadDocumentValue(node.InnerHtml, "//td[1]").Replace("\r\n", string.Empty).Trim();
                string title          = HtmlHelper.ReadDocumentValue(node.InnerHtml, "//td[2]/a", "title");
                string mobileNewsPath = HtmlHelper.ReadDocumentValue(node.InnerHtml, "//td[2]/a", "href").Replace(NewsViewerPath, MobileNewsViewerPath);
                // e.g. https://m.moneydj.com/f1a.aspx?a={uuid}&c=MB010000
                string newsUrl      = MobileDomainUrl + mobileNewsPath;
                NewsModel newsModel = new NewsModel
                {
                    Title = title,
                    Time  = DateTime.ParseExact(time, "MM/dd HH:mm", CultureInfo.InvariantCulture),
                    Url   = newsUrl
                };
                return(newsModel);
            });

            return(resultList);
        }
        private string SurveyTestUrl(AccessToken token, string serverUrl, string surveyId)
        {
            try
            {
                var url       = $"{serverUrl}/v1/Surveys/{surveyId}/PublicIds";
                var request   = new RestApi().Get(url, token);
                var urlString = string.Empty;
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        var content         = reader.ReadToEnd();
                        var SurveyPublicIds = JsonConvert.DeserializeObject <List <SurveyPublicIdModel> >(content);
                        urlString = SurveyPublicIds.FirstOrDefault(x => x.LinkType == "ExternalTestId").Url;
                    }
                }

                return(urlString);
            }
            catch (Exception)
            {
                DisplayAlert("Oeps", "Could not open preview", "Ok");
            }

            return(string.Empty);
        }
        private async void ButtonOnClicked(object sender, EventArgs e)
        {
            var restApi      = new RestApi();
            var commentCount = await restApi.GetCommentCount(_entry.Text);

            _editor.Text += $"\n{commentCount}";
        }
Example #5
0
        public static async Task UpdateRunningTask()
        {
            if (ActualRunningTaskData == default(TaskPresentationLayout))
            {
                ActualRunningTaskData = new TaskPresentationLayout();
            }

            UpdateWorkspaces();
            UpdateProjects();
            RunningTask = (await RestApi.GetCurrentTimeEntries()).data;

            if (RunningTask == default(TimeEntries))
            {
                ActualRunningTaskData.Update();
                return;
            }

            var startTime     = DateTime.Parse(RunningTask.start, null, DateTimeStyles.RoundtripKind);
            var projectName   = RunningTask.pid == 0 ? default(string) : Projects.FirstOrDefault(p => p.id == RunningTask.pid).name;
            var workspaceName = Workspaces.FirstOrDefault(w => w.id == RunningTask.wid).name;

            ActualRunningTaskData.Update(
                workspaceName,
                projectName,
                RunningTask.description,
                startTime);
        }
Example #6
0
        public RegisterStepOnePage(RetailerList objRetailerList)
        {
            InitializeComponent();
            NavigationPage.SetBackButtonTitle(this, "");
            XFLblTAC.Text = $"T&C";
            _objGetDetailsFromZipcodeResponse = new GetDetailsFromZipcodeResponse();
            _baseUrl         = Domain.Url + Domain.GetDetailsByZipCode;
            _objHeaderModel  = new HeaderModel();
            _apiService      = new RestApi();
            _objRetailerList = new RetailerList();
            if (Settings.IsLoggedIn)
            {
                xfGridPass.IsVisible = false;
            }
            if (objRetailerList != null)
            {
                _objRetailerList = objRetailerList;

                imgCompanyLogo.Source = objRetailerList.imagePath;
                XFLBLCompanyRate.Text = $"{objRetailerList.rate:0.00}" + "c";
                XFBTN_Duration.Text   = objRetailerList.duration + " Months";
            }

            _objUserRegistrationRequest = new UserRegistrationRequest();
            GetDeatailsFromZipCode();
        }
    void Start()
    {
        Api = FindObjectOfType <RestApi>();

        WebSocketListener.Instance().Subscribe(this);

        CardTray = FindObjectOfType <CardTrayBehaviour>();
        CardTray.OnSelected.AddListener(OnCardSelections);

        Board = FindObjectOfType <GameBoardBehaviour>();

        AnimationEngine = FindObjectOfType <AnimationEngineBehaviour>();
        AnimationEngine.OnComplete.AddListener(onAnimationsComplete);

        lobbyInfo = LobbyInfoController.Instance();
        if (lobbyInfo != null && lobbyInfo.msg != null)
        {
            WebSocketListener.Instance().StartListening(lobbyInfo.msg.id, lobbyInfo.playerName, () => {
                Debug.Log("I'm listening...");
                if (lobbyInfo.gameStartMessage != null)
                {
                    handleDownStreamMessage(MsgTypes.GAME_START, lobbyInfo.gameStartMessage);
                }
            });
        }
    }
Example #8
0
        public async void TestMethod1()
        {
            string result = await RestApi.GetTaskAsync <string>(BDIIndexUrl);

            Assert.IsNotNull(result);
            Assert.IsNotNull(null);
        }
Example #9
0
        internal static void NotifyTaskStatus(
            RestApi restApi,
            string owner,
            string message,
            TrunkBotConfiguration.Notifier notificationsConfig)
        {
            if (notificationsConfig == null)
            {
                return;
            }

            try
            {
                List <string> recipients = GetNotificationRecipients(
                    restApi, owner, notificationsConfig);

                TrunkMergebotApi.Notify.Message(
                    restApi, notificationsConfig.Plug, message, recipients);
            }
            catch (Exception e)
            {
                mLog.ErrorFormat("Error notifying task status message '{0}'. Error: {1}",
                                 message, e.Message);
                mLog.DebugFormat("StackTrace:{0}{1}", Environment.NewLine, e.StackTrace);
            }
        }
Example #10
0
        public void AuthenticateRequired_WithMethodAuthenticate_ReturnsTrue()
        {
            RestApi.RegisterRoutes(typeof(MethodAuthenticateRoute));
            var authenticationRequired = Authentication.RouteRequiresAuthenticate(RestApi.Routes.First());

            Assert.IsTrue(authenticationRequired);
        }
Example #11
0
        public async Task <IActionResult> LayoutBooking(string zoneId)
        {
            if (!Cookies.CheckFbLogIn(Request))
            {
                return(RedirectToAction("LogIn", "Authentication"));
            }


            byte[] values; string id = "";
            var    cookies = HttpContext.Request.Cookies;

            HttpContext.Session.TryGetValue("ZoneId", out values);
            if (values != null)
            {
                id = Encoding.ASCII.GetString(values);
            }

            zoneId = (zoneId == null?id:zoneId);
            RestApi api = new RestApi("https://localhost:5003/api/concertSeats/Zone?zoneId=" + zoneId);

            api.SetHeader("Authorization", Cookies.GetToken(Request));

            var data = await api.GetAsync("");

            //data.ReasonPhrase
            //data.StatusCode == 401
            var responseBody = await data.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Result>(responseBody);
            List <ConcertSeatModel> availableSeats = JsonConvert.DeserializeObject <List <ConcertSeatModel> >(result.Data);

            return(View(availableSeats));
        }
Example #12
0
        public async Task <IActionResult> Details(string concertId)
        {
            RestApi api = new RestApi("https://localhost:5003/api/concert?concertId=" + concertId);

            var data = await api.GetAsync("");

            var responseBody = await data.Content.ReadAsStringAsync();

            Result result = JsonConvert.DeserializeObject <Result>(responseBody);
            List <ConcertModel> concertList = JsonConvert.DeserializeObject <List <ConcertModel> >(result.Data);

            var concert = (from c in concertList where c.Id == concertId select c).FirstOrDefault(x => x.IsActive == true);

            api  = new RestApi("https://localhost:5003/api/concertSeats?concertId=" + concertId);
            data = await api.GetAsync("");

            responseBody = await data.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject <Result>(responseBody);
            List <AvailableSeatModel> availableSeats = JsonConvert.DeserializeObject <List <AvailableSeatModel> >(result.Data);

            ConcertDetailModel concertDetail = new ConcertDetailModel {
                Concert        = concert,
                AvailableSeats = availableSeats
            };

            if (availableSeats.Count > 0)
            {
                HttpContext.Session.Set("ZoneId", Encoding.ASCII.GetBytes(availableSeats[0].ZoneId));
            }
            return(View(concertDetail));
        }
Example #13
0
 public Client(Configuration configuration)
 {
     _configuration = configuration;
     _api           = new RestApi(_configuration, new SignHelper(_configuration));
     _logger        = new Logger(GetType().Name, _configuration.LogLevel);
     SetThreadPoolConfiguration();
 }
Example #14
0
        public void Get_InvokingEndpointAndExpectationMet_MessageIsSentToQueue()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/list");

            restEndpoint.Configure(get).With(Parameter.Any()).Returns(true)
            .Send <IOrderWasPlaced>(msg => msg.OrderedProduct = "stockings", "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("list");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            do
            {
                Thread.Sleep(100);
            } while (MsmqHelpers.GetMessageCount("shippingservice") == 0);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("true"));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(1), "shipping service did not recieve send");
        }
Example #15
0
        public void Get_SimpleExpectationSetUpInvokingEndpointAndExpectationMetInDifferentOrder_RestApiReturnsMatch()
        {
            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/order/{id}?foo&bar");

            restEndpoint.Configure(get).With(Parameter.RouteParameter <int>("id").Equals(1)
                                             .And(Parameter.QueryParameter <string>("foo").Equals("howdy"))
                                             .And(Parameter.QueryParameter <string>("bar").Equals("partner"))).Returns(true);

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("/order/1?bar=partner&foo=howdy");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("true"));
        }
Example #16
0
        protected void Application_Start()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(RestApi));

            RestApi.RegisterRoutes(assembly);
            RestApi.RoutePrefix = "/api";
        }
Example #17
0
 public GatewayService(IOptions <DiscordSettings> settings, ILogger <GatewayService> logger, JsonSerializerOptions jsonOptions, RestApi restApi)
 {
     _settings    = settings;
     _logger      = logger;
     _jsonOptions = jsonOptions;
     _restApi     = restApi;
 }
        public AddWorkSheetPage()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
            _objAddWorksheetRequestModel   = new AddWorkSheetRequestModel();
            _objAddWorksheetResponseModel  = new AddWorksheetResponseModel();
            _objDriver_LoadTypeResponse    = new Driver_LoadTypeResponse();
            _objDriverSelectVehicleResonse = new DriverSelectVehicleResonse();
            _objLoadCompanySiteResponse    = new LoadCompanySiteResponse();
            _objDriver_GetClientsResponse  = new Driver_GetClientsResponse();
            _objAddWorkSheetNumberResponse = new AddWorkSheetNumberResponse();
            _objShiftDataViewModel         = new ShiftDataViewModel();
            dropdownShift.ItemsSource      = _objShiftDataViewModel.GetShiftType();
            _objHeaderModel        = new HeaderModel();
            _apiServices           = new RestApi();
            _baseUrlLoadTypes      = Settings.Url + Domain.GetLoadTypesApiConstant;
            _baseUrlVehicle        = Settings.Url + Domain.SelectVehicleApiConstant;
            _baseUrlCompanySite    = Settings.Url + Domain.GetCompanySitesApiConstant;
            _baseUrlGetClients     = Settings.Url + Domain.GetClientsApiConstant;
            _baseUrlAddWorkSheet   = Settings.Url + Domain.AddWorkSheetApiConstant;
            _baseUrlGetWorksheetNo = Settings.Url + Domain.GetWorksheetNumberApiConstant;

            BindingContext = _objAddWorksheetRequestModel;
            // xyz("WKA009");
        }
        internal CambriaBamDevOpsTalkApiStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            RestApi api = new RestApi(this, "HelloWorldAPI", new RestApiProps
            {
                RestApiName = "Hello World API",
                Description = "This API says hello!",
                DefaultCorsPreflightOptions = new CorsOptions
                {
                    AllowMethods = Cors.ALL_METHODS,
                    AllowOrigins = Cors.ALL_ORIGINS
                }
            });

            Function helloWorldFunction = new Function(this, "hello-world", new FunctionProps
            {
                Runtime = Runtime.DOTNET_CORE_2_1,
                Code    = Code.FromAsset("./lambda-src/Cambria.BAM.DevOpsTalk.Api.Lambda/bin/Release/netcoreapp2.1/Cambria.BAM.DevOpsTalk.Api.Lambda.zip"),
                Handler = "Cambria.BAM.DevOpsTalk.Api.Lambda::Cambria.BAM.DevOpsTalk.Api.Lambda.Function::Get",
                Timeout = Duration.Seconds(15)
            });

            api.Root.AddMethod("GET", new LambdaIntegration(helloWorldFunction));


            var output = new CfnOutput(this, "RootUri", new CfnOutputProps
            {
                Description = "The root URI of the API",
                Value       = api.Url
            });
        }
Example #20
0
        static void SafeDeleteShelve(
            RestApi restApi,
            string repository,
            int shelveId)
        {
            if (shelveId == -1)
            {
                return;
            }

            try
            {
                TrunkMergebotApi.DeleteShelve(restApi, repository, shelveId);
            }
            catch (Exception ex)
            {
                mLog.ErrorFormat(
                    "Unable to delete shelve {0} on repository '{1}': {2}",
                    shelveId, repository, ex.Message);

                mLog.DebugFormat(
                    "StackTrace:{0}{1}",
                    Environment.NewLine, ex.StackTrace);
            }
        }
Example #21
0
        static BuildProperties CreateBuildProperties(
            RestApi restApi,
            string taskNumber,
            string branchName,
            string labelName,
            string buildStagePreCiOrPostCi,
            TrunkBotConfiguration botConfig)
        {
            int branchHeadChangesetId = TrunkMergebotApi.GetBranchHead(
                restApi, botConfig.Repository, branchName);
            ChangesetModel branchHeadChangeset = TrunkMergebotApi.GetChangeset(
                restApi, botConfig.Repository, branchHeadChangesetId);

            int trunkHeadChangesetId = TrunkMergebotApi.GetBranchHead(
                restApi, botConfig.Repository, botConfig.TrunkBranch);
            ChangesetModel trunkHeadChangeset = TrunkMergebotApi.GetChangeset(
                restApi, botConfig.Repository, trunkHeadChangesetId);

            return(new BuildProperties
            {
                BranchName = branchName,
                TaskNumber = taskNumber,
                BranchHead = branchHeadChangeset.ChangesetId.ToString(),
                BranchHeadGuid = branchHeadChangeset.Guid.ToString(),
                ChangesetOwner = branchHeadChangeset.Owner,
                TrunkHead = trunkHeadChangeset.ChangesetId.ToString(),
                TrunkHeadGuid = trunkHeadChangeset.Guid.ToString(),
                RepSpec = string.Format("{0}@{1}", botConfig.Repository, botConfig.Server),
                LabelName = labelName,
                Stage = buildStagePreCiOrPostCi
            });
        }
Example #22
0
        static bool GetIssueInfo(
            RestApi restApi,
            string taskNumber,
            TrunkBotConfiguration.IssueTracker issuesConfig,
            out string taskTittle,
            out string taskUrl)
        {
            taskTittle = null;
            taskUrl    = null;

            if (issuesConfig == null)
            {
                return(false);
            }

            mLog.InfoFormat("Obtaining task {0} title...", taskNumber);
            taskTittle = TrunkMergebotApi.Issues.GetIssueField(
                restApi, issuesConfig.Plug, issuesConfig.ProjectKey,
                taskNumber, issuesConfig.TitleField);

            mLog.InfoFormat("Obtaining task {0} URL...", taskNumber);
            taskUrl = TrunkMergebotApi.Issues.GetIssueUrl(
                restApi, issuesConfig.Plug, issuesConfig.ProjectKey,
                taskNumber);

            return(true);
        }
Example #23
0
        public void Post_DoesNotMatchSetup_DoesNotSendMessages()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}/shares");

            api.Configure(post).With(Parameter.RouteParameter <int>("id").Equals(1)).Send <IOrderWasPlaced>(msg => { msg.OrderNumber = 1; }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/2/shares", new StringContent(""));

            WaitVerifyNoExceptions(postAsync);

            client.Dispose();
            service.Dispose();

            Thread.Sleep(2000);

            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(0), "shipping service recieved events");
        }
Example #24
0
        public void Get_SimpleExpectationSetUpInHeaderHeaderVariableIsMissing_ReturnsDefaultValue()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/list");

            restEndpoint.Configure(get).With(Parameter.HeaderParameter <DateTime>("Today").Equals(dt => dt.Day == 3)).Returns(true)
            .Send <IOrderWasPlaced>(msg => msg.OrderedProduct = "stockings", "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("list");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("null"));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(0), "shipping service recieved events");
        }
Example #25
0
        public void Get_SimpleExpectationSetUpInHeader_HeaderParameterUsableInReturnStatement()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <SomeTupleReturnValue> get = restEndpoint.AddGet <SomeTupleReturnValue>("/list/{id}");

            restEndpoint.Configure(get).With(Parameter.HeaderParameter <DateTime>("Today").Equals(dt => dt.Day == 3).And(Parameter.RouteParameter <int>("id").Any())).Returns <DateTime, int>((today, id) => new SomeTupleReturnValue {
                One = today, Two = id
            });

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            client.DefaultRequestHeaders.Add("Today", new DateTime(2000, 1, 3).ToString());

            Task <string> getAsync = client.GetStringAsync("list/1");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("{\"One\":\"2000-01-03T00:00:00\",\"Two\":1}"));
        }
Example #26
0
        public void Post_PostWitBody_BodyIsPassedDownTheChain()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order");

            api.Configure(post).With(Body.AsDynamic().IsEqualTo(body => body.orderId == 1))
            .Send <IOrderWasPlaced, dynamic>((msg, body) =>
            {
                msg.OrderNumber = body.orderId;
            }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order", new StringContent("{\"orderId\":\"1\"}", Encoding.UTF8, "application/json"));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            MsmqHelpers.WaitForMessages("shippingservice");

            client.Dispose();
            service.Dispose();

            Assert.That(MsmqHelpers.PickMessageBody("shippingservice"), Is.StringContaining("1"));
            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }
Example #27
0
        public void Post_PostWitBodyAndRouteParameters_BodyAndParametersFromRequestAreBound()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}");

            api.Configure(post).With(Body.AsDynamic().IsEqualTo(body => body.orderId == 1).And(Parameter.RouteParameter <int>("id").Equals(2))).Returns(3);

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/2", new StringContent("{\"orderId\":\"1\"}", Encoding.UTF8, "application/json"));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            Task <string> readAsStringAsync = message.Content.ReadAsStringAsync();

            readAsStringAsync.Wait();

            client.Dispose();
            service.Dispose();

            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(readAsStringAsync.Result, Is.EqualTo("3"));
        }
Example #28
0
        public void Post_JustASimplePostWithNoBody_MessagesAreSent()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}/shares");

            api.Configure(post).With(Parameter.RouteParameter <int>("id").Equals(1)).Send <IOrderWasPlaced>(msg => { msg.OrderNumber = 1; }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/1/shares", new StringContent(""));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            client.Dispose();
            service.Dispose();

            do
            {
                Thread.Sleep(100);
            } while (MsmqHelpers.GetMessageCount("shippingservice") == 0);

            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(1));
        }
        public static EdmString MapFromJson(JObject json)
        {
            var edmString = new EdmString();

            edmString.Value = RestApi.MapStringFromJson(json, "value");
            return(edmString);
        }
Example #30
0
        static void ReportMerge(
            RestApi restApi,
            string repository,
            string branchName,
            string botName,
            MergeReport mergeReport)
        {
            if (mergeReport == null)
            {
                return;
            }

            try
            {
                TrunkMergebotApi.MergeReports.ReportMerge(restApi, botName, mergeReport);
            }
            catch (Exception ex)
            {
                mLog.ErrorFormat(
                    "Unable to report merge for branch '{0}' on repository '{1}': {2}",
                    branchName, repository, ex.Message);

                mLog.DebugFormat(
                    "StackTrace:{0}{1}",
                    Environment.NewLine, ex.StackTrace);
            }
        }
Example #31
0
        protected override void Write(LogEventInfo logEvent)
        {
            var restClient = new RestApi(new Uri(this.Host), this.Token);
            // todo : try to do something more async
#pragma warning disable 4014
            restClient.Log(new ErrorFromNlog(logEvent, this.ApplicationName));
#pragma warning restore 4014
        }
Example #32
0
        public LMSSQLErrorLog(IDictionary config)
            : base(config)
        {
            var logId = Helpers.Helpers.ResolveLogId(config);
            var url = Helpers.Helpers.ResolveUrl(config);
            this.ApplicationName = Helpers.Helpers.ResolveApplicationName(config);

            _client = new RestApi(url, logId);
        }
Example #33
0
        public LMSMemoryErrorLog(IDictionary config)
            : base(config)
        {
            //Trace.TraceInformation("LMS Elmah logger starting");
            var logId = Helpers.Helpers.ResolveLogId(config);
            var url = Helpers.Helpers.ResolveUrl(config);
            this.ApplicationName = Helpers.Helpers.ResolveApplicationName(config);

            _client = new RestApi(url, logId);
            //Trace.TraceInformation("LMS Elmah logger started");
        }