├── TextFile1.txt ├── WebServiceAutomation ├── JwtToken │ ├── RootNode.cs │ └── HandlingJwtToken.cs ├── Model │ ├── JsonModel │ │ ├── Features.cs │ │ ├── JsonRootObject.cs │ │ └── JsonRootObjectBuilder.cs │ ├── XmlModel │ │ ├── Features.cs │ │ ├── LaptopDetailss.cs │ │ ├── Laptop.cs │ │ └── XmlModelBuilder.cs │ └── RestResponse.cs ├── Questions │ ├── Model │ │ ├── LapTopFeatures.cs │ │ └── LaptopDetails.cs │ └── Post │ │ └── PostRequestTests.cs ├── Helper │ ├── Authetication │ │ └── Base64StringConverter.cs │ ├── Response │ │ └── ResponseDataHelper.cs │ └── Request │ │ ├── HttpClientHelper.cs │ │ └── HttpAsyncClientHelper.cs ├── Properties │ └── AssemblyInfo.cs ├── packages.config ├── Testrun.runsettings ├── Question │ └── TestNestedJson.cs ├── MyTaskClass.cs └── UnitTest1.cs ├── RestSharpAutomation ├── Jwt Token │ ├── Model │ │ └── JwtToken.cs │ └── TestJwtToken.cs ├── JiraAPI │ ├── Response │ │ ├── Session.cs │ │ ├── LoginResponse.cs │ │ ├── CurrentUser.cs │ │ ├── CreateProjectResponse.cs │ │ └── LoginInfo.cs │ ├── Request │ │ ├── JiraLogin.cs │ │ └── CreateProjectPayload.cs │ ├── TestJiraAPI.cs │ └── TestJiraEndToEndFlow.cs ├── DropBoxAPI │ ├── ListFolderModel │ │ ├── Field.cs │ │ ├── PropertyGroup.cs │ │ ├── RootObject.cs │ │ ├── SharingInfo.cs │ │ └── Entry.cs │ └── TestGenerateToken.cs ├── Resource │ └── Get │ │ └── getall.json ├── Question │ ├── Model │ │ ├── LdiMarkups.cs │ │ ├── AccessorialMarkup.cs │ │ ├── MileMarkups.cs │ │ └── MarginProfile.cs │ ├── FileUpload │ │ ├── FileUpload.cs │ │ └── TestZamZarUpload.cs │ ├── PostFormData │ │ └── TestFormData.cs │ ├── LargeJson │ │ └── TestPostWithLargeJson.cs │ ├── Post │ │ ├── PostRequest.cs │ │ └── PostRequestTests.cs │ └── MSLogin │ │ └── UpdateAPI.cs ├── CustomReporter │ ├── ReportInitilaize.cs │ └── CustomeExtentRepoter.cs ├── ReportAttribute │ ├── TestCustomAttribue.cs │ └── TestMethodWithReport.cs ├── Properties │ └── AssemblyInfo.cs ├── Mocks │ └── TestServiceWithMock.cs ├── RestPostEndpoint │ └── FileUploadEndPoint.cs ├── CustomSerializer │ ├── CustomXmlSerializer.cs │ └── CustomJsonSerializer.cs ├── QueryParameter │ └── QueryParameter.cs ├── app.config └── UnitTest1.cs ├── RestSharpLatest ├── APIHelper │ ├── IClient.cs │ ├── IJiraClient.cs │ ├── IRestApiResponse.cs │ ├── IResponse.cs │ ├── ICommand.cs │ ├── Client │ │ ├── DefaultClient.cs │ │ ├── BasicAuthDecorator.cs │ │ ├── AuthenticationDecorato.cs │ │ ├── TracerClient.cs │ │ └── JiraClient.cs │ ├── RestApiExecutor.cs │ ├── APIResponse │ │ └── Response.cs │ ├── AbstractRequest.cs │ ├── APIRequest │ │ ├── GetRequestBuilder.cs │ │ ├── DeleteRequestBuilder.cs │ │ ├── PutRequestBuilder.cs │ │ └── PostRequestBuilder.cs │ ├── AbstractResponse.cs │ └── Command │ │ ├── RequestCommand.cs │ │ └── DownloadRequestCommand.cs ├── DropBox │ ├── Model │ │ ├── Field.cs │ │ ├── PropertyGroup.cs │ │ ├── Root.cs │ │ ├── FileLockInfo.cs │ │ ├── SharingInfo.cs │ │ └── Entry.cs │ ├── TestFileDownloadUsingFramework.cs │ ├── TestDownloadFile.cs │ └── ListFilesAndFolder.cs ├── JsonWebToken │ ├── Model │ │ ├── JwtToken.cs │ │ └── User.cs │ ├── Generate_JWT_Token.txt │ ├── JsonWebTokenAuthenticator.cs │ └── TestGetSecureWithJwt.cs ├── APIModel │ └── JsonApiModel │ │ ├── Features.cs │ │ ├── JsonModel.cs │ │ └── JsonModelBuilder.cs ├── SessionBasedAuth │ └── JiraApplication │ │ ├── Model │ │ ├── Session.cs │ │ ├── LoginResponse.cs │ │ ├── LoginInfo.cs │ │ └── CreateProjectPayload.cs │ │ └── TestJiraLogin.cs ├── CustomReporter │ ├── ReportInitilaize.cs │ └── CustomeExtentRepoter.cs ├── GetRequest │ ├── TestInterceptor.cs │ ├── TestApiHelperGet.cs │ ├── TestGetWithFramework.cs │ └── TestGetRequestSecure.cs ├── ReportAttribute │ ├── TestCustomAttribue.cs │ └── TestMethodWithReport.cs ├── UnitTest1.cs ├── Properties │ └── AssemblyInfo.cs ├── SchemaValidation │ └── Schema │ │ ├── RequestBodySchema.txt │ │ └── ValidateSchema.cs ├── Assignment │ ├── File_Upload_using_RestSharp_api │ │ └── Assignment_Post_File_Upload.cs │ ├── GET_Request_using_RestSharp_with_JWT │ │ └── Assignment_Get_with_JWT.cs │ ├── Assignment - GET Request │ │ └── Assignment_Get_Request.cs │ ├── POST_Request_with_De_serialization_of_XML_response_body │ │ └── Assignment_POST_Request_with_De-serialization_XML_body.cs │ ├── GET_Request_with_De_serialization_using_FrameworkAPI │ │ └── Assignment_Get_Request_Framework.cs │ ├── POST_Request_with_Decorator │ │ └── Assignment_POST_Request_with_Decorator.cs │ └── File_Download_using_Framework │ │ └── Assignment_POST_File_Download_Parallel.cs ├── Questions │ └── ExtentReport │ │ └── ExtentReport_Using_Framework.cs ├── FileUpload │ └── TestMultipartFormData.cs ├── app.config └── PostRequest │ └── TestMockAbleIo.cs ├── HttpInterceptor ├── app.config ├── Properties │ └── AssemblyInfo.cs ├── packages.config └── TestInterceptor.cs ├── README.md ├── MsTestProject ├── Properties │ └── AssemblyInfo.cs ├── packages.config ├── TestContextClass.cs └── UnitTest1.cs ├── .gitignore ├── Testrun.runsettings └── WebServiceAutomation.sln /TextFile1.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /WebServiceAutomation/JwtToken/RootNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.JwtToken 8 | { 9 | public class RootNode 10 | { 11 | public string token { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /RestSharpAutomation/Jwt Token/Model/JwtToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.Jwt_Token.Model 8 | { 9 | public class JwtToken 10 | { 11 | public string token { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/IClient.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper 9 | { 10 | public interface IClient : IDisposable 11 | { 12 | RestClient GetClient(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/JsonModel/Features.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Model.JsonModel 8 | { 9 | public class Features 10 | { 11 | public List Feature { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/Field.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.DropBox.Model 8 | { 9 | public class Field 10 | { 11 | public string name { get; set; } 12 | public string value { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Response/Session.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Response 8 | { 9 | public class Session 10 | { 11 | public string name { get; set; } 12 | public string value { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /WebServiceAutomation/Questions/Model/LapTopFeatures.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Questions.Model 8 | { 9 | [Serializable] 10 | public class LapTopFeatures 11 | { 12 | public List Feature { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Request/JiraLogin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Request 8 | { 9 | public class JiraLogin 10 | { 11 | public string username { get; set; } 12 | public string password { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/PropertyGroup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.DropBox.Model 8 | { 9 | public class PropertyGroup 10 | { 11 | public List fields { get; set; } 12 | public string template_id { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/ListFolderModel/Field.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.DropBoxAPI.ListFolderModel 8 | { 9 | public class Field 10 | { 11 | public string name { get; set; } 12 | public string value { get; set; } 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/IJiraClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.APIHelper 8 | { 9 | public interface IJiraClient : IClient 10 | { 11 | void Login(IJiraUser user); 12 | void Logout(); 13 | } 14 | 15 | public interface IJiraUser { } 16 | } 17 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/IRestApiResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper 9 | { 10 | public interface IRestApiResponse 11 | { 12 | HttpStatusCode GetHttpStatusCode(); 13 | Exception GetException(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Response/LoginResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Response 8 | { 9 | public class LoginResponse 10 | { 11 | public Session session { get; set; } 12 | public LoginInfo loginInfo { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpAutomation/Resource/Get/getall.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "BrandName": "Alienware", 4 | "Features": { 5 | "Feature": [ 6 | "8th Generation Intel® Core™ i5-8300H", 7 | "Windows 10 Home 64-bit English", 8 | "NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6", 9 | "8GB, 2x4GB, DDR4, 2666MHz" 10 | ] 11 | }, 12 | "Id": 1, 13 | "LaptopName": "Alienware M17" 14 | } 15 | ] -------------------------------------------------------------------------------- /RestSharpLatest/JsonWebToken/Model/JwtToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.JsonWebToken.Model 9 | { 10 | public class JwtToken 11 | { 12 | [JsonPropertyName("token")] 13 | public string Token { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/ListFolderModel/PropertyGroup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.DropBoxAPI.ListFolderModel 8 | { 9 | public class PropertyGroup 10 | { 11 | public string template_id { get; set; } 12 | public List fields { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/Root.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.DropBox.Model 8 | { 9 | public class Root 10 | { 11 | public string cursor { get; set; } 12 | public List entries { get; set; } 13 | public bool has_more { get; set; } 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /RestSharpLatest/APIModel/JsonApiModel/Features.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIModel.JsonApiModel 9 | { 10 | public class Features 11 | { 12 | [JsonPropertyName("Feature")] 13 | public List Feature { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Response/CurrentUser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Response 8 | { 9 | public class CurrentUser 10 | { 11 | public string self { get; set; } 12 | public string name { get; set; } 13 | public LoginInfo loginInfo { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Response/CreateProjectResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Response 8 | { 9 | public class CreateProjectResponse 10 | { 11 | public string self { get; set; } 12 | public int id { get; set; } 13 | public string key { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/FileLockInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.DropBox.Model 8 | { 9 | public class FileLockInfo 10 | { 11 | public DateTime created { get; set; } 12 | public bool is_lockholder { get; set; } 13 | public string lockholder_name { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Model/LdiMarkups.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.Question.Model 8 | { 9 | public class LdiMarkups 10 | { 11 | public int additionalProp1 { get; set; } 12 | public int additionalProp2 { get; set; } 13 | public int additionalProp3 { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/IResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.APIHelper 8 | { 9 | public interface IResponse : IRestApiResponse 10 | { 11 | string GetResponseData(); 12 | } 13 | 14 | public interface IResponse : IRestApiResponse 15 | { 16 | T GetResponseData(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/ListFolderModel/RootObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.DropBoxAPI.ListFolderModel 8 | { 9 | public class RootObject 10 | { 11 | public List entries { get; set; } 12 | public string cursor { get; set; } 13 | public bool has_more { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/XmlModel/Features.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Xml.Serialization; 7 | 8 | namespace WebServiceAutomation.Model.XmlModel 9 | { 10 | [XmlRoot(ElementName = "Features")] 11 | public class Features 12 | { 13 | [XmlElement(ElementName = "Feature")] 14 | public List Feature { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /HttpInterceptor/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/XmlModel/LaptopDetailss.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Xml.Serialization; 7 | 8 | namespace WebServiceAutomation.Model.XmlModel 9 | { 10 | [XmlRoot(ElementName = "laptopDetailss")] 11 | public class LaptopDetailss 12 | { 13 | [XmlElement(ElementName = "Laptop")] 14 | public List Laptop { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/JsonModel/JsonRootObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Model.JsonModel 8 | { 9 | public class JsonRootObject 10 | { 11 | public string BrandName { get; set; } 12 | public Features Features { get; set; } 13 | public int Id { get; set; } 14 | public string LaptopName { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Model/AccessorialMarkup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.Question.Model 8 | { 9 | public class AccessorialMarkup 10 | { 11 | public string accessorialCode { get; set; } 12 | public int markup { get; set; } 13 | public bool overrideDefault { get; set; } 14 | public bool notRated { get; set; } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Response/LoginInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Response 8 | { 9 | public class LoginInfo 10 | { 11 | public int failedLoginCount { get; set; } 12 | public int loginCount { get; set; } 13 | public DateTime lastFailedLoginTime { get; set; } 14 | public DateTime previousLoginTime { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/ICommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.APIHelper 8 | { 9 | public interface ICommand 10 | { 11 | IResponse ExecuteRequest(); // for response in string format 12 | IResponse ExecuteRequest(); // for the de-serialize object from response 13 | byte[] DownloadData(); 14 | Task DownloadDataAsync(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RestSharpLatest/JsonWebToken/Generate_JWT_Token.txt: -------------------------------------------------------------------------------- 1 | Approach 1 2 | 1. Create a Request for the User Registration /users/sign-up 3 | 2. Create a Second Request for authenticating the created user /users/authenticate 4 | 5 | Approach 2 6 | 1. Create a Custom Authenticator that inherit from the Authenticator Base Class 7 | (Rest Sharp Class) 8 | 2. In the Custom authenticator 9 | 2.1. Create a Request for the User Registration /users/sign-up 10 | 2.2. Create a Second Request for authenticating the created user /users/authenticate -------------------------------------------------------------------------------- /RestSharpLatest/SessionBasedAuth/JiraApplication/Model/Session.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.SessionBasedAuth.JiraApplication.Model 9 | { 10 | public class Session 11 | { 12 | [JsonPropertyName("name")] 13 | public string name { get; set; } 14 | [JsonPropertyName("value")] 15 | public string value { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharpLatest/CustomReporter/ReportInitilaize.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpAutomation.CustomReporter 9 | { 10 | [TestClass] 11 | public class ReportInitilaize 12 | { 13 | [AssemblyCleanup] 14 | public static void CleanUp() 15 | { 16 | CustomeExtentRepoter.GetInstance().WriteToReport(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /WebServiceAutomation/Questions/Model/LaptopDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Questions.Model 8 | { 9 | [Serializable] 10 | public class LaptopDetails 11 | { 12 | public string BrandName { get; set; } 13 | 14 | public LapTopFeatures Features { get; set; } 15 | 16 | public int Id { get; set; } 17 | 18 | public string LaptopName { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RestSharpAutomation/CustomReporter/ReportInitilaize.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpAutomation.CustomReporter 9 | { 10 | [TestClass] 11 | public class ReportInitilaize 12 | { 13 | [AssemblyCleanup] 14 | public static void CleanUp() 15 | { 16 | CustomeExtentRepoter.GetInstance().WriteToReport(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/SharingInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.DropBox.Model 8 | { 9 | public class SharingInfo 10 | { 11 | public string modified_by { get; set; } 12 | public string parent_shared_folder_id { get; set; } 13 | public bool read_only { get; set; } 14 | public bool? no_access { get; set; } 15 | public bool? traverse_only { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Model/MileMarkups.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.Question.Model 8 | { 9 | public class MileMarkups 10 | { 11 | public MileMarkups(int mileStart, decimal markup) 12 | { 13 | MileStart = mileStart; 14 | Markup = markup; 15 | } 16 | public int MileStart { get; set; } 17 | public decimal Markup { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RestSharpFramework 2 | 3 | Framework for testing RESTful Services with RestSharp and C# HTTP Client 4 | 5 | ## Course Link (Discount Coupon) 6 | 7 | https://www.udemy.com/course/rest-api-automation-with-restsharp-http-client/ 8 | 9 | ## YouTube Playlist 10 | 11 | - **RestSharp** https://www.youtube.com/playlist?list=PLlsKgYi2Lw73ox9LF5VfYMrA1eo9e7rIq 12 | 13 | - **Selenium Webdriver** https://www.youtube.com/playlist?list=PLlsKgYi2Lw724ozNSmdSrrtU8q6a1m3ob 14 | 15 | - **C# HttpClient** https://www.youtube.com/playlist?list=PLlsKgYi2Lw722PMqESdivKJQgRtJAdbzn 16 | -------------------------------------------------------------------------------- /RestSharpLatest/SessionBasedAuth/JiraApplication/Model/LoginResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.SessionBasedAuth.JiraApplication.Model 9 | { 10 | public class LoginResponse 11 | { 12 | [JsonPropertyName("session")] 13 | public Session session { get; set; } 14 | [JsonPropertyName("loginInfo")] 15 | public LoginInfo loginInfo { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/ListFolderModel/SharingInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.DropBoxAPI.ListFolderModel 8 | { 9 | public class SharingInfo 10 | { 11 | public bool read_only { get; set; } 12 | public string parent_shared_folder_id { get; set; } 13 | public string modified_by { get; set; } 14 | public bool? traverse_only { get; set; } 15 | public bool? no_access { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharpLatest/GetRequest/TestInterceptor.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.GetRequest 10 | { 11 | class TestInterceptor : RestSharp.Interceptors.Interceptor 12 | { 13 | public override ValueTask BeforeRequest(RestRequest request, CancellationToken cancellationToken) 14 | { 15 | return base.BeforeRequest(request, cancellationToken); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /RestSharpLatest/JsonWebToken/Model/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.JsonWebToken.Model 9 | { 10 | public class User 11 | { 12 | [JsonPropertyName("id")] 13 | public int Id { get; set; } 14 | [JsonPropertyName("password")] 15 | public string Password { get; set; } 16 | [JsonPropertyName("username")] 17 | public string Username { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /WebServiceAutomation/Helper/Authetication/Base64StringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Helper.Authetication 8 | { 9 | public class Base64StringConverter 10 | { 11 | public static string GetBase64String(string usename,string password) 12 | { 13 | string auth = usename + ":" + password; 14 | byte[] inArray = System.Text.UTF8Encoding.UTF8.GetBytes(auth); 15 | return System.Convert.ToBase64String(inArray); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RestSharpAutomation/ReportAttribute/TestCustomAttribue.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpAutomation.ReportAttribute 9 | { 10 | [TestClass] 11 | public class TestCustomAttribue 12 | { 13 | [TestMethodWithReport] 14 | public void FirstMethod() 15 | { 16 | 17 | } 18 | 19 | [TestMethodWithReport] 20 | public void SecondMethod() 21 | { 22 | Assert.Fail("I failed the test method"); 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RestSharpLatest/ReportAttribute/TestCustomAttribue.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpAutomation.ReportAttribute 9 | { 10 | [TestClass] 11 | public class TestCustomAttribue 12 | { 13 | [TestMethodWithReport] 14 | public void FirstMethod() 15 | { 16 | 17 | } 18 | 19 | [TestMethodWithReport] 20 | public void SecondMethod() 21 | { 22 | Assert.Fail("I failed the test method"); 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RestSharpLatest/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | 4 | namespace RestSharpLatest 5 | { 6 | [TestClass] 7 | public class UnitTest1 8 | { 9 | [TestMethod] 10 | public void TestMethod1() 11 | { 12 | /** 13 | * 1. Create the client 14 | * 2. Create the request 15 | * 3. Send the request 16 | * 4. Capture the response 17 | * 5. Add the verification on the response. 18 | * **/ 19 | 20 | RestClient client = new RestClient(); 21 | RestRequest request = new RestRequest(); 22 | 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RestSharpLatest/APIModel/JsonApiModel/JsonModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIModel.JsonApiModel 9 | { 10 | public class JsonModel 11 | { 12 | [JsonPropertyName("BrandName")] 13 | public string BrandName { get; set; } 14 | [JsonPropertyName("Features")] 15 | public Features Features { get; set; } 16 | [JsonPropertyName("Id")] 17 | public int Id { get; set; } 18 | [JsonPropertyName("LaptopName")] 19 | public string LaptopName { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /HttpInterceptor/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("HttpInterceptor")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("HttpInterceptor")] 10 | [assembly: AssemblyCopyright("Copyright © 2024")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("43325d19-284b-474e-ae11-abfad62b863a")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /RestSharpLatest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("RestSharpLatest")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("RestSharpLatest")] 10 | [assembly: AssemblyCopyright("Copyright © 2022")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("d7727898-bbf8-41b5-bd92-160f8e0fc593")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /MsTestProject/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("MsTestProject")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("MsTestProject")] 10 | [assembly: AssemblyCopyright("Copyright © Microsoft 2019")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("7f451f30-0ced-4cff-bce9-0d2ce727f38e")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/XmlModel/Laptop.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Xml.Serialization; 7 | 8 | namespace WebServiceAutomation.Model.XmlModel 9 | { 10 | [XmlRoot(ElementName = "Laptop")] 11 | public class Laptop 12 | { 13 | [XmlElement(ElementName = "BrandName")] 14 | public string BrandName { get; set; } 15 | [XmlElement(ElementName = "Features")] 16 | public Features Features { get; set; } 17 | [XmlElement(ElementName = "Id")] 18 | public string Id { get; set; } 19 | [XmlElement(ElementName = "LaptopName")] 20 | public string LaptopName { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /WebServiceAutomation/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("WebServiceAutomation")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("WebServiceAutomation")] 10 | [assembly: AssemblyCopyright("Copyright © Microsoft 2019")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("50e9c02d-5854-4c75-9fd8-38f370861c24")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | *.suo 54 | 55 | # Results and Package 56 | TestResults/ 57 | packages/ 58 | .vs/ 59 | **/obj/ 60 | **/bin/ 61 | -------------------------------------------------------------------------------- /RestSharpLatest/SessionBasedAuth/JiraApplication/Model/LoginInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.SessionBasedAuth.JiraApplication.Model 9 | { 10 | public class LoginInfo 11 | { 12 | [JsonPropertyName("failedLoginCount")] 13 | public int failedLoginCount { get; set; } 14 | [JsonPropertyName("loginCount")] 15 | public int loginCount { get; set; } 16 | [JsonPropertyName("lastFailedLoginTime")] 17 | public string lastFailedLoginTime { get; set; } 18 | [JsonPropertyName("previousLoginTime")] 19 | public string previousLoginTime { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /RestSharpLatest/SchemaValidation/Schema/RequestBodySchema.txt: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "Generated schema for Root", 4 | "type": "object", 5 | "properties": { 6 | "BrandName": { 7 | "type": "string" 8 | }, 9 | "Features": { 10 | "type": "object", 11 | "properties": { 12 | "Feature": { 13 | "type": "array", 14 | "items": { 15 | "type": "string" 16 | } 17 | } 18 | }, 19 | "required": [ 20 | "Feature" 21 | ] 22 | }, 23 | "Id": { 24 | "type": "number" 25 | }, 26 | "LaptopName": { 27 | "type": "string" 28 | } 29 | }, 30 | "required": [ 31 | "BrandName", 32 | "Features", 33 | "Id", 34 | "LaptopName" 35 | ] 36 | } -------------------------------------------------------------------------------- /RestSharpAutomation/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System.Reflection; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | 6 | [assembly: AssemblyTitle("RestSharpAutomation")] 7 | [assembly: AssemblyDescription("")] 8 | [assembly: AssemblyConfiguration("")] 9 | [assembly: AssemblyCompany("")] 10 | [assembly: AssemblyProduct("RestSharpAutomation")] 11 | [assembly: AssemblyCopyright("Copyright © 2019")] 12 | [assembly: AssemblyTrademark("")] 13 | [assembly: AssemblyCulture("")] 14 | 15 | [assembly: ComVisible(false)] 16 | 17 | [assembly: Guid("b492c2ad-db6a-471f-af94-34397fc2427f")] 18 | 19 | // [assembly: AssemblyVersion("1.0.*")] 20 | [assembly: AssemblyVersion("1.0.0.0")] 21 | [assembly: AssemblyFileVersion("1.0.0.0")] 22 | //[assembly: Parallelize(Workers = 4, Scope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope.MethodLevel)] 23 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Client/DefaultClient.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper.Client 9 | { 10 | public class DefaultClient : IClient 11 | { 12 | private RestClient _client; 13 | private readonly RestClientOptions _restClientOptions; 14 | 15 | public DefaultClient() 16 | { 17 | _restClientOptions = new RestClientOptions(); 18 | } 19 | 20 | public void Dispose() 21 | { 22 | _client?.Dispose(); 23 | } 24 | 25 | public RestClient GetClient() 26 | { 27 | _restClientOptions.ThrowOnDeserializationError = true; 28 | if(_client == null) 29 | _client = new RestClient(_restClientOptions); 30 | return _client; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Model/MarginProfile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.Question.Model 8 | { 9 | public class MarginProfile 10 | { 11 | public int customerId { get; set; } 12 | public string trailerGroup { get; set; } 13 | public int fuelSurcharge { get; set; } 14 | public bool overrideDefaultFuelSurcharge { get; set; } 15 | public bool overrideDefaultLDIMarkup { get; set; } 16 | public int truckPayAdjustment { get; set; } 17 | public bool overrideDefaultTruckPayAdjustment { get; set; } 18 | public bool overrideDefaultMileMarkups { get; set; } 19 | public List mileMarkups { get; set; } 20 | 21 | public LdiMarkups ldiMarkups { get; set; } 22 | public List accessorialMarkups { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/RestApiExecutor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.APIHelper 8 | { 9 | public class RestApiExecutor 10 | { 11 | private ICommand Command; 12 | 13 | public void SetCommand(ICommand _command) 14 | { 15 | Command = _command; 16 | } 17 | 18 | public IResponse ExecuteRequest() 19 | { 20 | return Command.ExecuteRequest(); 21 | } 22 | 23 | public IResponse ExecuteRequest() 24 | { 25 | return Command.ExecuteRequest(); 26 | } 27 | 28 | public byte[] DownloadData() 29 | { 30 | return Command.DownloadData(); 31 | } 32 | 33 | public Task DownloadDataAsync() 34 | { 35 | return Command.DownloadDataAsync(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RestSharpAutomation/Mocks/TestServiceWithMock.cs: -------------------------------------------------------------------------------- 1 | 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.Mocks 12 | { 13 | [TestClass] 14 | public class TestServiceWithMock 15 | { 16 | [TestMethod] 17 | public void TestGetOfProductCompositService() 18 | { 19 | IRestClient client = new RestClient("http://localhost:9090"); 20 | IRestRequest request = new RestRequest() 21 | { 22 | Method = Method.GET, 23 | Resource = "/productinfo/123" 24 | }; 25 | request.AddHeader("Accept", "application/json"); 26 | var response = client.Get(request); 27 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /RestSharpAutomation/RestPostEndpoint/FileUploadEndPoint.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.RestPostEndpoint 11 | { 12 | [TestClass] 13 | public class FileUploadEndPoint 14 | { 15 | [TestMethod] 16 | public void Test_Upload_Of_File() 17 | { 18 | IRestClient client = new RestClient(); 19 | IRestRequest request = new RestRequest() 20 | { 21 | Resource = "https://jobportalkarate.herokuapp.com/normal/webapi/upload" 22 | }; 23 | 24 | request.AddFile("file", @"C:\Users\rathr1\Desktop\PipeLine-Command.txt", "multipart/form-data"); 25 | var response = client.Post(request); 26 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 27 | 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/ListFolderModel/Entry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.DropBoxAPI.ListFolderModel 8 | { 9 | public class Entry 10 | { 11 | public string tag { get; set; } 12 | public string name { get; set; } 13 | public string id { get; set; } 14 | public DateTime client_modified { get; set; } 15 | public DateTime server_modified { get; set; } 16 | public string rev { get; set; } 17 | public int size { get; set; } 18 | public string path_lower { get; set; } 19 | public string path_display { get; set; } 20 | public SharingInfo sharing_info { get; set; } 21 | public bool is_downloadable { get; set; } 22 | public List property_groups { get; set; } 23 | public bool has_explicit_shared_members { get; set; } 24 | public string content_hash { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/RestResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Model 8 | { 9 | public class RestResponse 10 | { 11 | private int statusCode; 12 | private string responseData; 13 | 14 | public RestResponse(int statusCode,string responseData) 15 | { 16 | this.statusCode = statusCode; 17 | this.responseData = responseData; 18 | } 19 | 20 | public int StatusCode 21 | { 22 | get 23 | { 24 | return statusCode; 25 | } 26 | } 27 | 28 | public string ResponseContent 29 | { 30 | get 31 | { 32 | return responseData; 33 | } 34 | } 35 | 36 | public override string ToString() 37 | { 38 | return String.Format("StatsCode : {0} ResponseData : {1}", statusCode, responseData); 39 | } 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /HttpInterceptor/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/APIResponse/Response.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper.APIResponse 9 | { 10 | public class Response : AbstractResponse 11 | { 12 | private readonly RestResponse _restResponse; 13 | 14 | public Response(RestResponse restResponse) : base(restResponse) 15 | { 16 | _restResponse = restResponse; 17 | } 18 | 19 | public override string GetResponseData() 20 | { 21 | return _restResponse.Content; 22 | } 23 | } 24 | 25 | public class Response : AbstractResponse 26 | { 27 | private readonly RestResponse _restResponse; 28 | 29 | public Response(RestResponse restResponse) : base(restResponse) 30 | { 31 | _restResponse = restResponse; 32 | } 33 | 34 | public override T GetResponseData() 35 | { 36 | return _restResponse.Data; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MsTestProject/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/Model/Entry.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.DropBox.Model 9 | { 10 | public class Entry 11 | { 12 | [JsonProperty(".tag")] 13 | public string Tag { get; set; } 14 | public DateTime client_modified { get; set; } 15 | public string content_hash { get; set; } 16 | public FileLockInfo file_lock_info { get; set; } 17 | public bool has_explicit_shared_members { get; set; } 18 | public string id { get; set; } 19 | public bool is_downloadable { get; set; } 20 | public string name { get; set; } 21 | public string path_display { get; set; } 22 | public string path_lower { get; set; } 23 | public List property_groups { get; set; } 24 | public string rev { get; set; } 25 | public DateTime server_modified { get; set; } 26 | public SharingInfo sharing_info { get; set; } 27 | public int size { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /WebServiceAutomation/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/FileUpload/FileUpload.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharp.Serialization; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.Question.FileUpload 12 | { 13 | [TestClass] 14 | public class FileUpload 15 | { 16 | [TestMethod] 17 | public void Test_File_Upload_With_File_From_Device() 18 | { 19 | IRestClient client = new RestClient(); 20 | IRestRequest request = new RestRequest() 21 | { 22 | Resource = "http://localhost:9191/normal/webapi/upload", 23 | Method = Method.POST 24 | }; 25 | request.AddHeader("Accept", "application/json"); 26 | request.AddFile("file", @"C:\Users\rathr1\Downloads\rathr1.pem", "multipart/form-data"); 27 | 28 | var response = client.Post(request); 29 | Console.WriteLine(response.StatusCode); 30 | Console.WriteLine(response.Content); 31 | 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Client/BasicAuthDecorator.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using RestSharp.Authenticators; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.APIHelper.Client 10 | { 11 | public class BasicAuthDecorator : IClient 12 | { 13 | private readonly IClient _client; 14 | 15 | public BasicAuthDecorator(IClient client) // Default Client //Tracer Client 16 | { 17 | _client = client; 18 | } 19 | public void Dispose() 20 | { 21 | _client.Dispose(); 22 | } 23 | 24 | public RestClient GetClient() 25 | { 26 | //1. Invoke _client.GetClient() API 27 | 28 | var newClient = _client.GetClient(); // Plain RestClient // Rest Client + Tracer 29 | 30 | //2. Add the auth configuration 31 | newClient.Authenticator = new HttpBasicAuthenticator("admin", "welcome"); 32 | //3. return the new client 33 | return newClient; // Plain RestClient + Auth Config 34 | // Rest Client + Tracer + Auth Config 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /RestSharpLatest/SessionBasedAuth/JiraApplication/TestJiraLogin.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharpLatest.SessionBasedAuth.JiraApplication.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpLatest.SessionBasedAuth.JiraApplication 12 | { 13 | [TestClass] 14 | public class TestJiraLogin 15 | { 16 | private readonly string BaseUrl = "http://localhost:9191/"; 17 | 18 | [TestMethod] 19 | public void LoginIntoJira() 20 | { 21 | var client = new RestClient(BaseUrl); 22 | var request = new RestRequest() 23 | { 24 | Resource = "/rest/auth/1/session", 25 | Method = Method.Post 26 | }; 27 | 28 | request.AddJsonBody(new { 29 | username = "rahul", 30 | password = "admin@1234#" 31 | }); 32 | 33 | var response = client.Execute(request); 34 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /RestSharpAutomation/CustomSerializer/CustomXmlSerializer.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using RestSharp.Deserializers; 3 | using RestSharp.Serialization; 4 | using RestSharp.Serializers; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.CustomSerializer 12 | { 13 | public class CustomXmlSerializer : IRestSerializer 14 | { 15 | string[] IRestSerializer.SupportedContentTypes => throw new NotImplementedException(); 16 | 17 | DataFormat IRestSerializer.DataFormat => throw new NotImplementedException(); 18 | 19 | string ISerializer.ContentType { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } 20 | 21 | T IDeserializer.Deserialize(IRestResponse response) 22 | { 23 | throw new NotImplementedException(); 24 | } 25 | 26 | string IRestSerializer.Serialize(Parameter parameter) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | 31 | string ISerializer.Serialize(object obj) 32 | { 33 | throw new NotImplementedException(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/Request/CreateProjectPayload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpAutomation.JiraAPI.Request 8 | { 9 | public class CreateProjectPayload 10 | { 11 | public string key { get; set; } = "EX" + new Random().Next(1000); 12 | public string name { get; set; } = "Example" + new Random().Next(1000); 13 | public string projectTypeKey { get; set; } = "business"; 14 | public string projectTemplateKey { get; set; } = "com.atlassian.jira-core-project-templates:jira-core-project-management"; 15 | public string description { get; set; } = "Example Project description"; 16 | public string lead { get; set; } = "rahul"; 17 | public string url { get; set; } = "http://atlassian.com"; 18 | public string assigneeType { get; set; } = "PROJECT_LEAD"; 19 | public int avatarId { get; set; } = 10324; 20 | //public int issueSecurityScheme { get; set; } 21 | //public int permissionScheme { get; set; } 22 | //public int notificationScheme { get; set; } 23 | //public int categoryId { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/AbstractRequest.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper 9 | { 10 | public abstract class AbstractRequest 11 | { 12 | public abstract RestRequest Build(); 13 | 14 | // For URL 15 | 16 | protected virtual void WithUrl(string url, RestRequest restRequest) 17 | { 18 | restRequest.Resource = url; 19 | } 20 | 21 | protected virtual void WithHeaders(Dictionary header, RestRequest restRequest) 22 | { 23 | foreach (string key in header.Keys) 24 | { 25 | restRequest.AddOrUpdateHeader(key, header[key]); 26 | } 27 | } 28 | 29 | // 30 | //QueryParameter 31 | 32 | protected virtual void WithQueryParameters(Dictionary parameters, RestRequest restRequest) 33 | { 34 | foreach (string key in parameters.Keys) 35 | { 36 | restRequest.AddParameter(key, parameters[key]); 37 | } 38 | } 39 | // URL Segments 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /RestSharpLatest/SessionBasedAuth/JiraApplication/Model/CreateProjectPayload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.SessionBasedAuth.JiraApplication.Model 8 | { 9 | public class CreateProjectPayload 10 | { 11 | public string key { get; set; } = "EX" + new Random().Next(1000); 12 | public string name { get; set; } = "Example" + new Random().Next(1000); 13 | public string projectTypeKey { get; set; } = "business"; 14 | public string projectTemplateKey { get; set; } = "com.atlassian.jira-core-project-templates:jira-core-project-management"; 15 | public string description { get; set; } = "Example Project description"; 16 | public string lead { get; set; } = "rahul"; 17 | public string url { get; set; } = "http://atlassian.com"; 18 | public string assigneeType { get; set; } = "PROJECT_LEAD"; 19 | public int avatarId { get; set; } = 10324; 20 | //public int issueSecurityScheme { get; set; } 21 | //public int permissionScheme { get; set; } 22 | //public int notificationScheme { get; set; } 23 | //public int categoryId { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/FileUpload/TestZamZarUpload.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharp.Authenticators; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.Question.FileUpload 11 | { 12 | [TestClass] 13 | public class TestZamZarUpload 14 | { 15 | private string baseurl = "https://sandbox.zamzar.com/v1/jobs"; 16 | 17 | [TestMethod] 18 | public void uploading() 19 | { 20 | 21 | IRestClient client = new RestClient(); 22 | client.Authenticator = new HttpBasicAuthenticator("969bed863c84fea859fe48bc57ae13dbf1f28da1", " "); 23 | 24 | IRestRequest request = new RestRequest() 25 | { 26 | Resource = baseurl 27 | }; 28 | 29 | request.AddHeader("Accept", "application/json"); 30 | request.AddFile("source_file", @"C:\Data\log\2.gif", "multipart/form-data"); 31 | request.AddParameter("target_format", "png", ParameterType.RequestBody); 32 | 33 | IRestResponse restResponse = client.Post(request); 34 | Assert.AreEqual(201, (int)restResponse.StatusCode); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Client/AuthenticationDecorato.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using RestSharp.Authenticators; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.APIHelper.Client 10 | { 11 | public class AuthenticationDecorato : IClient 12 | { 13 | private readonly IClient _client; 14 | private readonly AuthenticatorBase _authenticatorBase; 15 | 16 | public AuthenticationDecorato(IClient client, AuthenticatorBase authenticator) // Default Client //Tracer Client 17 | { 18 | _client = client; 19 | _authenticatorBase = authenticator; 20 | } 21 | public void Dispose() 22 | { 23 | _client.Dispose(); 24 | } 25 | 26 | public RestClient GetClient() 27 | { 28 | //1. Invoke _client.GetClient() API 29 | 30 | var newClient = _client.GetClient(); // Plain RestClient // Rest Client + Tracer 31 | 32 | //2. Add the auth configuration 33 | newClient.Authenticator = _authenticatorBase; 34 | //3. return the new client 35 | return newClient; // Plain RestClient + Auth Config 36 | // Rest Client + Tracer + Auth Config 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /RestSharpAutomation/QueryParameter/QueryParameter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using WebServiceAutomation.Model.XmlModel; 9 | 10 | namespace RestSharpAutomation.QueryParameter 11 | { 12 | [TestClass] 13 | public class QueryParameter 14 | { 15 | private string searchUrl = "http://localhost:8080/laptop-bag/webapi/api/query"; 16 | 17 | [TestMethod] 18 | public void TestQueryParameter() 19 | { 20 | IRestClient client = new RestClient(); 21 | IRestRequest request = new RestRequest() 22 | { 23 | Resource = searchUrl 24 | }; 25 | 26 | request.AddHeader("Accept", "application/xml"); 27 | // 1st apporach 28 | //request.AddParameter("id", "1", ParameterType.QueryString); 29 | request.AddQueryParameter("id", "1"); 30 | request.AddQueryParameter("laptopName", "Alienware M17"); 31 | 32 | var response = client.Get(request); 33 | 34 | Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode); 35 | Assert.AreEqual("Alienware", response.Data.BrandName); 36 | 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /RestSharpLatest/GetRequest/TestApiHelperGet.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharpLatest.APIHelper; 3 | using RestSharpLatest.APIHelper.APIRequest; 4 | using RestSharpLatest.APIHelper.Client; 5 | using RestSharpLatest.APIHelper.Command; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace RestSharpLatest.GetRequest 13 | { 14 | [TestClass] 15 | public class TestApiHelperGet 16 | { 17 | private IClient _client; 18 | private readonly string getUrl = "http://localhost:8081/laptop-bag/webapi/api/all"; 19 | 20 | public void SetUp() 21 | { 22 | _client = new DefaultClient(); 23 | } 24 | 25 | 26 | [TestMethod] 27 | public void GetRequestWithApiHelper() 28 | { 29 | var headers = new Dictionary() 30 | { 31 | { "Accept", "application/json"} 32 | }; 33 | AbstractRequest abstractRequest = new GetRequestBuilder().WithUrl(getUrl).WithHeaders(headers); 34 | ICommand getCommand = new RequestCommand(abstractRequest, _client); 35 | } 36 | 37 | public void TearDown() 38 | { 39 | _client?.Dispose(); 40 | } 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Testrun.runsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 4 6 | 7 | 8 | 9 | 10 | 11 | x86 12 | 13 | 14 | 15 | 16 | 17 | %SystemDrive%\Temp\foo;%SystemDrive%\Temp\bar 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 31 | 32 | 33 | 34 | 4 35 | MethodLevel 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /WebServiceAutomation/Testrun.runsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 4 6 | 7 | 8 | 9 | 10 | 11 | x86 12 | 13 | 14 | 15 | 16 | 17 | %SystemDrive%\Temp\foo;%SystemDrive%\Temp\bar 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 31 | 32 | 33 | 34 | 4 35 | MethodLevel 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/APIRequest/GetRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper.APIRequest 9 | { 10 | public class GetRequestBuilder : AbstractRequest 11 | { 12 | private readonly RestRequest _restRequest; 13 | 14 | public GetRequestBuilder() 15 | { 16 | _restRequest = new RestRequest() 17 | { 18 | Method = Method.Get 19 | }; 20 | } 21 | 22 | public override RestRequest Build() 23 | { 24 | return _restRequest; 25 | } 26 | 27 | // URL 28 | 29 | public GetRequestBuilder WithUrl(string url) 30 | { 31 | WithUrl(url, _restRequest); 32 | return this; 33 | } 34 | 35 | // Req headers 36 | 37 | public GetRequestBuilder WithHeaders(Dictionary headers) 38 | { 39 | WithHeaders(headers, _restRequest); 40 | return this; 41 | } 42 | 43 | //QueryParameter 44 | public GetRequestBuilder WithQueryParameters(Dictionary parameters) 45 | { 46 | WithQueryParameters(parameters, _restRequest); 47 | return this; 48 | } 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/XmlModel/XmlModelBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | 4 | namespace WebServiceAutomation.Model.XmlModel 5 | { 6 | public class XmlModelBuilder 7 | { 8 | private string _BrandName { get; set; } 9 | private Features _Features { get; set; } 10 | private string _Id { get; set; } 11 | private string _LaptopName { get; set; } 12 | 13 | public Laptop Build() 14 | { 15 | return new Laptop() 16 | { 17 | BrandName = _BrandName, 18 | Features = _Features, 19 | Id = _Id, 20 | LaptopName = _LaptopName 21 | }; 22 | } 23 | 24 | public XmlModelBuilder WithBrandName(string name) 25 | { 26 | _BrandName = name; 27 | return this; 28 | } 29 | 30 | public XmlModelBuilder WithId(int id) 31 | { 32 | _Id = id.ToString(); 33 | return this; 34 | } 35 | 36 | public XmlModelBuilder WithLaptopName(string name) 37 | { 38 | _LaptopName = name; 39 | return this; 40 | } 41 | 42 | public XmlModelBuilder WithFeatures(List feature) 43 | { 44 | _Features = new Features() 45 | { 46 | Feature = feature 47 | }; 48 | return this; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/TestJiraAPI.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharpAutomation.JiraAPI.Request; 4 | using RestSharpAutomation.JiraAPI.Response; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.JiraAPI 12 | { 13 | [TestClass] 14 | public class TestJiraAPI 15 | { 16 | private const string LoginEndpoint = "/rest/auth/1/session"; 17 | 18 | [TestMethod] 19 | public void TestJiraLogin() 20 | { 21 | JiraLogin jiraLogin = new JiraLogin() 22 | { 23 | username = "rahul", 24 | password = "admin@1234#" 25 | }; 26 | 27 | IRestClient client = new RestClient() 28 | { 29 | BaseUrl = new Uri("http://localhost:9191") 30 | }; 31 | 32 | IRestRequest request = new RestRequest() 33 | { 34 | Resource = LoginEndpoint 35 | }; 36 | request.RequestFormat = DataFormat.Json; 37 | request.AddJsonBody(jiraLogin); 38 | request.AddHeader("Contenet-Type", "application/json"); 39 | 40 | var response = client.Post(request); 41 | Console.WriteLine(response.Data); 42 | 43 | 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/PostFormData/TestFormData.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpAutomation.Question.PostFormData 10 | { 11 | [TestClass] 12 | public class TestFormData 13 | { 14 | 15 | [TestMethod] 16 | public void Test_Post_of_Form_Data() 17 | { 18 | IRestClient client = new RestClient(); 19 | IRestRequest request = new RestRequest() 20 | { 21 | Resource = "https://api.eventbaja.com/api/v2/registration" 22 | 23 | }; 24 | 25 | request.AddParameter("role", "vendor", ParameterType.GetOrPost); 26 | request.AddParameter("user", "test@mailinator", ParameterType.GetOrPost); 27 | request.AddParameter("address", "89", ParameterType.GetOrPost); 28 | request.AddParameter("password", "qwertyui", ParameterType.GetOrPost); 29 | request.AddParameter("password_confirmation", "qwertyui", ParameterType.GetOrPost); 30 | request.AddParameter("otp", "526524", ParameterType.GetOrPost); 31 | request.AddParameter("confirm otp", "526524", ParameterType.GetOrPost); 32 | 33 | 34 | var response = client.Post(request); 35 | Console.WriteLine(response.StatusCode); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/AbstractResponse.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.APIHelper 10 | { 11 | public abstract class AbstractResponse : IResponse 12 | { 13 | private readonly RestResponse _restResponse; 14 | 15 | public AbstractResponse(RestResponse restResponse) 16 | { 17 | _restResponse = restResponse; 18 | } 19 | 20 | public Exception GetException() 21 | { 22 | return _restResponse.ErrorException; 23 | } 24 | 25 | public HttpStatusCode GetHttpStatusCode() 26 | { 27 | return _restResponse.StatusCode; 28 | } 29 | 30 | public abstract string GetResponseData(); 31 | } 32 | 33 | public abstract class AbstractResponse : IResponse 34 | { 35 | 36 | private readonly RestResponse _restResponse; 37 | 38 | public AbstractResponse(RestResponse restResponse) 39 | { 40 | _restResponse = restResponse; 41 | } 42 | 43 | public Exception GetException() 44 | { 45 | return _restResponse.ErrorException; 46 | } 47 | 48 | public HttpStatusCode GetHttpStatusCode() 49 | { 50 | return _restResponse.StatusCode; 51 | } 52 | 53 | public abstract T GetResponseData(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /RestSharpLatest/ReportAttribute/TestMethodWithReport.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharpAutomation.CustomReporter; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.ReportAttribute 11 | { 12 | /*** 13 | 1. Create a class which inherit from TestMethodAttribute 14 | 2. Overirde the Execute method to provide the implementation 15 | 3. Use the custom attribute with testmethod 16 | */ 17 | [AttributeUsage(AttributeTargets.Method,AllowMultiple = false)] 18 | public class TestMethodWithReport : TestMethodAttribute 19 | { 20 | private readonly object syslock = new object(); 21 | public override TestResult[] Execute(ITestMethod testMethod) 22 | { 23 | var name = testMethod.TestClassName + "." + testMethod.TestMethodName; 24 | var result = base.Execute(testMethod); 25 | var execution = result.FirstOrDefault(); 26 | var status = execution.Outcome; 27 | var errormsg = execution?.TestFailureException?.Message; 28 | var trace = execution?.TestFailureException?.StackTrace; 29 | 30 | lock (syslock) 31 | { 32 | CustomeExtentRepoter.GetInstance().AddToReport(name, "", status, errormsg + "\n" + trace); 33 | } 34 | 35 | return result; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RestSharpAutomation/ReportAttribute/TestMethodWithReport.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharpAutomation.CustomReporter; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.ReportAttribute 11 | { 12 | /*** 13 | 1. Create a class which inherit from TestMethodAttribute 14 | 2. Overirde the Execute method to provide the implementation 15 | 3. Use the custom attribute with testmethod 16 | */ 17 | [AttributeUsage(AttributeTargets.Method,AllowMultiple = false)] 18 | public class TestMethodWithReport : TestMethodAttribute 19 | { 20 | private readonly object syslock = new object(); 21 | public override TestResult[] Execute(ITestMethod testMethod) 22 | { 23 | var name = testMethod.TestClassName + "." + testMethod.TestMethodName; 24 | var result = base.Execute(testMethod); 25 | var execution = result.FirstOrDefault(); 26 | var status = execution.Outcome; 27 | var errormsg = execution?.TestFailureException?.Message; 28 | var trace = execution?.TestFailureException?.StackTrace; 29 | 30 | lock (syslock) 31 | { 32 | CustomeExtentRepoter.GetInstance().AddToReport(name, "", status, errormsg + "\n" + trace); 33 | } 34 | 35 | return result; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Command/RequestCommand.cs: -------------------------------------------------------------------------------- 1 | using RestSharpLatest.APIHelper.APIResponse; 2 | using RestSharp; 3 | using System.Threading.Tasks; 4 | 5 | namespace RestSharpLatest.APIHelper.Command 6 | { 7 | public class RequestCommand : ICommand 8 | { 9 | private readonly IClient _client; 10 | private readonly AbstractRequest _abstractRequest; 11 | 12 | public RequestCommand(AbstractRequest abstractRequest, IClient client) 13 | { 14 | _abstractRequest = abstractRequest; 15 | _client = client; 16 | } 17 | 18 | public byte[] DownloadData() 19 | { 20 | throw new System.NotImplementedException("Use the Download Command for File Downlaod"); 21 | } 22 | 23 | public Task DownloadDataAsync() 24 | { 25 | throw new System.NotImplementedException("Use the Download Command for File Downlaod"); 26 | } 27 | 28 | public IResponse ExecuteRequest() 29 | { 30 | var client = _client.GetClient(); 31 | var request = _abstractRequest.Build(); 32 | var response = client.Execute(request); 33 | return new Response(response); 34 | } 35 | 36 | public IResponse ExecuteRequest() 37 | { 38 | var client = _client.GetClient(); 39 | var request = _abstractRequest.Build(); 40 | var response = client.Execute(request); 41 | return new Response(response); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /RestSharpLatest/APIModel/JsonApiModel/JsonModelBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace RestSharpLatest.APIModel.JsonApiModel 8 | { 9 | public class JsonModelBuilder 10 | { 11 | private string _BrandName { get; set; } 12 | private Features _Features { get; set; } 13 | private int _Id { get; set; } 14 | private string _LaptopName { get; set; } 15 | 16 | public JsonModel Build() 17 | { 18 | return new JsonModel() 19 | { 20 | BrandName = _BrandName, 21 | Features = _Features, 22 | Id = _Id, 23 | LaptopName = _LaptopName 24 | }; 25 | } 26 | 27 | public JsonModelBuilder WithBrandName(string name) 28 | { 29 | _BrandName = name; 30 | return this; 31 | } 32 | 33 | public JsonModelBuilder WithId(int id) 34 | { 35 | _Id = id; 36 | return this; 37 | } 38 | 39 | public JsonModelBuilder WithLaptopName(string name) 40 | { 41 | _LaptopName = name; 42 | return this; 43 | } 44 | 45 | public JsonModelBuilder WithFeatures(List feature) 46 | { 47 | _Features = new Features() 48 | { 49 | Feature = feature 50 | }; 51 | return this; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /WebServiceAutomation/Model/JsonModel/JsonRootObjectBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WebServiceAutomation.Model.JsonModel 8 | { 9 | public class JsonRootObjectBuilder 10 | { 11 | private string _BrandName { get; set; } 12 | private Features _Features { get; set; } 13 | private int _Id { get; set; } 14 | private string _LaptopName { get; set; } 15 | 16 | public JsonRootObject Build() 17 | { 18 | return new JsonRootObject() 19 | { 20 | BrandName = _BrandName, 21 | Features = _Features, 22 | Id = _Id, 23 | LaptopName = _LaptopName 24 | }; 25 | } 26 | 27 | public JsonRootObjectBuilder WithBrandName(string name) 28 | { 29 | _BrandName = name; 30 | return this; 31 | } 32 | 33 | public JsonRootObjectBuilder WithId(int id) 34 | { 35 | _Id = id; 36 | return this; 37 | } 38 | 39 | public JsonRootObjectBuilder WithLaptopName(string name) 40 | { 41 | _LaptopName = name; 42 | return this; 43 | } 44 | 45 | public JsonRootObjectBuilder WithFeatures(List feature) 46 | { 47 | _Features = new Features() 48 | { 49 | Feature = feature 50 | }; 51 | return this; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/APIRequest/DeleteRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RestSharpLatest.APIHelper.APIRequest 9 | { 10 | public class DeleteRequestBuilder : AbstractRequest 11 | { 12 | private readonly RestRequest _restRequest; 13 | 14 | public DeleteRequestBuilder() 15 | { 16 | _restRequest = new RestRequest() 17 | { 18 | Method = Method.Delete 19 | }; 20 | } 21 | 22 | public override RestRequest Build() 23 | { 24 | return _restRequest; 25 | } 26 | 27 | // URL 28 | 29 | public DeleteRequestBuilder WithUrl(string url) 30 | { 31 | WithUrl(url, _restRequest); 32 | return this; 33 | } 34 | 35 | // Req headers 36 | 37 | public DeleteRequestBuilder WithDefaultHeaders() 38 | { 39 | WithHeaders(null, _restRequest); 40 | return this; 41 | } 42 | 43 | protected override void WithHeaders(Dictionary header, RestRequest restRequest) 44 | { 45 | restRequest.AddOrUpdateHeader("Accept", "text/plain"); 46 | } 47 | 48 | //QueryParameter 49 | public DeleteRequestBuilder WithQueryParameters(Dictionary parameters) 50 | { 51 | WithQueryParameters(parameters, _restRequest); 52 | return this; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MsTestProject/TestContextClass.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace MsTestProject 10 | { 11 | [TestClass] 12 | public class TestContextClass 13 | { 14 | private TestContext testContextInstance; 15 | 16 | private delegate void TestImplDelegate(); 17 | public TestContext TestContext 18 | { 19 | get 20 | { 21 | return testContextInstance; 22 | } 23 | set 24 | { 25 | testContextInstance = value; 26 | } 27 | } 28 | 29 | [TestInitialize] 30 | public void BeforeMethod() 31 | { 32 | Console.WriteLine("Before Test"); 33 | } 34 | 35 | [TestMethod] 36 | public void TestMethodOne() 37 | { 38 | throw new Exception("Exception"); 39 | } 40 | 41 | [TestCleanup] 42 | public void AfterMethod() 43 | { 44 | /* 45 | In NUNIT We have below code to achieve my goal..Do we have anything in MSTest to achieve the same? 46 | if (TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Failed) 47 | Console.WriteLine(TestContext.CurrentContext.Result.Message); 48 | */ 49 | 50 | if (testContextInstance.CurrentTestOutcome == UnitTestOutcome.Failed) 51 | { 52 | } 53 | 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /MsTestProject/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace MsTestProject 5 | { 6 | [TestClass] 7 | public class UnitTest1 8 | { 9 | [TestMethod, TestCategory("Smoke")] 10 | public void TestMethod1() // 5th , 6th,7 11 | { 12 | Console.WriteLine(" Test Method One"); 13 | } 14 | 15 | [TestMethod] 16 | [Ignore] 17 | public void TestMethod2() // 2nd, 3rd, 4 18 | { 19 | Console.WriteLine(" Test Method Two "); 20 | } 21 | 22 | [TestInitialize] 23 | public void Setup() // 1st , 4th , 2 , 5th, 3,6 24 | { 25 | Console.WriteLine(" This is Setup "); 26 | } 27 | 28 | [TestCleanup] 29 | public void TearDown() // 3rd, 6th, 4th, 7th,5,8 30 | { 31 | Console.WriteLine(" This is Clean up"); 32 | } 33 | 34 | [ClassInitialize] 35 | public static void ClassSetup(TestContext testContext) //1 ,2 36 | { 37 | Console.WriteLine(" Class Set up "); 38 | } 39 | 40 | [ClassCleanup] 41 | public static void ClassTearDown() //8th,9 42 | { 43 | Console.WriteLine(" Class Tear Down "); 44 | } 45 | 46 | [AssemblyInitialize] 47 | public static void AssemblySetup(TestContext testContext) // 1 48 | { 49 | Console.WriteLine(" Assembly Setup "); 50 | } 51 | 52 | [AssemblyCleanup] 53 | public static void AssemblyTearDown() //10 54 | { 55 | Console.WriteLine(" Assembly Tear Down "); 56 | } 57 | 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/File_Upload_using_RestSharp_api/Assignment_Post_File_Upload.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpLatest.Assignment.File_Upload_using_RestSharp_api 12 | { 13 | [TestClass] 14 | public class Assignment_Post_File_Upload 15 | { 16 | private readonly string BasePath = "http://localhost:9191/"; 17 | 18 | // Assignment - File Upload from the local file system 19 | [TestMethod] 20 | public void File_Upload() 21 | { 22 | // File to upload 23 | var filePath = @"C:\Data\log\TestData.xlsx"; 24 | 25 | // Create the client 26 | var client = new RestClient(BasePath); 27 | 28 | // Create the Request 29 | var fileUploadRequest = new RestRequest() 30 | { 31 | Resource = "normal/webapi/upload", 32 | Method = Method.Post 33 | }; 34 | 35 | // call the Add file api and pass complete path to the file. 36 | fileUploadRequest.AddFile("file", filePath, "multipart/form-data"); 37 | 38 | // send the request 39 | var resposne = client.Execute(fileUploadRequest); 40 | 41 | // verify the response status code. 42 | resposne.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 43 | 44 | // Release the resource acquired by the client. 45 | client.Dispose(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /RestSharpAutomation/DropBoxAPI/TestGenerateToken.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharp.Authenticators; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.DropBoxAPI 11 | { 12 | [TestClass] 13 | public class TestGenerateToken 14 | { 15 | private const string AuthorizeUrl = "https://www.dropbox.com/oauth2/authorize"; 16 | private const string GenerateTokenUrl = "https://api.dropboxapi.com/oauth2/token"; 17 | private const string OAuth1 = "https://api.dropboxapi.com/2/auth/token/from_oauth1"; 18 | 19 | [TestMethod] 20 | public void TestGetToken() 21 | { 22 | string body = "{\"oauth1_token\": \"keg8sdb86l4kdlp\",\"oauth1_token_secret\": \"kusfz7e4twb60k4\"}"; 23 | IRestClient client = new RestClient(); 24 | client.Authenticator = new HttpBasicAuthenticator("keg8sdb86l4kdlp", "kusfz7e4twb60k4"); 25 | IRestRequest request = new RestRequest() 26 | { 27 | Resource = GenerateTokenUrl 28 | }; 29 | 30 | request.AddParameter("code", "authorization_code", ParameterType.QueryString); 31 | request.AddParameter("grant_type", "authorization_code", ParameterType.QueryString); 32 | //request.AddHeader("Content-Type", "application/json"); 33 | //request.RequestFormat = DataFormat.Json; 34 | //request.AddBody(body); 35 | var response = client.Post(request); 36 | Assert.IsNotNull(response.StatusCode); 37 | 38 | 39 | } 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/LargeJson/TestPostWithLargeJson.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.Question.LargeJson 11 | { 12 | [TestClass] 13 | public class TestPostWithLargeJson 14 | { 15 | /* Compex JSON pay load */ 16 | 17 | [TestMethod] 18 | public void Test_Post_With_Large_Json() 19 | { 20 | IRestClient restClient = new RestClient(); 21 | IRestRequest request = new RestRequest() 22 | { 23 | Resource = "" 24 | }; 25 | 26 | request.AddHeader("Content-Type", "application/json"); 27 | request.AddHeader("Accept", "application/xml"); 28 | request.RequestFormat = DataFormat.Json; 29 | var body = GetFileData(@"C:\abc\pqr.json"); 30 | request.AddBody(body); 31 | 32 | IRestResponse response = restClient.Post(request); 33 | Assert.AreEqual(200, (int)response.StatusCode); 34 | Console.WriteLine(response.Content); 35 | } 36 | 37 | private string GetFileData(string fileLocation) 38 | { 39 | string data = ""; 40 | FileInfo info = new FileInfo(fileLocation); 41 | using(FileStream stream = info.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) 42 | { 43 | using(StreamReader reader = new StreamReader(stream)) 44 | { 45 | data = reader.ReadToEnd(); 46 | } 47 | } 48 | return data; 49 | } 50 | 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Command/DownloadRequestCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using RestSharp; 7 | 8 | namespace RestSharpLatest.APIHelper.Command 9 | { 10 | public class DownloadRequestCommand : ICommand 11 | { 12 | private readonly AbstractRequest _abstractRequest; 13 | private readonly IClient _client; 14 | 15 | public DownloadRequestCommand(AbstractRequest abstractRequest, IClient client) 16 | { 17 | _abstractRequest = abstractRequest; 18 | _client = client; 19 | } 20 | 21 | public byte[] DownloadData() 22 | { 23 | // Get the client 24 | var client = _client.GetClient(); 25 | // Build the request 26 | var request = _abstractRequest.Build(); 27 | // call the download api on the client 28 | var data = client.DownloadData(request); 29 | return data; 30 | } 31 | 32 | public Task DownloadDataAsync() 33 | { 34 | // Get the client 35 | var client = _client.GetClient(); 36 | // Build the request 37 | var request = _abstractRequest.Build(); 38 | // call the download api on the client 39 | return client.DownloadDataAsync(request); 40 | } 41 | 42 | public IResponse ExecuteRequest() 43 | { 44 | throw new NotImplementedException("Use Request Command for executing the request"); 45 | } 46 | 47 | public IResponse ExecuteRequest() 48 | { 49 | throw new NotImplementedException("Use Request Command for executing the request"); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /RestSharpLatest/Questions/ExtentReport/ExtentReport_Using_Framework.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharpAutomation.ReportAttribute; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace RestSharpLatest.Questions.ExtentReport 16 | { 17 | [TestClass] 18 | public class ExtentReport_Using_Framework 19 | { 20 | private readonly string BasePath = "http://localhost:9191/"; 21 | private static RestApiExecutor apiExecutor; 22 | private static IClient client; 23 | 24 | [ClassInitialize] 25 | public static void Setup(TestContext testContext) 26 | { 27 | client = new DefaultClient(); 28 | apiExecutor = new RestApiExecutor(); 29 | } 30 | 31 | [ClassCleanup] 32 | public static void TearDown() 33 | { 34 | client?.Dispose(); 35 | } 36 | 37 | [TestMethodWithReport] 38 | public void File_Upload_Using_Framework() 39 | { 40 | var fileContent = File.ReadAllBytes(@"C:\Data\log\TestData.xlsx"); 41 | var fileUploadRequest = new PostRequestBuilder().WithUrl(BasePath + "normal/webapi/upload").WithFileUpload("file", fileContent, "TestData.xlsx"); 42 | var command = new RequestCommand(fileUploadRequest, client); 43 | apiExecutor.SetCommand(command); 44 | var response = apiExecutor.ExecuteRequest(); 45 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Client/TracerClient.cs: -------------------------------------------------------------------------------- 1 | using HttpTracer; 2 | using RestSharp; 3 | using RestSharp.Authenticators; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Net.Http; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace RestSharpLatest.APIHelper.Client 13 | { 14 | public class TracerClient : IClient 15 | { 16 | private readonly RestClientOptions _restClientOptions; 17 | private RestClient _restClient; 18 | 19 | public TracerClient() 20 | { 21 | _restClientOptions = new RestClientOptions(); 22 | 23 | } 24 | 25 | public void Dispose() 26 | { 27 | _restClient?.Dispose(); 28 | } 29 | 30 | public RestClient GetClient() 31 | { 32 | //_restClientOptions.ConfigureMessageHandler = TraceConfig; 33 | /*_restClientOptions.ConfigureMessageHandler = (handler) => 34 | { 35 | var tracer = new HttpTracerHandler(handler, HttpMessageParts.All); 36 | return tracer; 37 | };*/ 38 | 39 | _restClientOptions.ConfigureMessageHandler = (handler) => 40 | { 41 | return new HttpTracerHandler(handler, HttpMessageParts.All); 42 | }; 43 | 44 | _restClientOptions.ThrowOnDeserializationError = true; 45 | // To avoide creating one RestClient per request 46 | if (_restClient == null) 47 | _restClient = new RestClient(_restClientOptions); 48 | 49 | return _restClient; 50 | } 51 | 52 | private HttpMessageHandler TraceConfig(HttpMessageHandler handler) 53 | { 54 | var tracer = new HttpTracerHandler(handler, HttpMessageParts.All); 55 | return tracer; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /RestSharpAutomation/CustomSerializer/CustomJsonSerializer.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using RestSharp; 3 | using RestSharp.Serialization; 4 | using RestSharp.Serialization.Json; 5 | using RestSharpAutomation.Question.Model; 6 | 7 | namespace RestSharpAutomation.CustomSerializer 8 | { 9 | public class CustomJsonSerializer : IRestSerializer 10 | { 11 | public string Serialize(object obj) => CustomSerialize(obj); 12 | 13 | public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); 14 | 15 | public T Deserialize(IRestResponse response) => new JsonSerializer().Deserialize(response); 16 | 17 | public string[] SupportedContentTypes { get; } = 18 | { 19 | "application/json", "text/json", "text/x-json", "text/javascript", "*+json" 20 | }; 21 | 22 | public string ContentType { get; set; } = "application/json"; 23 | 24 | public DataFormat DataFormat { get; } = DataFormat.Json; 25 | 26 | private string CustomSerialize(object @object) 27 | { 28 | JObject jsonObject; 29 | 30 | if (@object is MarginProfile marginProfile) 31 | { 32 | var jsonSerializer = new JsonSerializer(); 33 | var serializeString = jsonSerializer.Serialize(@object); 34 | jsonObject = JObject.Parse(serializeString); 35 | jsonObject.Remove("mileMarkups"); 36 | 37 | JObject mileMarkups = new JObject(); 38 | marginProfile.mileMarkups.ForEach(mile => 39 | { 40 | mileMarkups.Add(new JProperty(mile.MileStart.ToString(), mile.Markup)); 41 | }); 42 | 43 | jsonObject.Add("mileMarkups", mileMarkups); 44 | 45 | serializeString = jsonObject.ToString(Newtonsoft.Json.Formatting.None); 46 | return serializeString; 47 | } 48 | throw new System.Exception($"In Compitable Object {@object.ToString()}"); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /RestSharpLatest/GetRequest/TestGetWithFramework.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharpLatest.APIHelper; 3 | using RestSharpLatest.APIHelper.APIRequest; 4 | using RestSharpLatest.APIHelper.Client; 5 | using RestSharpLatest.APIHelper.Command; 6 | using FluentAssertions; 7 | using System.Diagnostics; 8 | using System.Collections.Generic; 9 | using WebServiceAutomation.Model.JsonModel; 10 | 11 | namespace RestSharpLatest.GetRequest 12 | { 13 | [TestClass] 14 | public class TestGetWithFramework 15 | { 16 | private static IClient client; 17 | private static RestApiExecutor executor; 18 | private readonly string getUrl = "http://localhost:8081/laptop-bag/webapi/api/all"; 19 | 20 | [ClassInitialize] 21 | public static void SetUp(TestContext testContext) 22 | { 23 | client = new DefaultClient(); 24 | executor = new RestApiExecutor(); 25 | } 26 | 27 | [TestMethod] 28 | public void GetRequest() 29 | { 30 | AbstractRequest request = new GetRequestBuilder().WithUrl(getUrl); 31 | ICommand getCommand = new RequestCommand(request, client); 32 | executor.SetCommand(getCommand); 33 | var response = executor.ExecuteRequest(); 34 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 35 | Debug.WriteLine(response.GetResponseData()); 36 | 37 | var typeResponse = executor.ExecuteRequest>(); 38 | Debug.WriteLine(""); 39 | Debug.WriteLine(typeResponse.GetResponseData()); 40 | 41 | request = new GetRequestBuilder().WithUrl("http://www.google.com"); 42 | getCommand = new RequestCommand(request, client); 43 | executor.SetCommand(getCommand); 44 | response = executor.ExecuteRequest(); 45 | Debug.WriteLine(""); 46 | Debug.WriteLine(response.GetResponseData()); 47 | } 48 | 49 | [ClassCleanup] 50 | public static void TearDown() 51 | { 52 | client?.Dispose(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/GET_Request_using_RestSharp_with_JWT/Assignment_Get_with_JWT.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharpLatest.JsonWebToken; 5 | using RestSharpLatest.JsonWebToken.Model; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace RestSharpLatest.Assignment.GET_Request_using_RestSharp_with_JWT 13 | { 14 | [TestClass] 15 | public class Assignment_Get_with_JWT 16 | { 17 | private static readonly string BaseUrl = "http://localhost:9191/"; 18 | 19 | // Assignment - Use the JSON Web Token Authenticator with RestSharp Client 20 | [TestMethod] 21 | public void Secure_Get_With_Jwt_RestClient() 22 | { 23 | // Create the Client 24 | var client = new RestClient() 25 | { 26 | // Set the custom authenticator 27 | Authenticator = new JsonWebTokenAuthenticator(BaseUrl, new User() 28 | { 29 | Id = 3, 30 | Username = "James_2", 31 | Password = "Testing@" 32 | }) 33 | }; 34 | 35 | // Create the Request 36 | var request = new RestRequest() 37 | { 38 | // Set the Get end-point url. 39 | Resource = BaseUrl + "auth/webapi/all", 40 | // Set the Http Method. 41 | Method = Method.Get 42 | }; 43 | 44 | // Send the GET request 45 | var response = client.Execute(request); 46 | 47 | // Validate the status code. 48 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 49 | 50 | // Send the GET request 51 | response = client.Execute(request); 52 | 53 | // Validate the status code. 54 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 55 | 56 | // Release the resource acquired by the client. 57 | client?.Dispose(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /RestSharpLatest/CustomReporter/CustomeExtentRepoter.cs: -------------------------------------------------------------------------------- 1 | using AventStack.ExtentReports; 2 | using AventStack.ExtentReports.Reporter; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.CustomReporter 11 | { 12 | // Sigleton design pattern 13 | public class CustomeExtentRepoter 14 | { 15 | private readonly ExtentHtmlReporter extentHtmlReporter; 16 | private readonly ExtentReports extentReports; 17 | private static CustomeExtentRepoter customeExtentRepoter; 18 | 19 | private CustomeExtentRepoter() 20 | { 21 | extentHtmlReporter = new ExtentHtmlReporter(@"C:\Data\log\restsharp\"); 22 | extentReports = new ExtentReports(); 23 | extentReports.AttachReporter(extentHtmlReporter); 24 | } 25 | 26 | public static CustomeExtentRepoter GetInstance() 27 | { 28 | if(customeExtentRepoter == null) 29 | { 30 | customeExtentRepoter = new CustomeExtentRepoter(); 31 | } 32 | 33 | return customeExtentRepoter; 34 | } 35 | 36 | public void AddToReport(string name, string description, UnitTestOutcome status, string error) 37 | { 38 | // name, 39 | // Descritpion 40 | // Outcome - Pass/Faile 41 | // Error info - Incase of failure 42 | switch (status) 43 | { 44 | case UnitTestOutcome.Passed: 45 | extentReports.CreateTest(name, description).Pass(""); 46 | break; 47 | case UnitTestOutcome.Failed: 48 | extentReports.CreateTest(name, description).Fail(error); 49 | break; 50 | default: 51 | extentReports.CreateTest(name, description).Skip(""); 52 | break; 53 | } 54 | } 55 | 56 | public void WriteToReport() 57 | { 58 | extentReports?.Flush(); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /RestSharpAutomation/CustomReporter/CustomeExtentRepoter.cs: -------------------------------------------------------------------------------- 1 | using AventStack.ExtentReports; 2 | using AventStack.ExtentReports.Reporter; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace RestSharpAutomation.CustomReporter 11 | { 12 | // Sigleton design pattern 13 | public class CustomeExtentRepoter 14 | { 15 | private readonly ExtentHtmlReporter extentHtmlReporter; 16 | private readonly ExtentReports extentReports; 17 | private static CustomeExtentRepoter customeExtentRepoter; 18 | 19 | private CustomeExtentRepoter() 20 | { 21 | extentHtmlReporter = new ExtentHtmlReporter(@"C:\Data\log\restsharp\"); 22 | extentReports = new ExtentReports(); 23 | extentReports.AttachReporter(extentHtmlReporter); 24 | } 25 | 26 | public static CustomeExtentRepoter GetInstance() 27 | { 28 | if(customeExtentRepoter == null) 29 | { 30 | customeExtentRepoter = new CustomeExtentRepoter(); 31 | } 32 | 33 | return customeExtentRepoter; 34 | } 35 | 36 | public void AddToReport(string name, string description, UnitTestOutcome status, string error) 37 | { 38 | // name, 39 | // Descritpion 40 | // Outcome - Pass/Faile 41 | // Error info - Incase of failure 42 | switch (status) 43 | { 44 | case UnitTestOutcome.Passed: 45 | extentReports.CreateTest(name, description).Pass(""); 46 | break; 47 | case UnitTestOutcome.Failed: 48 | extentReports.CreateTest(name, description).Fail(error); 49 | break; 50 | default: 51 | extentReports.CreateTest(name, description).Skip(""); 52 | break; 53 | } 54 | } 55 | 56 | public void WriteToReport() 57 | { 58 | extentReports?.Flush(); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/TestFileDownloadUsingFramework.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp.Authenticators; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace RestSharpLatest.DropBox 16 | { 17 | [TestClass] 18 | public class TestFileDownloadUsingFramework 19 | { 20 | private static RestApiExecutor restApiExecutor; 21 | private static IClient client; 22 | private static IClient authClient; 23 | private static string Token = ""; 24 | private readonly string BasePath = "https://content.dropboxapi.com/2"; 25 | 26 | [ClassInitialize] 27 | public static void Setup(TestContext testContext) 28 | { 29 | client = new TracerClient(); 30 | authClient = new AuthenticationDecorato(client, new JwtAuthenticator(Token)); 31 | restApiExecutor = new RestApiExecutor(); 32 | 33 | } 34 | 35 | [ClassCleanup] 36 | public static void TearDown() 37 | { 38 | authClient?.Dispose(); 39 | } 40 | 41 | [TestMethod] 42 | public void DownloadFile_UsingFramework() 43 | { 44 | var fileName = "Video.mp4"; 45 | var contextPath = "/files/download"; 46 | var location = "{\"path\":\"/" + fileName + "\"}"; 47 | 48 | var postRequest = new PostRequestBuilder().WithUrl(BasePath + contextPath).WithHeaders(new Dictionary() { { "Dropbox-API-Arg", location } }); 49 | 50 | var command = new DownloadRequestCommand(postRequest, authClient); 51 | restApiExecutor.SetCommand(command); 52 | var data = restApiExecutor.DownloadData(); 53 | File.WriteAllBytes("New_" + fileName, data); 54 | File.Exists("New_" + fileName).Should().BeTrue(); 55 | } 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/Assignment - GET Request/Assignment_Get_Request.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using WebServiceAutomation.Model.XmlModel; 11 | 12 | namespace RestSharpLatest.Assignment.Assignment___GET_Request 13 | { 14 | [TestClass] 15 | public class Assignment_Get_Request 16 | { 17 | // GET end point URL 18 | private readonly string getUrl = "http://localhost:8081/laptop-bag/webapi/api/all"; 19 | 20 | [TestMethod] 21 | public void SendRequestWithExecuteAPI() 22 | { 23 | // Create the Client. 24 | RestClient client = new RestClient(); 25 | 26 | // Sets the RestClient to only use XML. 27 | client.UseXml(); 28 | 29 | // Create the Request. 30 | RestRequest getRequest = new RestRequest() 31 | { 32 | // Set the Http Method. 33 | Method = Method.Get, 34 | // Set the Get end-point url. 35 | Resource = getUrl 36 | }; 37 | 38 | // Send the GET request and de-serialize the response. 39 | var response = client.Execute(getRequest); 40 | 41 | // Validate the status code. 42 | response.StatusCode.Should().Be(HttpStatusCode.OK); 43 | 44 | // Extract the List of objects. 45 | var content = response.Data.Laptop; 46 | 47 | // Extract a single object. 48 | var xmlObject = content.Find((item) => { 49 | return "1".Equals(item.Id, StringComparison.OrdinalIgnoreCase); 50 | }); 51 | 52 | // Validate the BrandName property. 53 | xmlObject.BrandName.Should().NotBeNull(); 54 | // Validate the LaptopName property. 55 | xmlObject.LaptopName.Should().NotBeNull(); 56 | 57 | // Release the resource acquired by the client. 58 | client?.Dispose(); 59 | 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /RestSharpLatest/JsonWebToken/JsonWebTokenAuthenticator.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using RestSharp; 3 | using RestSharp.Authenticators; 4 | using RestSharpLatest.JsonWebToken.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpLatest.JsonWebToken 12 | { 13 | public class JsonWebTokenAuthenticator : AuthenticatorBase 14 | { 15 | // Base URL of the application 16 | private readonly string _baseUrl; 17 | // Username and password of the User 18 | private readonly User _userData; 19 | 20 | public JsonWebTokenAuthenticator(string baseUrl, User userData) : base("") 21 | { 22 | _baseUrl = baseUrl; 23 | _userData = userData; 24 | } 25 | 26 | protected override ValueTask GetAuthenticationParameter(string accessToken) 27 | { 28 | Token = string.IsNullOrEmpty(Token) ? GetToken() : Token; 29 | return new ValueTask(new HeaderParameter(KnownHeaders.Authorization, Token)); 30 | } 31 | 32 | private string GetToken() 33 | { 34 | using(var client = new RestClient(_baseUrl)) 35 | { 36 | //Create a Request for the User Registration /users/sign-up 37 | var regResponse = client.PostJson("users/sign-up", _userData); 38 | // 1. Create a RestRequest of Type POSt 39 | // 2. Ser the given object into JSON rep 40 | // 3. Send the Post request 41 | regResponse.Should().Be(System.Net.HttpStatusCode.OK); 42 | 43 | //Create a Second Request for authenticating the created user /users/authenticate 44 | 45 | var authResponse = client.PostJson("users/authenticate", _userData); 46 | // 1. Create a RestRequest of Type POSt 47 | // 2. Ser the given object into JSON rep 48 | // 3. Send the Post request 49 | // 4. De-ser the response to a given type 50 | authResponse.Token.Should().NotBeNullOrEmpty(); 51 | return $"Bearer {authResponse.Token}"; 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /WebServiceAutomation/Question/TestNestedJson.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace WebServiceAutomation.Question 12 | { 13 | [TestClass] 14 | public class TestNestedJson 15 | { 16 | [TestMethod] 17 | public void TestUsingStatement() 18 | { 19 | using (HttpClient httpClient = new HttpClient()) 20 | { 21 | using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) 22 | { 23 | httpRequestMessage.RequestUri = new Uri("http://dummy.restapiexample.com/api/v1/employees"); 24 | httpRequestMessage.Method = HttpMethod.Get; 25 | httpRequestMessage.Headers.Add("Accept", "application/json"); 26 | Task httpResponse = httpClient.SendAsync(httpRequestMessage); 27 | using (HttpResponseMessage httpResponseMessage = httpResponse.Result) 28 | { 29 | HttpStatusCode status = httpResponseMessage.StatusCode; 30 | using (HttpContent content = httpResponseMessage.Content) 31 | { 32 | using (Task getResponse = content.ReadAsStringAsync()) 33 | { 34 | string output = getResponse.Result; 35 | Employee datum = JsonConvert.DeserializeObject(output); 36 | Console.WriteLine(datum.data[0].id); 37 | } 38 | } 39 | 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | class Datum 47 | { 48 | public string id { get; set; } 49 | public string employee_name { get; set; } 50 | public string employee_salary { get; set; } 51 | public string employee_age { get; set; } 52 | public string profile_image { get; set; } 53 | } 54 | 55 | class Employee 56 | { 57 | public string status { get; set; } 58 | public IList data { get; set; } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Post/PostRequest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharpAutomation.CustomSerializer; 4 | using RestSharpAutomation.Question.Model; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using WebServiceAutomation.Model.XmlModel; 11 | 12 | 13 | namespace RestSharpAutomation.Question.Post 14 | { 15 | [TestClass] 16 | public class PostRequest 17 | { 18 | private string postUrl = "http://localhost:8080/laptop-bag/webapi/api/add"; 19 | private Random random = new Random(); 20 | 21 | [TestMethod] 22 | public void TestPostWithModelObject() 23 | { 24 | IRestClient restClient = new RestClient(); 25 | IRestRequest request = new RestRequest() 26 | { 27 | Resource = postUrl 28 | }; 29 | 30 | request.AddHeader("Content-Type", "application/json"); 31 | request.AddHeader("Accept", "application/xml"); 32 | request.RequestFormat = DataFormat.Json; 33 | request.JsonSerializer = new CustomJsonSerializer(); 34 | request.AddBody(GetProfile()); 35 | 36 | IRestResponse response = restClient.Post(request); 37 | Assert.AreEqual(200, (int)response.StatusCode); 38 | Console.WriteLine(response.Content); 39 | } 40 | 41 | private MarginProfile GetProfile() 42 | { 43 | MileMarkups range1 = new MileMarkups(1, 100); 44 | MileMarkups range2 = new MileMarkups(101, 200); 45 | MileMarkups range3 = new MileMarkups(251, 250); 46 | List ranges = new List() 47 | { 48 | range1, 49 | range2, 50 | range3 51 | }; 52 | 53 | 54 | MarginProfile Profile = new MarginProfile() 55 | { 56 | customerId = 683746, 57 | trailerGroup = "Van", 58 | fuelSurcharge = 3, 59 | overrideDefaultFuelSurcharge = true, 60 | overrideDefaultLDIMarkup = true, 61 | truckPayAdjustment = 1, 62 | overrideDefaultTruckPayAdjustment = true, 63 | overrideDefaultMileMarkups = true, 64 | mileMarkups = ranges 65 | }; 66 | return Profile; 67 | } 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/APIRequest/PutRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using RestSharp.Serializers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.APIHelper.APIRequest 10 | { 11 | public class PutRequestBuilder : AbstractRequest 12 | { 13 | private readonly RestRequest _restRequest; 14 | 15 | public PutRequestBuilder() 16 | { 17 | _restRequest = new RestRequest() 18 | { 19 | Method = Method.Put 20 | }; 21 | } 22 | 23 | public override RestRequest Build() 24 | { 25 | return _restRequest; 26 | } 27 | 28 | //URL 29 | 30 | public PutRequestBuilder WithUrl(string url) 31 | { 32 | WithUrl(url, _restRequest); 33 | return this; 34 | } 35 | 36 | // Headers 37 | public PutRequestBuilder WithHeaders(Dictionary headers) 38 | { 39 | WithHeaders(headers, _restRequest); 40 | return this; 41 | } 42 | 43 | // Body 44 | 45 | public PutRequestBuilder WithBody(T body, RequestBodyType bodyType, string contentType = ContentType.Json) where T : class 46 | { 47 | // String 48 | // Object 49 | 50 | switch (bodyType) 51 | { 52 | case RequestBodyType.STRING: 53 | _restRequest.AddStringBody(body.ToString(), contentType); 54 | break; 55 | case RequestBodyType.JSON: 56 | _restRequest.AddJsonBody(body); 57 | break; 58 | case RequestBodyType.XML: 59 | _restRequest.AddXmlBody(body); 60 | break; 61 | } 62 | return this; 63 | } 64 | 65 | //QueryParameter 66 | public PutRequestBuilder WithQueryParameters(Dictionary parameters) 67 | { 68 | WithQueryParameters(parameters, _restRequest); 69 | return this; 70 | } 71 | 72 | 73 | protected override void WithQueryParameters(Dictionary parameters, RestRequest restRequest) 74 | { 75 | foreach (string key in parameters.Keys) 76 | { 77 | restRequest.AddQueryParameter(key, parameters[key]); 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /RestSharpLatest/FileUpload/TestMultipartFormData.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using System.IO; 9 | 10 | namespace RestSharpLatest.FileUpload 11 | { 12 | [TestClass] 13 | public class TestMultipartFormData 14 | { 15 | private readonly string BasePath = "http://localhost:9191/"; 16 | private static RestApiExecutor apiExecutor; 17 | private static IClient client; 18 | 19 | [ClassInitialize] 20 | public static void Setup(TestContext testContext) 21 | { 22 | client = new TracerClient(); 23 | apiExecutor = new RestApiExecutor(); 24 | } 25 | 26 | [ClassCleanup] 27 | public static void TearDown() 28 | { 29 | client?.Dispose(); 30 | } 31 | 32 | [TestMethod] 33 | public void File_Upload() 34 | { 35 | // Create the client 36 | var client = new RestClient(BasePath); 37 | // Create the Request 38 | var fileUploadRequest = new RestRequest() 39 | { 40 | Resource = "/normal/webapi/upload", 41 | Method = Method.Post 42 | }; 43 | // Read and store the file content in a byte array 44 | var fileContent = File.ReadAllBytes(@"C:\Data\log\TestData.xlsx"); 45 | // call the Add file api and pass the byte array 46 | fileUploadRequest.AddFile("file", fileContent, "TestData.xlsx", "multipart/form-data"); 47 | // send the request 48 | var resposne = client.Execute(fileUploadRequest); 49 | // verify the response status code. 50 | resposne.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 51 | client.Dispose(); 52 | } 53 | 54 | [TestMethod] 55 | public void File_Upload_Using_Framework() 56 | { 57 | var fileContent = File.ReadAllBytes(@"C:\Data\log\TestData.xlsx"); 58 | var fileUploadRequest = new PostRequestBuilder().WithUrl(BasePath + "normal/webapi/upload").WithFileUpload("file", fileContent, "TestData.xlsx"); 59 | var command = new RequestCommand(fileUploadRequest, client); 60 | apiExecutor.SetCommand(command); 61 | var response = apiExecutor.ExecuteRequest(); 62 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 63 | } 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/Post/PostRequestTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.Question.Post 12 | { 13 | [TestClass] 14 | public class PostRequestTests 15 | { 16 | Random generateId = new Random(); 17 | 18 | private string postUrl = "http://localhost:8080/laptop-bag/webapi/api/add"; 19 | 20 | private RestResponse restResponse; 21 | 22 | private string jsonMediaType = "application/json"; 23 | 24 | [TestMethod] 25 | 26 | public void PostRequestTest() 27 | 28 | { 29 | 30 | List ola = new List(); 31 | 32 | ola.Add("8th Generation Intel® Core™ i5 - 8300H"); 33 | 34 | ola.Add("Windows 10 Home 64-bit English"); 35 | 36 | ola.Add("NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6"); 37 | 38 | ola.Add("8GB, 2x4GB, DDR4, 2666MHz"); 39 | 40 | 41 | HttpClient client = new HttpClient(); 42 | 43 | //Setting data into class property to get posted. 44 | 45 | LaptopDetails details = new LaptopDetails() 46 | 47 | { 48 | 49 | BrandName = "Hp Dell Laptop", 50 | 51 | Features = new LapTopFeatures() 52 | 53 | { 54 | 55 | Feature = ola 56 | 57 | }, 58 | 59 | LaptopName = "Pentium 5", 60 | 61 | Id = generateId.Next(1000), 62 | 63 | }; 64 | 65 | 66 | Console.WriteLine($ "My data to post is - {details.ToString()}"); 67 | 68 | HttpContent body = new StringContent(details.ToString(), Encoding.UTF8, jsonMediaType); // Creating the request to fire. 69 | 70 | 71 | 72 | //Fire request.... 73 | 74 | Task postResponse = client.PostAsync(postUrl, body); 75 | 76 | HttpStatusCode statusCode = postResponse.Result.StatusCode; // Receive bad request. 77 | 78 | HttpContent postResponseContent = postResponse.Result.Content; 79 | 80 | string postResponseData = postResponseContent.ReadAsStringAsync().Result; 81 | 82 | 83 | 84 | restResponse = new RestResponse(); 85 | 86 | restResponse.statusCode = (int)statusCode; 87 | 88 | restResponse.responseData = postResponseData; 89 | 90 | Console.WriteLine($"This is my status code and response data - { restResponse.ToString()}"); 91 | 92 | } 93 | } 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /WebServiceAutomation/Helper/Response/ResponseDataHelper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using System.Xml.Serialization; 9 | 10 | namespace WebServiceAutomation.Helper.Response 11 | { 12 | public class ResponseDataHelper 13 | { 14 | 15 | // ResponseDataHelper.DeserializeJsonResponse(restResponse.ResponseContent) 16 | 17 | /* 18 | public static JsonRootObject DeserializeJsonResponse(string responseData) where JsonRootObject : class 19 | { 20 | return JsonConvert.DeserializeObject(responseData); 21 | } 22 | 23 | */ 24 | 25 | // ResponseDataHelper.DeserializeJsonResponse(restResponse.ResponseContent) 26 | 27 | /* 28 | public static Features DeserializeJsonResponse(string responseData) where Features : class 29 | { 30 | return JsonConvert.DeserializeObject(responseData); 31 | } 32 | 33 | */ 34 | 35 | public static T DeserializeJsonResponse(string responseData) where T : class 36 | { 37 | return JsonConvert.DeserializeObject(responseData); 38 | } 39 | 40 | 41 | // ResponseDataHelper.DeserializeXmlResponse(restResponse.ResponseContent) 42 | 43 | /* 44 | 45 | public static LaptopDetailss DeserializeXmlResponse(string responseData) where LaptopDetailss : class 46 | { 47 | XmlSerializer xmlSerializer = new XmlSerializer(typeof(LaptopDetailss)); 48 | TextReader textReader = new StringReader(responseData); 49 | return (LaptopDetailss)xmlSerializer.Deserialize(textReader); 50 | } 51 | 52 | 53 | */ 54 | 55 | // ResponseDataHelper.DeserializeXmlResponse(restResponse.ResponseContent) 56 | 57 | /* 58 | 59 | public static Laptop DeserializeXmlResponse(string responseData) where Laptop : class 60 | { 61 | XmlSerializer xmlSerializer = new XmlSerializer(typeof(Laptop)); 62 | TextReader textReader = new StringReader(responseData); 63 | return (Laptop)xmlSerializer.Deserialize(textReader); 64 | } 65 | 66 | 67 | */ 68 | 69 | 70 | public static T DeserializeXmlResponse(string responseData) where T : class 71 | { 72 | XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 73 | TextReader textReader = new StringReader(responseData); 74 | return (T)xmlSerializer.Deserialize(textReader); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/Client/JiraClient.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using RestSharp; 3 | using RestSharpLatest.SessionBasedAuth.JiraApplication.Model; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace RestSharpLatest.APIHelper.Client 7 | { 8 | public class JiraClient : IJiraClient 9 | { 10 | private RestClient _restClient; 11 | private readonly RestClientOptions _restClientOptions; 12 | 13 | public JiraClient(string baseUrl) 14 | { 15 | _restClientOptions = new RestClientOptions(baseUrl); 16 | _restClient = new RestClient(_restClientOptions); 17 | } 18 | 19 | public void Dispose() 20 | { 21 | _restClient?.Dispose(); 22 | _restClient = null; 23 | } 24 | 25 | public RestClient GetClient() 26 | { 27 | return _restClient; 28 | } 29 | 30 | public void Login(IJiraUser user) 31 | { 32 | // Send the post request to login inside the jira application 33 | var response = _restClient.PostJson("rest/auth/1/session", user); 34 | // 1. Create a RestRequest of Type POSt 35 | // 2. Ser the given object into JSON rep 36 | // 3. Send the Post request 37 | // 4. De-ser the response to a given type 38 | 39 | // Add the validation on session information present in the response 40 | response.session.name.Should().NotBeNullOrEmpty(); 41 | response.session.value.Should().NotBeNullOrEmpty(); 42 | 43 | // Add the session information in the form of cookie to the client 44 | _restClient.AddCookie(response.session.name, response.session.value, "/", "localhost"); 45 | } 46 | 47 | public void Logout() 48 | { 49 | // Create a Rest Request 50 | var request = new RestRequest() 51 | { 52 | Resource = "/rest/auth/1/session" 53 | }; 54 | 55 | // Send the delete request 56 | var response = _restClient.Delete(request); 57 | 58 | // Add the validation on the response status code. 59 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.NoContent); 60 | } 61 | } 62 | 63 | public class AdminJiraUser : IJiraUser 64 | { 65 | [JsonPropertyName("username")] 66 | public string username { get; private set; } 67 | [JsonPropertyName("password")] 68 | public string password { get; private set; } 69 | 70 | public AdminJiraUser(string username, string password) 71 | { 72 | this.username = username; 73 | this.password = password; 74 | } 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /RestSharpAutomation/Jwt Token/TestJwtToken.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharpAutomation.Jwt_Token.Model; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpAutomation.Jwt_Token 12 | { 13 | [TestClass] 14 | public class TestJwtToken 15 | { 16 | /*** 17 | 1. Register the user with the enpoint https://jobapplicationjwt.herokuapp.com/users/sign-up 18 | 2. Autheticate the user and generate the token https://jobapplicationjwt.herokuapp.com/users/authenticate 19 | 3. Extract the token from the response 20 | 4. Pass the token in the header for the Get Request https://jobapplicationjwt.herokuapp.com/auth/webapi/all 21 | 22 | */ 23 | 24 | private string RegisterUrl = "https://jobapplicationjwt.herokuapp.com/users/sign-up"; 25 | private string AuthenticateUrl = "https://jobapplicationjwt.herokuapp.com/users/authenticate"; 26 | private string GetAllUrl = "https://jobapplicationjwt.herokuapp.com/auth/webapi/all"; 27 | private IRestClient client; 28 | private IRestRequest request; 29 | private string token; 30 | private string user = "{ \"password\": \"Guns and Bikes\", \"username\": \"John Wick\"}"; 31 | 32 | 33 | [TestInitialize] 34 | public void SetUp() 35 | { 36 | client = new RestClient(); 37 | // Registration 38 | request = new RestRequest() 39 | { 40 | Resource = RegisterUrl 41 | }; 42 | request.AddJsonBody(user); 43 | var response = client.Post(request); 44 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 45 | 46 | // Generate the token 47 | 48 | request = new RestRequest() 49 | { 50 | Resource = AuthenticateUrl 51 | }; 52 | request.AddJsonBody(user); 53 | var responseToken = client.Post(request); 54 | Assert.AreEqual(HttpStatusCode.OK, responseToken.StatusCode); 55 | token = responseToken.Data.token; // JWT token 56 | } 57 | 58 | [TestMethod] 59 | public void TestGetWithJwt() 60 | { 61 | request = new RestRequest() 62 | { 63 | Resource = GetAllUrl 64 | }; 65 | request.AddHeader("Accept", "application/json"); 66 | request.AddHeader("Authorization", "Bearer " + token); 67 | var response = client.Get(request); 68 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 69 | } 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /RestSharpAutomation/Question/MSLogin/UpdateAPI.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using Newtonsoft.Json; 3 | using Newtonsoft.Json.Linq; 4 | using RestSharp; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Diagnostics; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace RestSharpAutomation.Question.MSLogin 13 | { 14 | [TestClass] 15 | public class UpdateAPI 16 | { 17 | [TestMethod] 18 | public void GetAccessToken() 19 | { 20 | Trace.WriteLine("whatever"); 21 | Debug.WriteLine("Entering Main"); 22 | RestClient client = new RestClient("https://login.microsoftonline.com"); 23 | RestRequest request = new RestRequest("/85722e96-8e10-4794-9933-f05d211175ef/oauth2/token", Method.POST); 24 | 25 | request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); 26 | request.AddHeader("Accept", "*/*"); 27 | request.AddParameter("client_id", "9e6da7a9-93f9-4ca9-b724-0b4ce7e8242d"); 28 | request.AddParameter("client_secret", "YHFw48kLl0R+rFeBAWYL3GVlqwfSyH/KQE+g0Hh7cHY="); 29 | request.AddParameter("grant_type", "client_credentials"); 30 | request.AddParameter("resource", "https://nwsfdevuses0dmdhfhir.azurehealthcareapis.com"); 31 | 32 | IRestResponse restResponse = client.Execute(request); 33 | string response = restResponse.Content; 34 | //int responseCode = (int)client.Execute(request).ResponseStatus; 35 | Debug.WriteLine(response); 36 | // Debug.WriteLine(responseCode); 37 | Trace.WriteLine(response); 38 | //System.Diagnostics.Trace.WriteLine(responseCode); 39 | Trace.WriteLine("END"); 40 | 41 | var data = (JObject)JsonConvert.DeserializeObject(response); 42 | string accessTokenValue = data["access_token"].Value(); 43 | Debug.WriteLine(accessTokenValue); 44 | Trace.WriteLine("END22"); 45 | 46 | RestClient clientget = new RestClient("https://nwsfdevuses0dmdhfhir.azurehealthcareapis.com"); 47 | 48 | RestRequest requestget = new RestRequest("/CarePlan", Method.GET); 49 | requestget.AddHeader("Authorization", "Bearer " + accessTokenValue); 50 | requestget.AddHeader("Accept", "*/*"); 51 | 52 | 53 | IRestResponse restGETResponse = clientget.Execute(requestget); 54 | int responseCode = (int)clientget.Execute(requestget).ResponseStatus; 55 | Debug.WriteLine(responseCode); 56 | 57 | string responseGET = restGETResponse.Content; 58 | Debug.WriteLine(responseGET); 59 | Debug.WriteLine("END77"); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /WebServiceAutomation/JwtToken/HandlingJwtToken.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace WebServiceAutomation.JwtToken 12 | { 13 | [TestClass] 14 | public class HandlingJwtToken 15 | { 16 | private readonly string registerurl = "https://jobapplicationjwt.herokuapp.com/users/sign-up"; 17 | private readonly string authurl = "https://jobapplicationjwt.herokuapp.com/users/authenticate"; 18 | private readonly string geturl = "https://jobapplicationjwt.herokuapp.com/auth/webapi/all"; 19 | private string token = ""; 20 | private readonly string body = "{ \"password\": \"Guns and Bikes\", \"username\": \"John Wick\"}"; 21 | private HttpClient client; 22 | private HttpRequestMessage request; 23 | 24 | private void RegisterUser() 25 | { 26 | request = new HttpRequestMessage(HttpMethod.Post, registerurl) 27 | { 28 | Content = new StringContent(body, Encoding.UTF8, "application/json") 29 | }; 30 | Task responseMessage = client.SendAsync(request); 31 | Assert.AreEqual(HttpStatusCode.OK, responseMessage.Result.StatusCode); 32 | } 33 | 34 | private void GetToken() 35 | { 36 | request = new HttpRequestMessage(HttpMethod.Post, authurl) 37 | { 38 | Content = new StringContent(body, Encoding.UTF8, "application/json") 39 | }; 40 | Task responseMessage = client.SendAsync(request); 41 | Assert.AreEqual(HttpStatusCode.OK, responseMessage.Result.StatusCode); 42 | var content = responseMessage.Result.Content.ReadAsStringAsync(); 43 | var response = JsonConvert.DeserializeObject(content.Result); 44 | token = response.token; 45 | } 46 | 47 | [TestInitialize] 48 | public void Setup() 49 | { 50 | client = new HttpClient(); 51 | RegisterUser(); 52 | GetToken(); 53 | } 54 | 55 | [TestMethod] 56 | public void SendRequstWithJwt() 57 | { 58 | request = new HttpRequestMessage(HttpMethod.Get, geturl); 59 | request.Headers.Add("Accept", "application/json"); 60 | request.Headers.Add("Authorization", "Bearer " + token); 61 | Task responseMessage = client.SendAsync(request); 62 | Assert.AreEqual(HttpStatusCode.OK, responseMessage.Result.StatusCode); 63 | } 64 | 65 | 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /RestSharpLatest/JsonWebToken/TestGetSecureWithJwt.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using RestSharpLatest.JsonWebToken.Model; 9 | 10 | 11 | namespace RestSharpLatest.JsonWebToken 12 | { 13 | [TestClass] 14 | public class TestGetSecureWithJwt 15 | { 16 | private static readonly string BaseUrl = "http://localhost:9191/"; 17 | private static RestApiExecutor apiExecutor; 18 | private static IClient client; 19 | 20 | [ClassInitialize] 21 | public static void SetUp(TestContext testContext) 22 | { 23 | client = new TracerClient(); 24 | client = new AuthenticationDecorato(client, new JsonWebTokenAuthenticator(BaseUrl, new User() 25 | { 26 | Id = 1, 27 | Username = "John", 28 | Password = "Admin@1234#" 29 | })); 30 | 31 | apiExecutor = new RestApiExecutor(); 32 | } 33 | 34 | [ClassCleanup] 35 | public static void TearDown() 36 | { 37 | client?.Dispose(); 38 | } 39 | 40 | [TestMethod] 41 | public void Secure_Get_With_Jwt() 42 | { 43 | var getRequest = new GetRequestBuilder().WithUrl(BaseUrl + "auth/webapi/all"); 44 | var command = new RequestCommand(getRequest, client); 45 | apiExecutor.SetCommand(command); 46 | 47 | var response = apiExecutor.ExecuteRequest(); 48 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 49 | 50 | response = apiExecutor.ExecuteRequest(); 51 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 52 | } 53 | 54 | [TestMethod] 55 | public void Secure_Get_With_Jwt_RestClient() 56 | { 57 | var client = new RestClient() 58 | { 59 | Authenticator = new JsonWebTokenAuthenticator(BaseUrl , new User() 60 | { 61 | Id = 3, 62 | Username = "James_2", 63 | Password = "Testing@" 64 | }) 65 | }; 66 | 67 | var request = new RestRequest() 68 | { 69 | Resource = BaseUrl + "auth/webapi/all", 70 | Method = Method.Get 71 | }; 72 | 73 | var response = client.Execute(request); 74 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 75 | 76 | response = client.Execute(request); 77 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 78 | } 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /WebServiceAutomation/Questions/Post/PostRequestTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Runtime.Serialization.Formatters.Binary; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using WebServiceAutomation.Model; 11 | using WebServiceAutomation.Questions.Model; 12 | 13 | namespace WebServiceAutomation.Questions.Post 14 | { 15 | [TestClass] 16 | public class PostRequestTests 17 | { 18 | Random generateId = new Random(); 19 | private string postUrl = "http://localhost:8080/laptop-bag/webapi/api/add"; 20 | private RestResponse restResponse; 21 | private string jsonMediaType = "application/json"; 22 | 23 | [TestMethod] 24 | public void PostRequestTest() 25 | 26 | { 27 | 28 | List ola = new List 29 | { 30 | "8th Generation Intel® Core™ i5 - 8300H", 31 | "Windows 10 Home 64-bit English", 32 | "NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6", 33 | "8GB, 2x4GB, DDR4, 2666MHz" 34 | }; 35 | 36 | HttpClient client = new HttpClient(); 37 | //Setting data into class property to get posted. 38 | LaptopDetails details = new LaptopDetails() 39 | { 40 | BrandName = "Hp Dell Laptop", 41 | Features = new LapTopFeatures() 42 | { 43 | Feature = ola 44 | }, 45 | LaptopName = "Pentium 5", 46 | Id = generateId.Next(1000), 47 | 48 | }; 49 | Console.WriteLine($"My data to post is - {details.ToString()}"); 50 | HttpContent body = new StringContent(details.ToString(), Encoding.UTF8, jsonMediaType); // Creating the request to fire. 51 | 52 | //Fire request.... 53 | Task postResponse = client.PostAsync(postUrl, body); 54 | HttpStatusCode statusCode = postResponse.Result.StatusCode; // Receive bad request. 55 | HttpContent postResponseContent = postResponse.Result.Content; 56 | string postResponseData = postResponseContent.ReadAsStringAsync().Result; 57 | restResponse = new RestResponse((int)statusCode, postResponseData); 58 | Console.WriteLine($"This is my status code and response data - {restResponse.ToString()}"); 59 | 60 | } 61 | 62 | public static byte[] ObjectToByteArray(LaptopDetails obj) 63 | { 64 | BinaryFormatter bf = new BinaryFormatter(); 65 | using (var ms = new MemoryStream()) 66 | { 67 | bf.Serialize(ms, obj); 68 | return ms.ToArray(); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/TestDownloadFile.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharp.Authenticators; 5 | using System; 6 | using System.IO; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.DropBox 10 | { 11 | [TestClass] 12 | public class TestDownloadFile 13 | { 14 | private readonly string Token = ""; 15 | 16 | private readonly string BasePath = "https://content.dropboxapi.com/2"; 17 | 18 | [TestMethod] 19 | public void DownloadFile() 20 | { 21 | var fileName = "Video.mp4"; 22 | var contextPath = "/files/download"; 23 | var location = "{\"path\":\"/" + fileName + "\"}"; 24 | 25 | var client = new RestClient() 26 | { 27 | Authenticator = new JwtAuthenticator(Token) 28 | }; 29 | 30 | var request = new RestRequest() 31 | { 32 | Resource = BasePath + contextPath, 33 | Method = Method.Post 34 | }; 35 | 36 | request.AddHeader("Dropbox-API-Arg", location); 37 | var data = client.DownloadData(request); 38 | File.WriteAllBytes(fileName, data); 39 | client.Dispose(); 40 | } 41 | 42 | [TestMethod] 43 | public void DownloadData_Parallel() 44 | { 45 | var contextPath = "/files/download"; 46 | 47 | var fileNameOne = "Video.mp4"; 48 | var locationOne = "{\"path\":\"/" + fileNameOne + "\"}"; 49 | 50 | var fileNameTwo = "Part1.mp3"; 51 | var locationTwo = "{\"path\":\"/" + fileNameTwo + "\"}"; 52 | 53 | var client = new RestClient() 54 | { 55 | Authenticator = new JwtAuthenticator(Token) 56 | }; 57 | 58 | var audioDownload = new RestRequest() 59 | { 60 | Resource = BasePath + contextPath, 61 | Method = Method.Post 62 | }; 63 | 64 | audioDownload.AddHeader("Dropbox-API-Arg", locationTwo); 65 | 66 | var videoDownload = new RestRequest() 67 | { 68 | Resource = BasePath + contextPath, 69 | Method = Method.Post 70 | }; 71 | videoDownload.AddHeader("Dropbox-API-Arg", locationOne); 72 | 73 | var task1 = client.DownloadDataAsync(videoDownload); 74 | var task2 = client.DownloadDataAsync(audioDownload); 75 | 76 | Task.WaitAll(task1, task2); 77 | 78 | File.WriteAllBytes(fileNameOne, task1.Result); 79 | File.WriteAllBytes(fileNameTwo, task2.Result); 80 | 81 | File.Exists(fileNameOne).Should().BeTrue(); 82 | File.Exists(fileNameTwo).Should().BeTrue(); 83 | 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/POST_Request_with_De_serialization_of_XML_response_body/Assignment_POST_Request_with_De-serialization_XML_body.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using System; 5 | using WebServiceAutomation.Model.XmlModel; 6 | 7 | namespace RestSharpLatest.Assignment.POST_Request_with_De_serialization_of_XML_response_body 8 | { 9 | [TestClass] 10 | public class Assignment_POST_Request_with_De_serialization_XML_body 11 | { 12 | private Random random = new Random(); 13 | private string postUrl = "http://localhost:8081/laptop-bag/webapi/api/add"; 14 | 15 | [TestMethod] 16 | public void SendPostRequestWithXMLBody() 17 | { 18 | int id = random.Next(1000); 19 | 20 | // XML Request Body 21 | string xmlData = "" + 22 | "Alienware" + 23 | "" + 24 | "8th Generation Intel® Core™ i5 - 8300H" + 25 | "Windows 10 Home 64 - bit English" + 26 | "NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6" + 27 | "8GB, 2x4GB, DDR4, 2666MHz" + 28 | "" + 29 | " " + id + "" + 30 | "Alienware M17" + 31 | ""; 32 | 33 | 34 | // Create the Client 35 | RestClient client = new RestClient(); 36 | // Create the Request 37 | RestRequest request = new RestRequest() 38 | { 39 | Resource = postUrl, 40 | Method = Method.Post 41 | }; 42 | 43 | // Add the xml request body to the request 44 | request.AddStringBody(xmlData, DataFormat.Xml); 45 | 46 | // Add the request header to accept the response in XML 47 | request.AddHeader("Accept", "application/xml"); 48 | 49 | // Execute the POST request and de-serialize the XML response body to an object 50 | var response = client.ExecutePost(request); 51 | 52 | // Validate the status code. 53 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 54 | 55 | // Validate the BrandName property. 56 | response.Data.BrandName.Should().NotBeNull(); 57 | // Validate the LaptopName property. 58 | response.Data.LaptopName.Should().NotBeNull(); 59 | 60 | // Release the resource acquired by the client. 61 | client.Dispose(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/GET_Request_with_De_serialization_using_FrameworkAPI/Assignment_Get_Request_Framework.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharpLatest.APIHelper; 4 | using RestSharpLatest.APIHelper.APIRequest; 5 | using RestSharpLatest.APIHelper.Client; 6 | using RestSharpLatest.APIHelper.Command; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Diagnostics; 10 | using System.Linq; 11 | using System.Text; 12 | using System.Threading.Tasks; 13 | using WebServiceAutomation.Model.JsonModel; 14 | 15 | namespace RestSharpLatest.Assignment.GET_Request_with_De_serialization_using_FrameworkAPI 16 | { 17 | [TestClass] 18 | public class Assignment_Get_Request_Framework 19 | { 20 | private static IClient client; 21 | private static RestApiExecutor executor; 22 | private readonly string getUrl = "http://localhost:8081/laptop-bag/webapi/api/all"; 23 | 24 | //ClassInitialize - a method that contains code that must be used before any of the tests in the test class have run 25 | [ClassInitialize] 26 | public static void SetUp(TestContext testContext) 27 | { 28 | // Create the Default Client 29 | client = new DefaultClient(); 30 | // Create the Executor 31 | executor = new RestApiExecutor(); 32 | } 33 | 34 | // Assignment - GET Request with De-serialization using Framework API 35 | [TestMethod] 36 | public void GetRequest() 37 | { 38 | // Create the GET request. 39 | AbstractRequest request = new GetRequestBuilder().WithUrl(getUrl); 40 | 41 | // Create the Command for the GET request. 42 | ICommand getCommand = new RequestCommand(request, client); 43 | 44 | // Set the command for the RestApiExecutor. 45 | executor.SetCommand(getCommand); 46 | 47 | // Send the GET request and De-Serialize the response to an object. 48 | var response = executor.ExecuteRequest>(); 49 | 50 | // Validate the status code using Fluent API. 51 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 52 | 53 | // Extract a single object. 54 | var entry = response.GetResponseData().Find((item) => { return item.Id == 1; }); 55 | 56 | // Validate the BrandName property. 57 | entry.BrandName.Should().NotBeNull(); 58 | // Validate the LaptopName property. 59 | entry.LaptopName.Should().NotBeNull(); 60 | 61 | } 62 | 63 | //ClassCleanup - a method that contains code to be used after all the tests in the test class have run 64 | [ClassCleanup] 65 | public static void TearDown() 66 | { 67 | // Release the resource acquired by the client. 68 | client?.Dispose(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /RestSharpLatest/APIHelper/APIRequest/PostRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using RestSharp; 2 | using RestSharp.Serializers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace RestSharpLatest.APIHelper.APIRequest 10 | { 11 | public class PostRequestBuilder : AbstractRequest 12 | { 13 | private readonly RestRequest _restRequest; 14 | 15 | public PostRequestBuilder() 16 | { 17 | _restRequest = new RestRequest() 18 | { 19 | Method = Method.Post 20 | }; 21 | } 22 | 23 | public override RestRequest Build() 24 | { 25 | return _restRequest; 26 | } 27 | 28 | //URL 29 | 30 | public PostRequestBuilder WithUrl(string url) 31 | { 32 | WithUrl(url, _restRequest); 33 | return this; 34 | } 35 | 36 | // Headers 37 | public PostRequestBuilder WithHeaders(Dictionary headers) 38 | { 39 | WithHeaders(headers, _restRequest); 40 | return this; 41 | } 42 | 43 | // Body 44 | 45 | public PostRequestBuilder WithBody(T body, RequestBodyType bodyType, string contentType = ContentType.Json) where T : class 46 | { 47 | // String 48 | // Object 49 | 50 | switch (bodyType) 51 | { 52 | case RequestBodyType.STRING: 53 | _restRequest.AddStringBody(body.ToString(), contentType); 54 | break; 55 | case RequestBodyType.JSON: 56 | _restRequest.AddJsonBody(body); 57 | break; 58 | case RequestBodyType.XML: 59 | _restRequest.AddXmlBody(body); 60 | break; 61 | } 62 | return this; 63 | } 64 | 65 | //QueryParameter 66 | public PostRequestBuilder WithQueryParameters(Dictionary parameters) 67 | { 68 | WithQueryParameters(parameters, _restRequest); 69 | return this; 70 | } 71 | 72 | //File Upload 73 | public PostRequestBuilder WithFileUpload(string paramName, byte[] content, string fileName) 74 | { 75 | _restRequest.AddFile(paramName, content, fileName, "multipart/form-data"); 76 | return this; 77 | } 78 | 79 | protected override void WithQueryParameters(Dictionary parameters, RestRequest restRequest) 80 | { 81 | foreach (string key in parameters.Keys) 82 | { 83 | restRequest.AddQueryParameter(key, parameters[key]); 84 | } 85 | } 86 | 87 | } 88 | 89 | public enum RequestBodyType 90 | { 91 | STRING, // For the String body 92 | JSON, // Serialize the object in to JSON 93 | XML // Serialize the object in to XML 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /RestSharpLatest/GetRequest/TestGetRequestSecure.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharp.Authenticators; 5 | using RestSharpLatest.APIHelper; 6 | using RestSharpLatest.APIHelper.APIRequest; 7 | using RestSharpLatest.APIHelper.Client; 8 | using RestSharpLatest.APIHelper.Command; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace RestSharpLatest.GetRequest 16 | { 17 | [TestClass] 18 | public class TestGetRequestSecure 19 | { 20 | private readonly string SecureGetUrl = "http://localhost:8081/laptop-bag/webapi/secure/all"; 21 | 22 | private static IClient _client; 23 | private static IClient authClient; 24 | private static RestApiExecutor apiExecutor; 25 | 26 | [ClassInitialize] 27 | public static void Setup(TestContext testContext) 28 | { 29 | // Created the Tracer client 30 | _client = new TracerClient(); 31 | // Invok the decorator with tracer client impl 32 | authClient = new BasicAuthDecorator(_client); 33 | apiExecutor = new RestApiExecutor(); 34 | } 35 | 36 | [ClassCleanup] 37 | public static void TearDown() 38 | { 39 | _client?.Dispose(); 40 | } 41 | 42 | [TestMethod] 43 | public void TestGetRequestWithBasicAuth() 44 | { 45 | // Create the Client 46 | // Create the Request 47 | // Using the client send the request 48 | 49 | var restClient = new RestClient() 50 | { 51 | Authenticator = new HttpBasicAuthenticator("admin", "welcome") 52 | }; 53 | // restClient.Authenticator = new HttpBasicAuthenticator("admin", "welcome") 54 | var getRequest = new RestRequest() 55 | { 56 | Method = Method.Get, 57 | Resource = SecureGetUrl 58 | }; 59 | 60 | var response = restClient.ExecuteGet(getRequest); 61 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 62 | 63 | } 64 | 65 | [TestMethod] 66 | public void TestSecureGetUsingDecorator() 67 | { 68 | //1. Create the request using Get Request builder class 69 | var getRequest = new GetRequestBuilder().WithUrl(SecureGetUrl); 70 | //2. Create the request command 71 | var command = new RequestCommand(getRequest, authClient); 72 | //3. Set the command on the API executor 73 | apiExecutor.SetCommand(command); 74 | //4. Execute the request 75 | var response = apiExecutor.ExecuteRequest(); 76 | //5. Capture the response 77 | //6. Add the validation on the response status code. 78 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 79 | 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /RestSharpLatest/SchemaValidation/Schema/ValidateSchema.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using Newtonsoft.Json.Linq; 3 | using Newtonsoft.Json.Schema; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace RestSharpLatest.SchemaValidation.Schema 12 | { 13 | [TestClass] 14 | public class ValidateSchema 15 | { 16 | private Random random = new Random(); 17 | 18 | [TestMethod] 19 | public void TestRequestBodyValidation() 20 | { 21 | int id = random.Next(1000); 22 | 23 | string jsonData = "{" + 24 | "\"BrandName\": \"Alienware\"," + 25 | "\"Features\": {" + 26 | "\"Feature\": [" + 27 | "\"8th Generation Intel® Core™ i5-8300H\"," + 28 | "\"Windows 10 Home 64-bit English\"," + 29 | "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," + 30 | "\"8GB, 2x4GB, DDR4, 2666MHz\"" + 31 | "]" + 32 | "}," + 33 | "\"Id\": " + id + "," + 34 | "\"LaptopName\": \"Alienware M17\"" + 35 | "}"; 36 | 37 | string jsonDataInvalid = "{" + 38 | "\"BrandName\": \"Alienware\"," + 39 | "\"Features\": {" + 40 | "\"Feature\": [" + 41 | "\"8th Generation Intel® Core™ i5-8300H\"," + 42 | "\"Windows 10 Home 64-bit English\"," + 43 | "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," + 44 | "\"8GB, 2x4GB, DDR4, 2666MHz\"" + 45 | "]" + 46 | "}," + 47 | "\"Id\": " + id + "" + 48 | "}"; 49 | 50 | /* 51 | * Step 1 - Parse the given JSON schema 52 | * Step 2 - Parse the given JSON object 53 | * Step 3 - Call the isVlaid for the validation 54 | */ 55 | 56 | string jsonSchema = File.ReadAllText(@"SchemaValidation\Schema\RequestBodySchema.txt"); 57 | JSchema jSchema = JSchema.Parse(jsonSchema); 58 | 59 | //JToken jToken = JToken.Parse(jsonData); 60 | JToken jToken = JToken.Parse(jsonDataInvalid); 61 | 62 | bool valid = jToken.IsValid(jSchema); 63 | Console.WriteLine(valid); 64 | 65 | jToken.IsValid(jSchema, out IList errors); 66 | 67 | foreach(ValidationError err in errors) 68 | { 69 | Console.WriteLine(err.Message); 70 | } 71 | 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /HttpInterceptor/TestInterceptor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net.Http; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace HttpInterceptor 10 | { 11 | [TestClass] 12 | public class TestInterceptor 13 | { 14 | private readonly string GetUrl = "http://localhost:9191/secure/webapi/all"; 15 | private readonly List interceptors = new List(); 16 | 17 | [TestMethod] 18 | public void TestMethod1() 19 | { 20 | 21 | var interCeptor = new CustomInterceptor(KnownHeaders.Authorization, "Basic YWRtaW46d2VsY29tZQ=="); 22 | interceptors.Add(interCeptor); 23 | 24 | // 1. Create the instance of RestClientOption 25 | // 2. Add the custom interceptor to the RestClientOption 26 | var option = new RestClientOptions() 27 | { 28 | Interceptors = interceptors 29 | }; 30 | 31 | 32 | // 3. Create the Request 33 | 34 | var request = new RestRequest(GetUrl, Method.Get); 35 | 36 | // 4. Create the client using the RestCleintOption 37 | 38 | var client = new RestClient(option); 39 | 40 | // 5. Send the request 41 | var response = client.ExecuteGet(request); 42 | // 6. Print the response at the console. 43 | Console.WriteLine(response.Content); 44 | 45 | } 46 | } 47 | 48 | // 1. Intercept the request and add the auth header 49 | // 2. Intercept the response and encrypt the response content 50 | class CustomInterceptor : RestSharp.Interceptors.Interceptor 51 | { 52 | private readonly string headerName; 53 | private readonly string headerValue; 54 | 55 | public CustomInterceptor(string name, string value) 56 | { 57 | headerName = name; 58 | headerValue = value; 59 | } 60 | 61 | public override ValueTask BeforeRequest(RestRequest request, CancellationToken cancellationToken) 62 | { 63 | request.AddHeader(headerName, headerValue); 64 | return base.BeforeRequest(request, cancellationToken); 65 | } 66 | 67 | public override ValueTask AfterHttpRequest(HttpResponseMessage responseMessage, CancellationToken cancellationToken) 68 | { 69 | // 1. Get the response content 70 | 71 | var content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); 72 | 73 | // 2. Convert the response into byte array 74 | 75 | var contentInByteArray = System.Text.Encoding.UTF8.GetBytes(content); 76 | // 3. Entry the byte array 77 | 78 | var responseContent = Convert.ToBase64String(contentInByteArray); 79 | // 4. Add the new content to the response object 80 | responseMessage.Content = new StringContent(responseContent); 81 | 82 | return base.AfterHttpRequest(responseMessage, cancellationToken); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/POST_Request_with_Decorator/Assignment_POST_Request_with_Decorator.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharpLatest.APIHelper; 4 | using RestSharpLatest.APIHelper.APIRequest; 5 | using RestSharpLatest.APIHelper.Client; 6 | using RestSharpLatest.APIHelper.Command; 7 | using RestSharpLatest.APIModel.JsonApiModel; 8 | using System; 9 | using System.Collections.Generic; 10 | 11 | namespace RestSharpLatest.Assignment.POST_Request_with_Decorator 12 | { 13 | [TestClass] 14 | public class Assignment_POST_Request_with_Decorator 15 | { 16 | private readonly string SecurePostUrl = "http://localhost:8081/laptop-bag/webapi/secure/add"; 17 | 18 | private static IClient authClient; 19 | private static RestApiExecutor apiExecutor; 20 | private readonly Random random = new Random(); 21 | 22 | //ClassInitialize - a method that contains code that must be used before any of the tests in the test class have run 23 | [ClassInitialize] 24 | public static void Setup(TestContext testContext) 25 | { 26 | // Invoke the decorator with the tracer client impl 27 | authClient = new BasicAuthDecorator(new TracerClient()); 28 | // Create the Executor 29 | apiExecutor = new RestApiExecutor(); 30 | } 31 | 32 | //ClassCleanup - a method that contains code to be used after all the tests in the test class have run 33 | [ClassCleanup] 34 | public static void TearDown() 35 | { 36 | // Release the resource acquired by the client. 37 | authClient?.Dispose(); 38 | } 39 | 40 | 41 | // Assignment - POST Request with BasicAuthDecorator using Framework API 42 | [TestMethod] 43 | public void TestSecurePostWithDecorator() 44 | { 45 | int id = random.Next(1000); 46 | 47 | // Create the request body. 48 | var payload = new JsonModelBuilder().WithId(id).WithBrandName("Alienware").WithLaptopName("Alienware M17").WithFeatures(new List() { "8th Generation Intel® Core™ i5-8300H", "Windows 10 Home 64-bit English" }).Build(); 49 | 50 | // Create the Post Request 51 | var request = new PostRequestBuilder().WithUrl(SecurePostUrl).WithBody(payload, RequestBodyType.JSON); 52 | 53 | // Create the Command for the post request. 54 | var command = new RequestCommand(request, authClient); 55 | 56 | // Set the command for the RestApiExecutor. 57 | apiExecutor.SetCommand(command); 58 | 59 | // Send the POST request and De-Serialize the response to an object. 60 | var response = apiExecutor.ExecuteRequest(); 61 | 62 | // Validate the status code using Fluent API. 63 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 64 | 65 | // Validate the BrandName property. 66 | response.GetResponseData().BrandName.Should().NotBeNull(); 67 | // Validate the LaptopName property. 68 | response.GetResponseData().LaptopName.Should().NotBeNull(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /WebServiceAutomation.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29020.237 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebServiceAutomation", "WebServiceAutomation\WebServiceAutomation.csproj", "{50E9C02D-5854-4C75-9FD8-38F370861C24}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsTestProject", "MsTestProject\MsTestProject.csproj", "{7F451F30-0CED-4CFF-BCE9-0D2CE727F38E}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharpAutomation", "RestSharpAutomation\RestSharpAutomation.csproj", "{B492C2AD-DB6A-471F-AF94-34397FC2427F}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharpLatest", "RestSharpLatest\RestSharpLatest.csproj", "{D7727898-BBF8-41B5-BD92-160F8E0FC593}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpInterceptor", "HttpInterceptor\HttpInterceptor.csproj", "{43325D19-284B-474E-AE11-ABFAD62B863A}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {50E9C02D-5854-4C75-9FD8-38F370861C24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {50E9C02D-5854-4C75-9FD8-38F370861C24}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {50E9C02D-5854-4C75-9FD8-38F370861C24}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {50E9C02D-5854-4C75-9FD8-38F370861C24}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {7F451F30-0CED-4CFF-BCE9-0D2CE727F38E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {7F451F30-0CED-4CFF-BCE9-0D2CE727F38E}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {7F451F30-0CED-4CFF-BCE9-0D2CE727F38E}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {7F451F30-0CED-4CFF-BCE9-0D2CE727F38E}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {B492C2AD-DB6A-471F-AF94-34397FC2427F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {B492C2AD-DB6A-471F-AF94-34397FC2427F}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {B492C2AD-DB6A-471F-AF94-34397FC2427F}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {B492C2AD-DB6A-471F-AF94-34397FC2427F}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {D7727898-BBF8-41B5-BD92-160F8E0FC593}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {D7727898-BBF8-41B5-BD92-160F8E0FC593}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {D7727898-BBF8-41B5-BD92-160F8E0FC593}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {D7727898-BBF8-41B5-BD92-160F8E0FC593}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {43325D19-284B-474E-AE11-ABFAD62B863A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {43325D19-284B-474E-AE11-ABFAD62B863A}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {43325D19-284B-474E-AE11-ABFAD62B863A}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {43325D19-284B-474E-AE11-ABFAD62B863A}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {59623560-985F-4977-9ACA-4F771C7FD4FC} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /WebServiceAutomation/MyTaskClass.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WebServiceAutomation.Helper.Request; 8 | using WebServiceAutomation.Helper.Response; 9 | using WebServiceAutomation.Model; 10 | using WebServiceAutomation.Model.XmlModel; 11 | 12 | namespace WebServiceAutomation 13 | { 14 | //[TestClass] 15 | public class MyTaskClass 16 | { 17 | private string postUrl = "http://localhost:8080/laptop-bag/webapi/api/add"; 18 | private string xmlMediaType = "application/xml"; 19 | private Dictionary headers = new Dictionary() 20 | { 21 | { "Accept","application/xml"} 22 | }; 23 | 24 | [TestMethod] 25 | public void TestTask() 26 | { 27 | Task t1 = Task.Factory.StartNew(() => 28 | { 29 | return HttpClientHelper.PerformGetRequest("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all", headers); 30 | }); 31 | 32 | var task = Task.Factory.StartNew(() => 33 | { 34 | Random random = new Random(); 35 | int id = random.Next(1000); 36 | Console.WriteLine("Start " + id); 37 | return AddRecord(id); 38 | }, TaskCreationOptions.LongRunning).ContinueWith((restResponse) => 39 | { 40 | string id = restResponse.Result.Id; 41 | RestResponse rs = HttpClientHelper.PerformGetRequest("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/find/" + id, headers); 42 | Assert.AreEqual(200, rs.StatusCode); 43 | Console.WriteLine("Done"); 44 | }, TaskContinuationOptions.OnlyOnRanToCompletion); 45 | 46 | task.Wait(50000); 47 | 48 | Console.WriteLine(t1.Result.StatusCode); 49 | 50 | } 51 | 52 | public Laptop AddRecord(int id) 53 | { 54 | string xmlData = "" + 55 | "Alienware" + 56 | "" + 57 | "8th Generation Intel® Core™ i5 - 8300H" + 58 | "Windows 10 Home 64 - bit English" + 59 | "NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6" + 60 | "8GB, 2x4GB, DDR4, 2666MHz" + 61 | "" + 62 | " " + id + "" + 63 | "Alienware M17" + 64 | ""; 65 | RestResponse restResponse = HttpClientHelper.PerformPostRequest(postUrl, xmlData, xmlMediaType, headers); 66 | Assert.AreEqual(200, restResponse.StatusCode); 67 | Laptop xmlDatat = ResponseDataHelper.DeserializeXmlResponse(restResponse.ResponseContent); 68 | return xmlDatat; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /RestSharpAutomation/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /RestSharpAutomation/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using RestSharp; 5 | 6 | namespace RestSharpAutomation 7 | { 8 | [TestClass] 9 | public class UnitTest1 10 | { 11 | [TestMethod] 12 | public void TestMethod1() 13 | { 14 | 15 | /** 16 | 1. Create the Client 17 | 2. Create the Request 18 | 3. Send the request using the client 19 | 4. Capture the respose 20 | */ 21 | 22 | IRestClient restClient = new RestClient(); 23 | IRestRequest restRequest = new RestRequest(); 24 | } 25 | 26 | [TestMethod] 27 | public void TestYouTubeDataApi() 28 | { 29 | 30 | /** 31 | 1. Create the Client 32 | 2. Create the Request 33 | 3. Send the request using the client 34 | 4. Capture the respose 35 | */ 36 | IRestClient client = new RestClient(); 37 | IRestRequest request = new RestRequest(); 38 | request.Resource = "https://accounts.google.com/o/oauth2/v2/auth"; 39 | request.AddParameter("scope", "https://www.googleapis.com/auth/youtube", ParameterType.QueryString); 40 | request.AddParameter("access_type", "online",ParameterType.QueryString); 41 | request.AddParameter("include_granted_scopes","true", ParameterType.QueryString); 42 | request.AddParameter("state", "state_parameter_passthrough_value", ParameterType.QueryString); 43 | request.AddParameter("redirect_uri", "https://localhost.com", ParameterType.QueryString); 44 | request.AddParameter("response_type", "code", ParameterType.QueryString); 45 | request.AddParameter("client_id", "654769406751-6ekohb9nkv7lomiegoan80756pr8iq74.apps.googleusercontent.com", ParameterType.QueryString); 46 | IRestResponse response = client.Get(request); 47 | Console.WriteLine(response.Content); 48 | 49 | } 50 | 51 | [TestMethod] 52 | public void TestDropBox() 53 | { 54 | string body = "{\"path\": \"/Homework\",\"autorename\": true}"; 55 | string uploadHeader = "{\"path\": \"/Homework/upload.mp4\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}"; 56 | string downloadHeader = "{\"path\": \"/Homework/Document.docx\"}"; 57 | IRestClient client = new RestClient(); 58 | IRestRequest request = new RestRequest() 59 | { 60 | Resource = "https://content.dropboxapi.com/2/files/download", 61 | Method = Method.POST 62 | 63 | }; 64 | request.AddHeader("Authorization", "Bearer 6nPT8TAQ09kAAAAAAAAAk-q6hpQpQKBVK5qLAuXxUbAtPGJ4KJY1IYiaZ1-1_bVD"); 65 | //request.AddHeader("Content-Type", "application/octet-stream"); 66 | request.AddHeader("Dropbox-API-Arg", downloadHeader); 67 | //request.AddFile("upload.mp4", "C:\\Users\\rathr1\\Downloads\\upload.mp4", "video/mp4"); 68 | //request.RequestFormat = DataFormat.Json; 69 | //request.AddBody(body); 70 | //IRestResponse response = client.Post(request); 71 | var response = client.DownloadData(request); 72 | //Console.WriteLine(response.Content); 73 | Console.WriteLine(response.Length); 74 | File.WriteAllBytes("down.docx", response); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /RestSharpAutomation/JiraAPI/TestJiraEndToEndFlow.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using RestSharp; 3 | using RestSharpAutomation.JiraAPI.Request; 4 | using RestSharpAutomation.JiraAPI.Response; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using NHamcrest.Core; 11 | 12 | namespace RestSharpAutomation.JiraAPI 13 | { 14 | [TestClass] 15 | public class TestJiraEndToEndFlow 16 | { 17 | private const string LoginEndPoint = "/rest/auth/1/session"; // POST 18 | private const string LogoutEndPoint = "/rest/auth/1/session"; // DELETE 19 | private const string CreateProjectEndPoint = "/rest/api/2/project"; // POST 20 | private static IRestClient client; 21 | private static IRestResponse LoginResponse; 22 | 23 | /** 24 | * 1 Login into JIRS --> Class Initialize 25 | * 2. Create the Project 26 | * 3. Logout from JIRA --> Class Cleanup 27 | * 28 | * **/ 29 | 30 | [ClassInitialize] 31 | public static void Login(TestContext context) 32 | { 33 | client = new RestClient() 34 | { 35 | BaseUrl = new Uri("http://localhost:9191") 36 | }; 37 | IRestRequest request = new RestRequest() 38 | { 39 | Resource = LoginEndPoint 40 | }; 41 | JiraLogin jiraLogin = new JiraLogin() 42 | { 43 | username = "rahul", 44 | password = "admin@1234#" 45 | }; 46 | request.RequestFormat = DataFormat.Json; 47 | request.AddJsonBody(jiraLogin); 48 | request.AddHeader("Content-Type", "application/json"); 49 | LoginResponse = client.Post(request); 50 | Assert.AreEqual(200, (int)LoginResponse.StatusCode); 51 | } 52 | 53 | [ClassCleanup] 54 | public static void Logout() 55 | { 56 | IRestRequest request = new RestRequest() 57 | { 58 | Resource = LogoutEndPoint 59 | }; 60 | request.AddCookie(LoginResponse.Data.session.name, LoginResponse.Data.session.value); 61 | var response = client.Delete(request); 62 | Assert.AreEqual(204, (int)response.StatusCode); 63 | } 64 | 65 | [TestMethod] 66 | public void CreateProject() 67 | { 68 | CreateProjectPayload createProjectPayload = new CreateProjectPayload(); 69 | IRestRequest restRequest = new RestRequest() 70 | { 71 | Resource = CreateProjectEndPoint 72 | }; 73 | restRequest.RequestFormat = DataFormat.Json; 74 | restRequest.AddBody(createProjectPayload); 75 | restRequest.AddHeader("Content-Type", "application/json"); 76 | restRequest.AddCookie(LoginResponse.Data.session.name, LoginResponse.Data.session.value); 77 | var response = client.Post(restRequest); 78 | Assert.AreEqual(201, (int)response.StatusCode); 79 | 80 | 81 | } 82 | 83 | [TestMethod] 84 | public void GetCurrentUser() 85 | { 86 | IRestRequest restRequest = new RestRequest() 87 | { 88 | Resource = "/rest/auth/1/session" 89 | }; 90 | restRequest.AddCookie(LoginResponse.Data.session.name, LoginResponse.Data.session.value); 91 | var response = client.Get(restRequest); 92 | Assert.AreEqual(200, (int)response.StatusCode); 93 | Assert.IsNotNull(response.Data); 94 | Console.WriteLine(response.Content); 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /RestSharpLatest/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /RestSharpLatest/DropBox/ListFilesAndFolder.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp; 4 | using RestSharp.Authenticators; 5 | using RestSharpLatest.APIHelper; 6 | using RestSharpLatest.APIHelper.APIRequest; 7 | using RestSharpLatest.APIHelper.Client; 8 | using RestSharpLatest.APIHelper.Command; 9 | using RestSharpLatest.DropBox.Model; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Linq; 13 | using System.Text; 14 | using System.Threading.Tasks; 15 | 16 | namespace RestSharpLatest.DropBox 17 | { 18 | [TestClass] 19 | public class ListFilesAndFolder 20 | { 21 | private readonly string BaseUrl = "https://api.dropboxapi.com/2"; 22 | private static readonly string Token = ""; 23 | 24 | private static IClient client; 25 | private static IClient authClient; 26 | private static RestApiExecutor apiExecutor; 27 | 28 | [ClassInitialize] 29 | public static void SetUp(TestContext testContext) 30 | { 31 | client = new TracerClient(); 32 | authClient = new AuthenticationDecorato(client, new JwtAuthenticator(Token)); 33 | //authClient = new AuthenticationDecorato(client, new HttpBasicAuthenticator("","")); // For Basic Auth 34 | apiExecutor = new RestApiExecutor(); 35 | 36 | } 37 | 38 | [ClassCleanup] 39 | public static void TearDown() 40 | { 41 | authClient?.Dispose(); 42 | } 43 | 44 | [TestMethod] 45 | public void GetAllFilesAndFolder() 46 | { 47 | var contextPath = "/files/list_folder"; 48 | 49 | var requestBody = "{\"include_deleted\":false,\"include_has_explicit_shared_members\":false,\"include_media_info\":false,\"include_mounted_folders\":true,\"include_non_downloadable_files\":true,\"path\":\"\",\"recursive\":false}"; 50 | 51 | var client = new RestClient() 52 | { 53 | Authenticator = new JwtAuthenticator(Token) 54 | }; 55 | 56 | var request = new RestRequest() 57 | { 58 | Resource = BaseUrl + contextPath, 59 | Method = Method.Post 60 | }; 61 | request.AddStringBody(requestBody, DataFormat.Json); 62 | var response = client.ExecutePost(request); 63 | response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); 64 | client.Dispose(); 65 | } 66 | 67 | [TestMethod] 68 | public void GetAllFilesAndFolder_with_Framework() { 69 | // request body 70 | var contextPath = "/files/list_folder"; 71 | 72 | var requestBody = "{\"include_deleted\":false,\"include_has_explicit_shared_members\":false,\"include_media_info\":false,\"include_mounted_folders\":true,\"include_non_downloadable_files\":true,\"path\":\"\",\"recursive\":false}"; 73 | // Post request 74 | var postrequest = new PostRequestBuilder().WithUrl(BaseUrl + contextPath).WithBody(requestBody, RequestBodyType.STRING); 75 | // Request command 76 | var command = new RequestCommand(postrequest, authClient); 77 | // set the command on api executor 78 | apiExecutor.SetCommand(command); 79 | // execute the request 80 | var response = apiExecutor.ExecuteRequest(); 81 | // validate the response status 82 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 83 | 84 | } 85 | 86 | [TestMethod] 87 | public void CreateFolder_with_framework() 88 | { 89 | // request body 90 | var contextPath = "/files/create_folder_v2"; 91 | 92 | var requestBody = "{\"autorename\":true,\"path\":\"/TestFolder\"}"; 93 | // Post request 94 | var postrequest = new PostRequestBuilder().WithUrl(BaseUrl + contextPath).WithBody(requestBody, RequestBodyType.STRING); 95 | // Request command 96 | var command = new RequestCommand(postrequest, authClient); 97 | // set the command on api executor 98 | apiExecutor.SetCommand(command); 99 | // execute the request 100 | var response = apiExecutor.ExecuteRequest(); 101 | // validate the response status 102 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /WebServiceAutomation/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using WebServiceAutomation.Helper.Request; 8 | using WebServiceAutomation.Helper.Response; 9 | using WebServiceAutomation.Model; 10 | using WebServiceAutomation.Model.XmlModel; 11 | 12 | namespace WebServiceAutomation 13 | { 14 | [TestClass] 15 | public class UnitTest1 16 | { 17 | 18 | [TestMethod] 19 | public void TestMethod1() 20 | { 21 | // Step 1. To create Http Client 22 | HttpClient httpClient = new HttpClient(); 23 | string getUrl = "https://laptopbag.herokuapp.com/laptop-bag/webapi/api/all"; 24 | httpClient.Dispose(); // Close the connection and release the resource 25 | 26 | } 27 | 28 | //[TestMethod] 29 | public void TestDelayAsync() 30 | { 31 | executeAsync().GetAwaiter().GetResult(); 32 | } 33 | 34 | private async Task executeAsync() 35 | { 36 | Console.WriteLine("Started.."); 37 | string x = await GetDealy().ConfigureAwait(false); 38 | Console.WriteLine("Ended.."); 39 | string y = await GetDealy1().ConfigureAwait(false); 40 | } 41 | 42 | private async Task GetDealy() 43 | { 44 | 45 | HttpClient httpClient = new HttpClient(); 46 | HttpResponseMessage response = await httpClient.GetAsync("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all"); 47 | response.EnsureSuccessStatusCode(); 48 | string content = await response.Content.ReadAsStringAsync(); 49 | return content; 50 | 51 | } 52 | 53 | private async Task executeAsync1() 54 | { 55 | Console.WriteLine("Started.."); 56 | string x = await GetDealy1().ConfigureAwait(false); 57 | Console.WriteLine("Ended.."); 58 | } 59 | 60 | private async Task GetDealy1() 61 | { 62 | 63 | HttpClient httpClient = new HttpClient(); 64 | HttpResponseMessage response = await httpClient.GetAsync("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all"); 65 | response.EnsureSuccessStatusCode(); 66 | string content = await response.Content.ReadAsStringAsync(); 67 | return content; 68 | 69 | } 70 | 71 | 72 | 73 | //[TestMethod] 74 | public void TestAsyncAwait() 75 | { 76 | Task t1 = Method1(); 77 | Task t2 = Method2(); 78 | t1.Wait(); 79 | t2.Wait(); 80 | } 81 | 82 | public async Task Method1() 83 | { 84 | await Task.Run(() => 85 | { 86 | HttpClientHelper.PerformGetRequest("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all", null); 87 | }); 88 | } 89 | 90 | 91 | public async Task Method2() 92 | { 93 | await Task.Run(() => 94 | { 95 | HttpClientHelper.PerformGetRequest("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all", null); 96 | }); 97 | } 98 | 99 | 100 | //[TestMethod] 101 | public void TestCreatTask() 102 | { 103 | 104 | 105 | Task t1 = new Task(GetAction()); 106 | t1.Start(); 107 | 108 | Task t2 = new Task(GetAction()); 109 | t2.Start(); 110 | 111 | 112 | Task t3 = new Task(GetAction()); 113 | t3.Start(); 114 | 115 | Task t4 = new Task(GetAction()); 116 | t4.Start(); 117 | 118 | t1.Wait(); 119 | t2.Wait(); 120 | t3.Wait(); 121 | t4.Wait(); 122 | } 123 | 124 | private Action GetAction() 125 | { 126 | Dictionary httpHeader = new Dictionary 127 | { 128 | { "Accept", "application/json" } 129 | }; 130 | return new Action(() => 131 | { 132 | RestResponse restResponse = HttpClientHelper.PerformGetRequest("https://laptopbag.herokuapp.com/laptop-bag/webapi/delay/all", httpHeader); 133 | Assert.AreEqual(200, restResponse.StatusCode); 134 | }); 135 | } 136 | 137 | 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /WebServiceAutomation/Helper/Request/HttpClientHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WebServiceAutomation.Model; 8 | 9 | namespace WebServiceAutomation.Helper.Request 10 | { 11 | public class HttpClientHelper 12 | { 13 | private static HttpClient httpClient; 14 | private static HttpRequestMessage httpRequestMessage; 15 | private static RestResponse restResponse; 16 | 17 | private static HttpClient AddHeadersAndCreateHttpClient(Dictionary httpHeader) 18 | { 19 | HttpClient httpClient = new HttpClient(); 20 | 21 | if(null != httpHeader) 22 | { 23 | foreach (string key in httpHeader.Keys) 24 | { 25 | httpClient.DefaultRequestHeaders.Add(key, httpHeader[key]); 26 | 27 | } 28 | } 29 | return httpClient; 30 | 31 | } 32 | 33 | private static HttpRequestMessage CreateHttpRequestMessage(string requestUrl,HttpMethod httpMethod,HttpContent httpContent) 34 | { 35 | HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, requestUrl); 36 | if(!((httpMethod == HttpMethod.Get) || (httpMethod == HttpMethod.Delete))) 37 | httpRequestMessage.Content = httpContent; 38 | return httpRequestMessage; 39 | } 40 | 41 | private static RestResponse SendRequest(string requestUrl, HttpMethod httpMethod, HttpContent httpContent, Dictionary httpHeader) 42 | { 43 | httpClient = AddHeadersAndCreateHttpClient(httpHeader); 44 | httpRequestMessage = CreateHttpRequestMessage(requestUrl, httpMethod, httpContent); 45 | 46 | try 47 | { 48 | Task httpResponseMessage = httpClient.SendAsync(httpRequestMessage); 49 | restResponse = new RestResponse((int)httpResponseMessage.Result.StatusCode, httpResponseMessage.Result.Content.ReadAsStringAsync().Result); 50 | }catch(Exception err) 51 | { 52 | restResponse = new RestResponse(500, err.Message + "\n" + err.InnerException); 53 | Console.WriteLine(err.StackTrace); 54 | Console.WriteLine(err.InnerException); 55 | } 56 | finally 57 | { 58 | httpRequestMessage?.Dispose(); 59 | httpClient?.Dispose(); 60 | } 61 | 62 | return restResponse; 63 | } 64 | 65 | public static RestResponse PerformGetRequest(string requestUrl, Dictionary httpHeader) 66 | { 67 | return SendRequest(requestUrl, HttpMethod.Get, null, httpHeader); 68 | } 69 | 70 | public static RestResponse PerformPostRequest(string requestUrl,HttpContent httpContent,Dictionary httpHeaders) 71 | { 72 | return SendRequest(requestUrl, HttpMethod.Post, httpContent, httpHeaders); 73 | } 74 | 75 | public static RestResponse PerformPostRequest(string requestUrl, string data, string mediaType,Dictionary httpHeaders) 76 | { 77 | HttpContent httpContent = new StringContent(data, Encoding.UTF8, mediaType); 78 | return PerformPostRequest(requestUrl, httpContent, httpHeaders); 79 | } 80 | 81 | public static RestResponse PerformPutRequest(string requestUrl,string content,string mediaType,Dictionary headers) 82 | { 83 | HttpContent httpContent = new StringContent(content, Encoding.UTF8, mediaType); 84 | return SendRequest(requestUrl, HttpMethod.Put, httpContent, headers); 85 | } 86 | 87 | public static RestResponse PerformPutRequest(string requestUrl, HttpContent httpContent, Dictionary headers) 88 | { 89 | return SendRequest(requestUrl, HttpMethod.Put, httpContent, headers); 90 | } 91 | 92 | public static RestResponse PerformDeleteRequest(string requestUrl) 93 | { 94 | return SendRequest(requestUrl, HttpMethod.Delete, null, null); 95 | } 96 | 97 | //overloaded version 98 | public static RestResponse PerformDeleteRequest(string requestUrl, Dictionary headers) 99 | { 100 | return SendRequest(requestUrl, HttpMethod.Delete, null, headers); 101 | } 102 | 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /RestSharpLatest/Assignment/File_Download_using_Framework/Assignment_POST_File_Download_Parallel.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using RestSharp.Authenticators; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace RestSharpLatest.Assignment.File_Download_using_Framework 16 | { 17 | [TestClass] 18 | public class Assignment_POST_File_Download_Parallel 19 | { 20 | private static RestApiExecutor restApiExecutor; 21 | private static IClient client; 22 | private static IClient authClient; 23 | private static readonly string Token = ""; 24 | private readonly string BasePath = "https://content.dropboxapi.com/2"; 25 | 26 | //ClassInitialize - a method that contains code that must be used before any of the tests in the test class have run 27 | [ClassInitialize] 28 | public static void Setup(TestContext testContext) 29 | { 30 | // Create the Tracer Client 31 | client = new TracerClient(); 32 | // Invoke the decorator with the tracer client impl to associate the token information. 33 | authClient = new AuthenticationDecorato(client, new JwtAuthenticator(Token)); 34 | // Create the Executor 35 | restApiExecutor = new RestApiExecutor(); 36 | 37 | } 38 | 39 | //ClassCleanup - a method that contains code to be used after all the tests in the test class have run 40 | [ClassCleanup] 41 | public static void TearDown() 42 | { 43 | // Release the resource acquired by the client. 44 | authClient?.Dispose(); 45 | } 46 | 47 | // Assignment - Parallel Download of Multiple Files using Framework API 48 | [TestMethod] 49 | public void Download_File_Parallel_UsingFramework() 50 | { 51 | var contextPath = "/files/download"; 52 | 53 | // Meta data for the first file 54 | var fileNameOne = "Video.mp4"; 55 | var locationOne = "{\"path\":\"/" + fileNameOne + "\"}"; 56 | 57 | // Meta data for the second file 58 | var fileNameTwo = "Part1.mp3"; 59 | var locationTwo = "{\"path\":\"/" + fileNameTwo + "\"}"; 60 | 61 | // Create the Post Request for first file 62 | var postRequestforVideoFile = new PostRequestBuilder().WithUrl(BasePath + contextPath).WithHeaders(new Dictionary() { { "Dropbox-API-Arg", locationOne } }); 63 | 64 | // Create the Post Request for second file 65 | var postRequestforAudioFile = new PostRequestBuilder().WithUrl(BasePath + contextPath).WithHeaders(new Dictionary() { { "Dropbox-API-Arg", locationTwo } }); 66 | 67 | // Create the DownloadRequestCommand for the first post request. 68 | var command = new DownloadRequestCommand(postRequestforVideoFile, authClient); 69 | 70 | // Set the command for the RestApiExecutor. 71 | restApiExecutor.SetCommand(command); 72 | 73 | // Call DownloadDataAsync method to download first file. 74 | var dataOne = restApiExecutor.DownloadDataAsync(); 75 | 76 | // Create the DownloadRequestCommand for the second post request. 77 | command = new DownloadRequestCommand(postRequestforAudioFile, authClient); 78 | 79 | // Set the command for the RestApiExecutor. 80 | restApiExecutor.SetCommand(command); 81 | 82 | // Call DownloadDataAsync method to download second file. 83 | var dataTwo = restApiExecutor.DownloadDataAsync(); 84 | 85 | // Wait for download task 86 | Task.WaitAll(dataOne, dataTwo); 87 | 88 | // Save the first file on the local file system 89 | File.WriteAllBytes("New_" + fileNameOne, dataOne.Result); 90 | 91 | // Verify that the files are downloaded successfully. 92 | File.Exists("New_" + fileNameOne).Should().BeTrue(); 93 | 94 | // Save the second file on the local file system 95 | File.WriteAllBytes("New_" + fileNameTwo, dataTwo.Result); 96 | 97 | // Verify that the files are downloaded successfully. 98 | File.Exists("New_" + fileNameTwo).Should().BeTrue(); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /RestSharpLatest/PostRequest/TestMockAbleIo.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Newtonsoft.Json.Linq; 4 | using RestSharpLatest.APIHelper; 5 | using RestSharpLatest.APIHelper.APIRequest; 6 | using RestSharpLatest.APIHelper.Client; 7 | using RestSharpLatest.APIHelper.Command; 8 | using System.Collections.Generic; 9 | using System.Diagnostics; 10 | using System.Text.Json; 11 | 12 | 13 | namespace RestSharpLatest.PostRequest 14 | { 15 | [TestClass] 16 | public class TestMockAbleIo 17 | { 18 | private readonly string PostUrl = "http://demo8650956.mockable.io"; 19 | private static IClient _client; 20 | private static RestApiExecutor apiExecutor; 21 | 22 | [ClassInitialize] 23 | public static void SetUp(TestContext testContext) 24 | { 25 | _client = new TracerClient(); 26 | apiExecutor = new RestApiExecutor(); 27 | } 28 | 29 | [TestMethod] 30 | public void ParseAndValidateTheJson() 31 | { 32 | // Create the request 33 | var postRequest = new PostRequestBuilder().WithUrl(PostUrl); 34 | // Create the command 35 | var command = new RequestCommand(postRequest, _client); 36 | // Set the command 37 | apiExecutor.SetCommand(command); 38 | // Execute the request 39 | var response = apiExecutor.ExecuteRequest(); 40 | // Capture the response 41 | 42 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 43 | var responseContent = response.GetResponseData(); 44 | Debug.WriteLine(responseContent); 45 | 46 | 47 | // Parse the Given JSON document 48 | JObject jsonToValidate = JObject.Parse(responseContent); 49 | // Use the json path to query the json document 50 | // type caste the result of the query if needed 51 | var loggedOut = (bool)jsonToValidate.SelectToken("$.responseContext.mainAppWebResponseContext.loggedOut"); 52 | 53 | loggedOut.Should().BeTrue(); 54 | 55 | var headerJsonObject = jsonToValidate.SelectToken("$.header"); 56 | Header headers = JsonSerializer.Deserialize
(headerJsonObject.ToString()); 57 | headers.feedTabbedHeaderRenderer.Should().NotBeNull(); 58 | } 59 | 60 | [TestMethod] 61 | public void ParseAndValidateTheJson_Timing() 62 | { 63 | Stopwatch stopwatch = new Stopwatch(); 64 | 65 | // Create the request 66 | var postRequest = new PostRequestBuilder().WithUrl(PostUrl); 67 | // Create the command 68 | var command = new RequestCommand(postRequest, _client); 69 | // Set the command 70 | apiExecutor.SetCommand(command); 71 | // Execute the request 72 | 73 | stopwatch.Start(); 74 | var response = apiExecutor.ExecuteRequest(); 75 | // Capture the response 76 | stopwatch.Stop(); 77 | 78 | Debug.WriteLine($"Execute Request took {stopwatch.Elapsed.Milliseconds}"); 79 | 80 | response.GetHttpStatusCode().Should().Be(System.Net.HttpStatusCode.OK); 81 | var responseContent = response.GetResponseData(); 82 | Debug.WriteLine(responseContent); 83 | 84 | 85 | // Parse the Given JSON document 86 | JObject jsonToValidate = JObject.Parse(responseContent); 87 | // Use the json path to query the json document 88 | // type caste the result of the query if needed 89 | var loggedOut = (bool)jsonToValidate.SelectToken("$.responseContext.mainAppWebResponseContext.loggedOut"); 90 | 91 | loggedOut.Should().BeTrue(); 92 | 93 | var headerJsonObject = jsonToValidate.SelectToken("$.header"); 94 | Header headers = JsonSerializer.Deserialize
(headerJsonObject.ToString()); 95 | headers.feedTabbedHeaderRenderer.Should().NotBeNull(); 96 | } 97 | 98 | [ClassCleanup] 99 | public static void TearDown() 100 | { 101 | _client?.Dispose(); 102 | } 103 | } 104 | 105 | // Model class for Sub Object 106 | class Runs 107 | { 108 | public string text { get; set; } 109 | 110 | } 111 | class Title 112 | { 113 | public IList runs { get; set; } 114 | 115 | } 116 | class FeedTabbedHeaderRenderer 117 | { 118 | public Title title { get; set; } 119 | 120 | } 121 | 122 | class Header 123 | { 124 | public FeedTabbedHeaderRenderer feedTabbedHeaderRenderer { get; set; } 125 | 126 | } 127 | 128 | class Application 129 | { 130 | public Header header { get; set; } 131 | 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /WebServiceAutomation/Helper/Request/HttpAsyncClientHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WebServiceAutomation.Model; 8 | 9 | namespace WebServiceAutomation.Helper.Request 10 | { 11 | public class HttpAsyncClientHelper 12 | { 13 | private HttpClient httpClient; 14 | private HttpRequestMessage httpRequestMessage; 15 | private RestResponse restResponse; 16 | 17 | private HttpClient AddHeadersAndCreateHttpClient(Dictionary httpHeader) 18 | { 19 | HttpClient httpClient = new HttpClient(); 20 | 21 | if (null != httpHeader) 22 | { 23 | foreach (string key in httpHeader.Keys) 24 | { 25 | httpClient.DefaultRequestHeaders.Add(key, httpHeader[key]); 26 | 27 | } 28 | } 29 | return httpClient; 30 | 31 | } 32 | 33 | private HttpRequestMessage CreateHttpRequestMessage(string requestUrl, HttpMethod httpMethod, HttpContent httpContent) 34 | { 35 | HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, requestUrl); 36 | if (!((httpMethod == HttpMethod.Get) || (httpMethod == HttpMethod.Delete))) 37 | httpRequestMessage.Content = httpContent; 38 | return httpRequestMessage; 39 | } 40 | 41 | private RestResponse SendRequest(string requestUrl, HttpMethod httpMethod, HttpContent httpContent, Dictionary httpHeader) 42 | { 43 | httpClient = AddHeadersAndCreateHttpClient(httpHeader); 44 | httpRequestMessage = CreateHttpRequestMessage(requestUrl, httpMethod, httpContent); 45 | 46 | try 47 | { 48 | Task httpResponseMessage = httpClient.SendAsync(httpRequestMessage); 49 | restResponse = new RestResponse((int)httpResponseMessage.Result.StatusCode, httpResponseMessage.Result.Content.ReadAsStringAsync().Result); 50 | } 51 | catch (Exception err) 52 | { 53 | restResponse = new RestResponse(500, err.Message + "\n" + err.InnerException); 54 | Console.WriteLine(err.StackTrace); 55 | Console.WriteLine(err.InnerException); 56 | } 57 | finally 58 | { 59 | httpRequestMessage?.Dispose(); 60 | httpClient?.Dispose(); 61 | } 62 | 63 | return restResponse; 64 | } 65 | 66 | public async Task PerformGetRequest(string requestUrl, Dictionary httpHeader) 67 | { 68 | httpClient = AddHeadersAndCreateHttpClient(httpHeader); 69 | HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(requestUrl); 70 | int statusCode = (int)httpResponseMessage.StatusCode; 71 | var responseData = await httpResponseMessage.Content.ReadAsStringAsync(); 72 | return new RestResponse(statusCode, responseData); 73 | 74 | } 75 | 76 | public RestResponse PerformPostRequest(string requestUrl, HttpContent httpContent, Dictionary httpHeaders) 77 | { 78 | return SendRequest(requestUrl, HttpMethod.Post, httpContent, httpHeaders); 79 | } 80 | 81 | public RestResponse PerformPostRequest(string requestUrl, string data, string mediaType, Dictionary httpHeaders) 82 | { 83 | HttpContent httpContent = new StringContent(data, Encoding.UTF8, mediaType); 84 | return PerformPostRequest(requestUrl, httpContent, httpHeaders); 85 | } 86 | 87 | public RestResponse PerformPutRequest(string requestUrl, string content, string mediaType, Dictionary headers) 88 | { 89 | HttpContent httpContent = new StringContent(content, Encoding.UTF8, mediaType); 90 | return SendRequest(requestUrl, HttpMethod.Put, httpContent, headers); 91 | } 92 | 93 | public RestResponse PerformPutRequest(string requestUrl, HttpContent httpContent, Dictionary headers) 94 | { 95 | return SendRequest(requestUrl, HttpMethod.Put, httpContent, headers); 96 | } 97 | 98 | public RestResponse PerformDeleteRequest(string requestUrl) 99 | { 100 | return SendRequest(requestUrl, HttpMethod.Delete, null, null); 101 | } 102 | 103 | //overloaded version 104 | public RestResponse PerformDeleteRequest(string requestUrl, Dictionary headers) 105 | { 106 | return SendRequest(requestUrl, HttpMethod.Delete, null, headers); 107 | } 108 | } 109 | } 110 | --------------------------------------------------------------------------------