Usage way

Shahriar Hossain edited this page May 27, 2016 · 1 revision

Since you are already on this page, that clearly indicates your passion, love for RestSharp. In the following code snippet you will see how BrowserStack Screenshot client BrowserStack Screenshot library was built with RestSharp.

The file BaseOperation.cs is the core helper for the BrowserStack Screenshot client library. In this file you will find two generic method. ExecutePost and ExecuteGet

ExecutePost take 5 parameters. Along with the login credential this method receives a baseUrl/endpoint, a RestSharp request object and the original object that you want to pass to the server. To ignore the null value property while serializing the object, Newtonsoft Json was used. If you want to make the request in an async fashion then instead of calling Execute you should call the ExecuteTaskAsync method. Note that exceptions from Execute are not thrown but are available in the ErrorException property.

// BaseOperation.cs
/// <summary>
/// Generic Post method
// <param name="request">Restsharp request object</param>
/// <param name="endpoint">The url where we want to hit to get result</param>
/// <param name="obj">Object that you want to serialize</param>
/// <param name="userName">BrowserStack User Name</param>
/// <param name="accessKey">BrowserStack Access Key</param>
/// </summary>
public static T ExecutePost<T, K>(RestRequest request, string endPoint, K obj, string userName = "default", string accessKey = "default") where T : class, new()
        {
            var restClient = new RestClient(endPoint)
            {
                Authenticator = new HttpBasicAuthenticator(userName, accessKey)
            };

            request.Method = Method.POST;

            request.AddHeader("Content-Type", "application/json");

            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,

                Converters = new List<JsonConverter> 
                { 
                    new IsoDateTimeConverter()
                    {
                        DateTimeFormat= "yyyy-MM-dd HH:mm:ss"
                    }
                }
            };

            var myContentJson = JsonConvert.SerializeObject(obj, settings);

            request.AddParameter("application/json", myContentJson, ParameterType.RequestBody);

            var response = restClient.Execute<T>(request);

            //To make the call async
            //var cancellationTokenSource = new CancellationTokenSource();
            //var response2 = restClient.ExecuteTaskAsync<T>(request, cancellationTokenSource.Token);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var browserStackException = new ApplicationException(message, response.ErrorException);
                throw browserStackException;
            }
            return response.Data;
        }

Here is the generic Get method. It is almost identical to the ExecutePost method except the part that it does not receive any actual object.

 /// <summary>
        /// Generic Post method
        /// <param name="request">Restsharp request object</param>
        /// <param name="endpoint">The url where we want to hit to get result</param>
        /// <param name="userName">BrowserStack User Name</param>
        /// <param name="accessKey">BrowserStack Access Key</param>
        /// </summary>
        public static T ExecuteGet<T>(RestRequest request, string endPoint, string userName = "default", string accessKey = "default") where T : class, new()
        {
            var restClient = new RestClient(endPoint)
            {
                Authenticator = new HttpBasicAuthenticator(userName, accessKey)
            };

            request.Method = Method.GET;

            request.AddHeader("Content-Type", "application/json");

            var response = restClient.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var browserStackException = new ApplicationException(message, response.ErrorException);
                throw browserStackException;
            }
            return response.Data;
        }

Here is how these two methods were invoked.

        /// <summary>
        /// Get available browser
        /// </summary>
        public List<Browser> GetAvailableBrowser()
        {
            var request = new RestRequest();
            request.Resource = "/browsers.json";
            return BaseOperation.ExecuteGet<List<Browser>>(request, baseUrl, UserName, AccessKey);
        }

        /// <summary>
        /// Generate screenshot
        /// <param name="browserList">List of browser for which you want to generate screenshot</param>
        /// </summary>
        public RootScreenshot GenerateScreenshot(RootBrowser browserList)
        {
            var request = new RestRequest();
            return BaseOperation.ExecutePost<RootScreenshot, RootBrowser>(request, baseUrl, browserList, UserName, AccessKey);
        }