diff --git a/CHANGELOG.md b/CHANGELOG.md index e58ab56..27fb790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +### version 3.0 +* update RestSharp to 109.0.1, this comes with many API breaking changes, some affecting us, see below: +* removal of basic auth - our API no longer makes sense with RestSharp immutable clients. +* switch from newtonsoft.json to system.text.json +* add unit test project +* drop all targets below net6. +* OAuth1 is no longer supported, we no longer sign requests. +* Request base classes are modified to remove support for signing requests. ### version 2.5 * added user/votes request route * Add net6.0 as a target framework diff --git a/pipeline.yml b/pipeline.yml index 606df1f..6221c54 100644 --- a/pipeline.yml +++ b/pipeline.yml @@ -35,7 +35,6 @@ soc2: hidden_email_list: dynamo_ws_access repository: env.HARMONY_REPO third_party_lib_paths: - - "third_party" - "bin\\release" deployment: diff --git a/src/AssemblyInfoGenerator/AssemblyInfo.cs b/src/AssemblyInfoGenerator/AssemblyInfo.cs index d2985a6..e00c6f5 100644 --- a/src/AssemblyInfoGenerator/AssemblyInfo.cs +++ b/src/AssemblyInfoGenerator/AssemblyInfo.cs @@ -36,7 +36,7 @@ // to distinguish one build from another. AssemblyFileVersion is specified // in AssemblyVersionInfo.cs so that it can be easily incremented by the // automated build process. -[assembly: AssemblyVersion("2.5.0.5065")] +[assembly: AssemblyVersion("3.0.0.2886")] // By default, the "Product version" shown in the file properties window is @@ -55,4 +55,4 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyFileVersion("2.5.0.5065")] +[assembly: AssemblyFileVersion("3.0.0.2886")] diff --git a/src/AssemblyInfoGenerator/AssemblyInfo.tt b/src/AssemblyInfoGenerator/AssemblyInfo.tt index 29f5cc2..9b8de4f 100644 --- a/src/AssemblyInfoGenerator/AssemblyInfo.tt +++ b/src/AssemblyInfoGenerator/AssemblyInfo.tt @@ -58,10 +58,10 @@ using System.Runtime.InteropServices; // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("<#= this.MajorVersion #>.<#= this.MinorVersion #>.<#= this.BuildNumber #>.<#= this.RevisionNumber #>")] <#+ -int MajorVersion = 2; -int MinorVersion = 5; +int MajorVersion = 3; +int MinorVersion = 0; int BuildNumber = 0; // The datetime baseline we choose using this algorithm will affect build number and all nuget packages uploaded // Please only change when major or minor version got incremented -int RevisionNumber = ((int)(DateTime.UtcNow - new DateTime(2022,1,1)).TotalDays)*10+((int)DateTime.UtcNow.Hour)/3; +int RevisionNumber = ((int)(DateTime.UtcNow - new DateTime(2023,1,1)).TotalDays)*10+((int)DateTime.UtcNow.Hour)/3; #> diff --git a/src/GregClient.sln b/src/GregClient.sln index df4b6ba..16ff6cb 100644 --- a/src/GregClient.sln +++ b/src/GregClient.sln @@ -5,7 +5,9 @@ VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GregClient", "GregClient\GregClient.csproj", "{644207B4-7E7F-474A-952E-3453960D8A01}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AssemblyInfoGenerator", "AssemblyInfoGenerator\AssemblyInfoGenerator.csproj", "{1B9F8D94-D6D5-4151-BF72-0F6C20A85ABC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssemblyInfoGenerator", "AssemblyInfoGenerator\AssemblyInfoGenerator.csproj", "{133FC760-5699-46D9-BEA6-E816B5F01016}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GregClientTests", "GregClientTests\GregClientTests.csproj", "{04331317-6CF9-42EE-B6A8-2B08C608C810}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -17,10 +19,14 @@ Global {644207B4-7E7F-474A-952E-3453960D8A01}.Debug|Any CPU.Build.0 = Debug|Any CPU {644207B4-7E7F-474A-952E-3453960D8A01}.Release|Any CPU.ActiveCfg = Release|Any CPU {644207B4-7E7F-474A-952E-3453960D8A01}.Release|Any CPU.Build.0 = Release|Any CPU - {1B9F8D94-D6D5-4151-BF72-0F6C20A85ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1B9F8D94-D6D5-4151-BF72-0F6C20A85ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1B9F8D94-D6D5-4151-BF72-0F6C20A85ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1B9F8D94-D6D5-4151-BF72-0F6C20A85ABC}.Release|Any CPU.Build.0 = Release|Any CPU + {133FC760-5699-46D9-BEA6-E816B5F01016}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {133FC760-5699-46D9-BEA6-E816B5F01016}.Debug|Any CPU.Build.0 = Debug|Any CPU + {133FC760-5699-46D9-BEA6-E816B5F01016}.Release|Any CPU.ActiveCfg = Release|Any CPU + {133FC760-5699-46D9-BEA6-E816B5F01016}.Release|Any CPU.Build.0 = Release|Any CPU + {04331317-6CF9-42EE-B6A8-2B08C608C810}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {04331317-6CF9-42EE-B6A8-2B08C608C810}.Debug|Any CPU.Build.0 = Debug|Any CPU + {04331317-6CF9-42EE-B6A8-2B08C608C810}.Release|Any CPU.ActiveCfg = Release|Any CPU + {04331317-6CF9-42EE-B6A8-2B08C608C810}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/GregClient/App.config b/src/GregClient/App.config index 3cf3ac5..296c08f 100644 --- a/src/GregClient/App.config +++ b/src/GregClient/App.config @@ -4,7 +4,4 @@ - - - diff --git a/src/GregClient/AuthProviders/BasicProvider.cs b/src/GregClient/AuthProviders/BasicProvider.cs deleted file mode 100644 index 80afef8..0000000 --- a/src/GregClient/AuthProviders/BasicProvider.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using RestSharp; -using RestSharp.Authenticators; - -namespace Greg.AuthProviders -{ - public class BasicProvider : IAuthProvider - { - private readonly string _username; - private readonly string _password; - - public BasicProvider(string username, string password) - { - _username = username; - _password = password; - } - - public void SignRequest(ref RestRequest m, RestClient client) - { - // Use the HttpBasicAuthenticator to write the auth information - // into the request header. This coincides with with the "basic" - // authentication strategy on Greg. - client.Authenticator = new HttpBasicAuthenticator(_username, _password); - } - - public void Logout() - { - } - - public bool Login() - { - return true; - } - - public LoginState LoginState - { - get { return LoginState.LoggedIn; } - } - - public string Username - { - get { return _username; } - } - - public event Func RequestLogin; - public event Action LoginStateChanged; - } -} diff --git a/src/GregClient/AuthProviders/IAuthProvider.cs b/src/GregClient/AuthProviders/IAuthProvider.cs index d6f888f..e411b6f 100644 --- a/src/GregClient/AuthProviders/IAuthProvider.cs +++ b/src/GregClient/AuthProviders/IAuthProvider.cs @@ -11,6 +11,7 @@ public interface IAuthProvider LoginState LoginState { get; } string Username { get; } + //TODO ideally would not force the use of restsharp just to set auth. /// /// This method should sign the request and params as OAuth1. /// OAuth parameters should be added to the query string. @@ -28,6 +29,8 @@ public interface IAuthProvider /// public interface IOAuth2AuthProvider : IAuthProvider { + //TODO ideally would not force the use of restsharp just to set auth. + /// /// This method should add the JWT access token to the Authorization header. /// Package manager expects a header in the form: Authorization: Bearer [accesstoken] diff --git a/src/GregClient/Converters/DependencyConverter.cs b/src/GregClient/Converters/DependencyConverter.cs index d052920..862eeb7 100644 --- a/src/GregClient/Converters/DependencyConverter.cs +++ b/src/GregClient/Converters/DependencyConverter.cs @@ -1,6 +1,7 @@ using Greg.Responses; -using Newtonsoft.Json; using System; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Greg.Converters { @@ -9,42 +10,26 @@ namespace Greg.Converters /// - a string, which is interpreted as the id of the dependency /// - an object having the expected properties, which is the default behavior /// - public class DependencyConverter : JsonConverter + public class DependencyConverter : JsonConverter { - public override bool CanWrite - { - get - { - return false; - } - } - - public override bool CanConvert(Type objectType) - { - return objectType == typeof(Dependency); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.ValueType == typeof(string)) + public override Dependency Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) { // This is interpreted as the id of the dependency. - Dependency dep = (Dependency)existingValue ?? new Dependency(); - dep._id = (string)reader.Value; + var dep =new Dependency(); + dep._id = reader.GetString(); return dep; } else { // Use the default deserialization behavior. - existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator(); - serializer.Populate(reader, existingValue); - return existingValue; + //do not pass the same options here as this method is called with, that will result in the converter being called again and again. + return JsonSerializer.Deserialize(ref reader); } } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void Write(Utf8JsonWriter writer, Dependency value, JsonSerializerOptions options) { - // Not needed as CanWrite is false. throw new NotImplementedException(); } } diff --git a/src/GregClient/GregClient.cs b/src/GregClient/GregClient.cs index f558c71..3fd0044 100644 --- a/src/GregClient/GregClient.cs +++ b/src/GregClient/GregClient.cs @@ -1,5 +1,6 @@ using Greg.Requests; using Greg.Responses; +using Greg.Utility; using RestSharp; using System; using System.Net; @@ -9,9 +10,7 @@ namespace Greg public class GregClient : IGregClient { private readonly RestClient _client; - - public string BaseUrl { get { return _client.BaseUrl.ToString(); } } - + public string BaseUrl { get { return _client.Options.BaseUrl.ToString(); } } public readonly IAuthProvider _authProvider; public IAuthProvider AuthProvider { @@ -21,9 +20,7 @@ public IAuthProvider AuthProvider public GregClient(IAuthProvider provider, string packageManagerUrl) { -#if LT_NET47 - ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -#else + // https://stackoverflow.com/questions/2819934/detect-windows-version-in-net // if the current OS is windows 7 or lower // set TLS to 1.2. @@ -32,41 +29,22 @@ public GregClient(IAuthProvider provider, string packageManagerUrl) { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; } -#endif _authProvider = provider; _client = new RestClient(packageManagerUrl); } - private IRestResponse ExecuteInternal(Request m) + private RestResponse ExecuteInternal(Request m) { - var req = new RestRequest(m.Path, m.HttpMethod); + + var req = new RestRequest(m.Path, m.HttpMethod.ToRestSharpHTTPMethod()); m.Build(ref req); if (m.RequiresAuthorization) { - //oauth2 - we don't need to sign/encode any parameters. - //Also don't need to create a temp request to avoid adsso putting header/body params - //in the query string. Just use original request, and inject access token. if (AuthProvider is IOAuth2AuthProvider) { AuthProvider.SignRequest(ref req, _client); } - //oauth1 - else - { // Issue: auth api was adding body params to the query string. - // Details: https://jira.autodesk.com/browse/DYN-1795 - // Build a subset of the original request, with only specific parameters that we need to authenticate. - // This means headers added in SignRequest will not exist on the request made to DPM. - var reqToSign = new RestRequest(req.Resource, req.Method); - var authParams = m.GetParamsToSign(ref req); - foreach (var par in authParams) - { - reqToSign.AddParameter(par); - } - // All reqToSign.Parameters will be added in the reqToSign.Resource. - AuthProvider.SignRequest(ref reqToSign, _client); - req.Resource = reqToSign.Resource; - } } try diff --git a/src/GregClient/GregClient.csproj b/src/GregClient/GregClient.csproj index 49abb6c..badb068 100644 --- a/src/GregClient/GregClient.csproj +++ b/src/GregClient/GregClient.csproj @@ -12,7 +12,7 @@ Properties Greg Greg - net452;net48;net5.0;net6.0 + net6.0 512 false @@ -41,15 +41,8 @@ 4 false - - - - - - - - + @@ -71,9 +64,6 @@ none - - - diff --git a/src/GregClient/PackageManagerClient.cs b/src/GregClient/PackageManagerClient.cs deleted file mode 100644 index 69d5ed9..0000000 --- a/src/GregClient/PackageManagerClient.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.IO; -using Greg.Requests; -using Greg.Responses; -using Greg.Utility; -using Newtonsoft.Json; -using RestSharp; - -namespace Greg -{ - /// - /// Package Manager REST Client for ACG API - /// - public class PackageManagerClient : IGregClient - { - private const string AFC_CODE = "DY1ON1"; - //Client for ACG REST API - private readonly RestClient _client; - //Client for file upload, the server address for file upload is different than ACG API - private readonly RestClient _fileClient; - - public string BaseUrl { get { return _client.BaseUrl.ToString(); } } - - public readonly IAuthProvider _authProvider; - public IAuthProvider AuthProvider - { - get { return _authProvider; } - } - - public PackageManagerClient(IAuthProvider provider, string packageManagerUrl, string fileStorageUrl) - { - _authProvider = provider; - _client = new RestClient(packageManagerUrl) - { - Authenticator = new RestSharp.Authenticators.NtlmAuthenticator() - }; - _fileClient = new RestClient(fileStorageUrl); - } - - /// - /// Execute the REST request - /// - /// - /// - private IRestResponse ExecuteInternal(PackageManagerRequest m) - { - if (m == null) - throw new Exception("Request object is not instance of type PackageManagerRequest."); - - var req = new RestRequest(m.Path, m.HttpMethod); - - m.Build(ref req); - - /// For GET request we need to pass AFC(Affiliation Code) in request header. - /// For all other request and Member requests we need to pass additional X-Session in request header. - /// X-Session header should be added from AuthProvider.SignRequest (ACG Auth Provider which is part of ACG login implementation) method. - /// If request is for upload file _flieClient is used, as URL for ACG API and File Upload server are different. - if (m.HttpMethod == Method.GET && !m.Path.Contains("members")) - SignRequest(req); - else - AuthProvider.SignRequest(ref req, _client); - - if (m.fileRequest) - return _fileClient.Execute(req); - else - return _client.Execute(req); - } - - /// - /// Add request headers for GET requests. No need to go through AuthProvider - /// - /// - public void SignRequest(RestRequest m) - { - m.AddHeader("Content-Type", "application/x-www-form-urlencoded"); - m.AddHeader("X-AFC", AFC_CODE); - } - - /// - /// Execute the REST request - /// - /// - /// - public Response Execute(Request m) - { - return new Response(ExecuteInternal((PackageManagerRequest)m)); - } - - /// - /// Execute and deserialize the request - /// - /// - /// - public ResponseBody ExecuteAndDeserialize(Request m) - { - return Execute(m).Deserialize(); - } - - /// - /// Execute the request and deserialize the content as dynamic type. - /// - /// The Type of content - /// The request. - /// A or null if there was an error - /// in executing the message. - public ResponseWithContentBody ExecuteAndDeserializeWithContent(Request m) - { - var response = this.Execute(m); - - return new ResponseWithContentBody() - { - message = response.InternalRestReponse.StatusDescription, - content = JsonConvert.DeserializeObject(response.InternalRestReponse.Content), - success = true - }; - } - - /// - /// Get the file stream from response and save locally. - /// - /// - /// - public string GetFileFromResponse(Response gregResponse) - { - var response = gregResponse.InternalRestReponse; - - if (!(response.ResponseUri != null && response.ResponseUri.AbsolutePath != null)) return ""; - - var tempOutput = System.IO.Path.Combine(FileUtilities.GetTempFolder(), System.IO.Path.GetFileName(response.ResponseUri.AbsolutePath)); - using (var f = new FileStream(tempOutput, FileMode.Create)) - { - f.Write(response.RawBytes, 0, (int)response.ContentLength); - } - - //var md5HeaderResp = response.Headers.FirstOrDefault(x => x.Name == "ETag"); - //if (md5HeaderResp == null) throw new Exception("Could not check integrity of package download!"); - - //var md5HeaderComputed = - // String.Join("", FileUtilities.GetMD5Checksum(tempOutput).Select(x => x.ToString("X"))).ToLower(); - - //if (md5HeaderResp.Value.ToString() == md5HeaderComputed) - // throw new Exception("Could not validate package integrity! Please try again!"); - - return tempOutput; - - } - } -} diff --git a/src/GregClient/Properties/AssemblyInfo.cs b/src/GregClient/Properties/AssemblyInfo.cs index 1375b67..cf94524 100644 --- a/src/GregClient/Properties/AssemblyInfo.cs +++ b/src/GregClient/Properties/AssemblyInfo.cs @@ -2,4 +2,4 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -[assembly: InternalsVisibleTo("GregClientSandbox")] +[assembly: InternalsVisibleTo("GregClientTests")] diff --git a/src/GregClient/Requests/BanPackage.cs b/src/GregClient/Requests/BanPackage.cs index 2e901b0..a852f75 100644 --- a/src/GregClient/Requests/BanPackage.cs +++ b/src/GregClient/Requests/BanPackage.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -23,9 +24,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } + get { return HttpMethod.Put; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/Deprecate.cs b/src/GregClient/Requests/Deprecate.cs index ed5907a..1e30cc7 100644 --- a/src/GregClient/Requests/Deprecate.cs +++ b/src/GregClient/Requests/Deprecate.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Text; using RestSharp; @@ -36,9 +37,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } + get { return HttpMethod.Put; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/Downvote.cs b/src/GregClient/Requests/Downvote.cs index f4d450b..01f3f0a 100644 --- a/src/GregClient/Requests/Downvote.cs +++ b/src/GregClient/Requests/Downvote.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; + +using System.Net.Http; using RestSharp; namespace Greg.Requests @@ -18,9 +16,9 @@ public override string Path get { return "downvote/" + this._id; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } + get { return HttpMethod.Put; } } private readonly string _id; diff --git a/src/GregClient/Requests/GetMaintainers.cs b/src/GregClient/Requests/GetMaintainers.cs index b1f90f6..55505c7 100644 --- a/src/GregClient/Requests/GetMaintainers.cs +++ b/src/GregClient/Requests/GetMaintainers.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -22,9 +23,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/GetMyPackages.cs b/src/GregClient/Requests/GetMyPackages.cs index d60fe6c..b9a0527 100644 --- a/src/GregClient/Requests/GetMyPackages.cs +++ b/src/GregClient/Requests/GetMyPackages.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -7,8 +8,6 @@ namespace Greg.Requests /// public class GetMyPackages : PackageReferenceRequest { - private readonly Method httpMethod = Method.GET; - /// /// GET request for fetching latest versions of all packages published by the current user. /// Authentication is required to identify user. @@ -16,8 +15,6 @@ public class GetMyPackages : PackageReferenceRequest public GetMyPackages() { this.ForceAuthentication = true; - - httpMethod = Method.GET; } /// @@ -31,9 +28,9 @@ public override string Path /// /// Http method used to make remote package manager API call. /// - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return httpMethod; } + get { return HttpMethod.Get; } } /// diff --git a/src/GregClient/Requests/HeaderCollectionDownload.cs b/src/GregClient/Requests/HeaderCollectionDownload.cs index ef32e10..004b478 100644 --- a/src/GregClient/Requests/HeaderCollectionDownload.cs +++ b/src/GregClient/Requests/HeaderCollectionDownload.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -49,9 +50,9 @@ public override string Path } } - public override RestSharp.Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/HeaderDownload.cs b/src/GregClient/Requests/HeaderDownload.cs index e510b58..0c47a9c 100644 --- a/src/GregClient/Requests/HeaderDownload.cs +++ b/src/GregClient/Requests/HeaderDownload.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -34,9 +35,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/HeaderVersionDownload.cs b/src/GregClient/Requests/HeaderVersionDownload.cs index 2334638..3ef360d 100644 --- a/src/GregClient/Requests/HeaderVersionDownload.cs +++ b/src/GregClient/Requests/HeaderVersionDownload.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -39,11 +40,11 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { get { - return Method.GET; + return HttpMethod.Get; } } diff --git a/src/GregClient/Requests/Hosts.cs b/src/GregClient/Requests/Hosts.cs index f0670d1..2c9f69e 100644 --- a/src/GregClient/Requests/Hosts.cs +++ b/src/GregClient/Requests/Hosts.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Net.Http; using RestSharp; namespace Greg.Requests @@ -21,9 +18,9 @@ public override string Path get { return "hosts"; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/PackageDownload.cs b/src/GregClient/Requests/PackageDownload.cs index 4342233..1d31876 100644 --- a/src/GregClient/Requests/PackageDownload.cs +++ b/src/GregClient/Requests/PackageDownload.cs @@ -1,8 +1,7 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; +using System.Net.Http; using Greg.Responses; using Greg.Utility; using RestSharp; @@ -27,9 +26,9 @@ public override string Path get { return _version != null ? "download/" + this._id + "/" + _version : "download/" + this._id; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } private readonly string _id; @@ -42,7 +41,7 @@ internal override void Build(ref RestRequest request) public static string GetFileFromResponse(Response gregResponse) { - var response = gregResponse.InternalRestReponse; + var response = gregResponse.InternalRestResponse; if ( !(response.ResponseUri != null && response.ResponseUri.AbsolutePath != null) ) return ""; diff --git a/src/GregClient/Requests/PackageManagerRequest.cs b/src/GregClient/Requests/PackageManagerRequest.cs index 93037b2..8df3a27 100644 --- a/src/GregClient/Requests/PackageManagerRequest.cs +++ b/src/GregClient/Requests/PackageManagerRequest.cs @@ -1,20 +1,19 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + using RestSharp; using System.IO; +using System.Net.Http; namespace Greg.Requests { public class PackageManagerRequest : Request { - private Method _httpMethod; + private HttpMethod _httpMethod; public readonly bool fileRequest; internal string fileToUpload; - public PackageManagerRequest(string path, RestSharp.Method httpMethod, bool fileRequest = false, string fileToUpload = "") : base() + public PackageManagerRequest(string path, HttpMethod httpMethod, bool fileRequest = false, string fileToUpload = "") : base() { _path = path; _httpMethod = httpMethod; @@ -31,7 +30,7 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { get { return _httpMethod; } } diff --git a/src/GregClient/Requests/PackageUpload.cs b/src/GregClient/Requests/PackageUpload.cs index b4562a3..77168ba 100644 --- a/src/GregClient/Requests/PackageUpload.cs +++ b/src/GregClient/Requests/PackageUpload.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.IO; +using System.Net.Http; using Greg.Utility; using RestSharp; @@ -31,14 +32,9 @@ public override string Path get { return "package"; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.POST; } - } - - internal override IList GetParamsToSign(ref RestRequest request) - { - return new List();// Nothing to sign yet. + get { return HttpMethod.Post; } } internal override void Build(ref RestRequest request) @@ -70,8 +66,7 @@ internal override void Build(ref RestRequest request) fs.Close(); } - var p = FileParameter.Create("pkg", bytes, ZipFile); - request.Files.Add(p); + request.AddFile("pkg", bytes, ZipFile); } } diff --git a/src/GregClient/Requests/PackageUploadRequestBody.cs b/src/GregClient/Requests/PackageUploadRequestBody.cs index 39cef65..cf64402 100644 --- a/src/GregClient/Requests/PackageUploadRequestBody.cs +++ b/src/GregClient/Requests/PackageUploadRequestBody.cs @@ -5,17 +5,9 @@ namespace Greg.Requests { public class PackageUploadRequestBody : PackageVersionUploadRequestBody { - - //!!!! it is important to keep this in mind: - //https://stackoverflow.com/questions/33107789/json-net-deserialization-constructor-vs-property-rules - - /// - /// Default constructor - should only be used for deserialization with json.net. - /// json.net will construct an empty object and fill it with properties with matching names. - /// + //public parameterless constructor used for system.text.json deserialization. public PackageUploadRequestBody() { - } public PackageUploadRequestBody(string name, string version, string description, @@ -24,48 +16,12 @@ public PackageUploadRequestBody(string name, string version, string description, string metadata, string group, IEnumerable dependencies, string siteUrl, string repositoryUrl, bool containsBinaries, IEnumerable nodeLibraryNames, IEnumerable hostDependencies, - string copyright_holder, string copyright_year) : - - this(name, version, description, - keywords, license, - contents, engine, engineVersion, - metadata, group, dependencies, - siteUrl, repositoryUrl, containsBinaries, - nodeLibraryNames) - { - this.host_dependencies = hostDependencies; - this.copyright_holder = copyright_holder; - this.copyright_year = copyright_year; - } - - [Obsolete("This constructor will be removed in a future release of packageManagerClient.")] - public PackageUploadRequestBody(string name, string version, string description, - IEnumerable keywords, string license, - string contents, string engine, string engineVersion, - string metadata, string group, IEnumerable dependencies, - string siteUrl, string repositoryUrl, bool containsBinaries, - IEnumerable nodeLibraryNames, IEnumerable hostDependencies) : - - this(name,version,description, - keywords,license, - contents,engine,engineVersion, - metadata,group,dependencies, - siteUrl,repositoryUrl,containsBinaries, - nodeLibraryNames) + string copyright_holder, string copyright_year) { this.host_dependencies = hostDependencies; this.copyright_holder = copyright_holder; this.copyright_year = copyright_year; - } - [Obsolete("This constructor will be removed in a future release of packageManagerClient.")] - public PackageUploadRequestBody(string name, string version, string description, - IEnumerable keywords, string license, - string contents, string engine, string engineVersion, - string metadata, string group, IEnumerable dependencies, - string siteUrl, string repositoryUrl, bool containsBinaries, - IEnumerable nodeLibraryNames) - { this.name = name; this.version = version; this.description = description; @@ -84,6 +40,9 @@ public PackageUploadRequestBody(string name, string version, string description, this.license = license; } + + + public string license { get; set; } } } \ No newline at end of file diff --git a/src/GregClient/Requests/PackageVersionUpload.cs b/src/GregClient/Requests/PackageVersionUpload.cs index cd4cac4..ad5f4b6 100644 --- a/src/GregClient/Requests/PackageVersionUpload.cs +++ b/src/GregClient/Requests/PackageVersionUpload.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Net.Http; using Greg.Utility; using RestSharp; @@ -28,14 +29,9 @@ public override string Path get { return "package"; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } - } - - internal override IList GetParamsToSign(ref RestRequest request) - { - return new List();// Nothing to sign yet. + get { return HttpMethod.Put; } } internal override void Build(ref RestRequest request) @@ -68,8 +64,7 @@ internal override void Build(ref RestRequest request) fs.Close(); } - var p = FileParameter.Create("pkg", bytes, ZipFile); - request.Files.Add(p); + request.AddFile("pkg", bytes, ZipFile); } } diff --git a/src/GregClient/Requests/PackageVersionUploadRequestBody.cs b/src/GregClient/Requests/PackageVersionUploadRequestBody.cs index c8253c4..83dbc2a 100644 --- a/src/GregClient/Requests/PackageVersionUploadRequestBody.cs +++ b/src/GregClient/Requests/PackageVersionUploadRequestBody.cs @@ -5,7 +5,9 @@ namespace Greg.Requests { public class PackageVersionUploadRequestBody : RequestBody { - internal PackageVersionUploadRequestBody() + + //public parameterless constructor used for system.text.json deserialization. + public PackageVersionUploadRequestBody() { } @@ -37,81 +39,12 @@ public PackageVersionUploadRequestBody(string name, string version, string descr string metadata, string group, IEnumerable dependencies, string siteUrl, string repositoryUrl, bool containsBinaries, IEnumerable nodeLibraryNames, IEnumerable hostDependencies, - string copyright_holder, string copyright_year) : + string copyright_holder, string copyright_year) - this(name, version, description, - keywords, - contents, engine, engineVersion, - metadata, group, dependencies, - siteUrl, repositoryUrl, containsBinaries, - nodeLibraryNames) { this.host_dependencies = hostDependencies; this.copyright_holder = copyright_holder; this.copyright_year = copyright_year; - } - - - /// - /// Constructor which can be used to set hostDependencies - /// - /// Package name - /// Package version - /// Package description - /// Package keywords for quick identification - /// Package content description - /// Package engine name, usually is set to Dynamo - /// Package engine version, usually is set to use Dynamo version - /// - /// - /// Package dependencies - /// - /// - /// boolean flag indicating if the package contains binaries - /// - /// external programs this package depends on. - [Obsolete("This constructor will be removed in a future release of packageManagerClient.")] - public PackageVersionUploadRequestBody(string name, string version, string description, - IEnumerable keywords, - string contents, string engine, string engineVersion, - string metadata, string group, IEnumerable dependencies, - string siteUrl, string repositoryUrl, bool containsBinaries, - IEnumerable nodeLibraryNames, IEnumerable hostDependencies) : - - this(name, version, description, - keywords, - contents, engine, engineVersion, - metadata, group, dependencies, - siteUrl, repositoryUrl, containsBinaries, - nodeLibraryNames) - { - this.host_dependencies = hostDependencies; - } - - /// - /// Constructor - /// - /// Package name - /// Package version - /// Package description - /// Package keywords for quick identification - /// Package content description - /// Package engine name, usually is set to Dynamo - /// Package engine version, usually is set to use Dynamo version - /// - /// - /// Package dependencies - /// - /// - /// boolean flag indicating if the package contains binaries - /// - [Obsolete("This constructor will be removed in a future release of packageManagerClient.")] - public PackageVersionUploadRequestBody(string name, string version, string description, - IEnumerable keywords, string contents, string engine, string engineVersion, - string metadata, string group, IEnumerable dependencies, - string siteUrl, string repositoryUrl, bool containsBinaries, - IEnumerable nodeLibraryNames) - { this.name = name; this.version = version; this.description = description; @@ -128,6 +61,8 @@ public PackageVersionUploadRequestBody(string name, string version, string descr this.node_libraries = nodeLibraryNames; } + + public string file_hash { get; set; } public string name { get; set; } diff --git a/src/GregClient/Requests/Request.cs b/src/GregClient/Requests/Request.cs index 1e6e841..6079f18 100644 --- a/src/GregClient/Requests/Request.cs +++ b/src/GregClient/Requests/Request.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Text; using RestSharp; @@ -17,23 +18,18 @@ public bool RequiresAuthorization { get { - return HttpMethod == Method.POST || HttpMethod == Method.PUT || ForceAuthentication; + return HttpMethod == HttpMethod.Post || HttpMethod == HttpMethod.Put || ForceAuthentication; } } public abstract string Path { get; } - public abstract Method HttpMethod { get; } + public abstract HttpMethod HttpMethod { get; } public RequestBody RequestBody { get; set; } public bool ForceAuthentication { get; set; } - internal virtual IList GetParamsToSign(ref RestRequest request) - { - return request.Parameters;// By default send all params to sign. - } - internal abstract void Build(ref RestRequest request); } } diff --git a/src/GregClient/Requests/RequestBody.cs b/src/GregClient/Requests/RequestBody.cs index 2c8ddc7..ae2bc4b 100644 --- a/src/GregClient/Requests/RequestBody.cs +++ b/src/GregClient/Requests/RequestBody.cs @@ -1,14 +1,12 @@ -using RestSharp.Serialization.Json; +using System.Text.Json; namespace Greg.Requests { public abstract class RequestBody { - public static JsonSerializer jsonSerializer = new JsonSerializer(); - public virtual string AsJson() { - return jsonSerializer.Serialize(this); + return JsonSerializer.Serialize(this); } } diff --git a/src/GregClient/Requests/Search.cs b/src/GregClient/Requests/Search.cs index f6f8c7e..f2340df 100644 --- a/src/GregClient/Requests/Search.cs +++ b/src/GregClient/Requests/Search.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -18,9 +19,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } private readonly string _query; diff --git a/src/GregClient/Requests/TermsOfUse.cs b/src/GregClient/Requests/TermsOfUse.cs index 9432a7f..69f7536 100644 --- a/src/GregClient/Requests/TermsOfUse.cs +++ b/src/GregClient/Requests/TermsOfUse.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Text; using RestSharp; @@ -8,14 +9,14 @@ namespace Greg.Requests { public class TermsOfUse : Request { - private readonly Method httpMethod = Method.GET; + private readonly HttpMethod httpMethod = System.Net.Http.HttpMethod.Get; public TermsOfUse(bool queryAcceptanceStatus) { // both endpoints require authentication by the user this.ForceAuthentication = true; - httpMethod = queryAcceptanceStatus ? Method.GET : Method.PUT; + httpMethod = queryAcceptanceStatus ? System.Net.Http.HttpMethod.Get: System.Net.Http.HttpMethod.Put; } public override string Path @@ -23,7 +24,7 @@ public override string Path get { return "tou"; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { get { return httpMethod; } } diff --git a/src/GregClient/Requests/Undeprecate.cs b/src/GregClient/Requests/Undeprecate.cs index f17730e..571916d 100644 --- a/src/GregClient/Requests/Undeprecate.cs +++ b/src/GregClient/Requests/Undeprecate.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Text; using RestSharp; @@ -36,9 +37,9 @@ public override string Path } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } + get { return HttpMethod.Put; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Requests/Upvote.cs b/src/GregClient/Requests/Upvote.cs index 19fa818..0e6fb79 100644 --- a/src/GregClient/Requests/Upvote.cs +++ b/src/GregClient/Requests/Upvote.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Text; using RestSharp; @@ -18,9 +19,9 @@ public override string Path get { return "upvote/" + this._id; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.PUT; } + get { return HttpMethod.Put; } } private readonly string _id; diff --git a/src/GregClient/Requests/UserVotes.cs b/src/GregClient/Requests/UserVotes.cs index c3c2fff..3e3f922 100644 --- a/src/GregClient/Requests/UserVotes.cs +++ b/src/GregClient/Requests/UserVotes.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -7,8 +8,6 @@ namespace Greg.Requests /// public class GetUserVotes : PackageReferenceRequest { - private readonly Method httpMethod = Method.GET; - /// /// GET request for fetching all votes by the current user. /// Authentication is required to identify user. @@ -16,8 +15,6 @@ public class GetUserVotes : PackageReferenceRequest public GetUserVotes() { this.ForceAuthentication = true; - - httpMethod = Method.GET; } /// /// Path used to call remote package manager API endpoint. @@ -30,9 +27,9 @@ public override string Path /// /// Http method used to make remote package manager API call. /// - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return httpMethod; } + get { return HttpMethod.Get; } } /// diff --git a/src/GregClient/Requests/ValidateAuth.cs b/src/GregClient/Requests/ValidateAuth.cs index a6c322d..faaa89d 100644 --- a/src/GregClient/Requests/ValidateAuth.cs +++ b/src/GregClient/Requests/ValidateAuth.cs @@ -1,4 +1,5 @@ using RestSharp; +using System.Net.Http; namespace Greg.Requests { @@ -14,9 +15,9 @@ public override string Path get { return "validate"; } } - public override Method HttpMethod + public override HttpMethod HttpMethod { - get { return Method.GET; } + get { return HttpMethod.Get; } } internal override void Build(ref RestRequest request) diff --git a/src/GregClient/Responses/Responses.cs b/src/GregClient/Responses/Responses.cs index c30b7f6..3beb47b 100644 --- a/src/GregClient/Responses/Responses.cs +++ b/src/GregClient/Responses/Responses.cs @@ -1,41 +1,30 @@ using System; using System.Collections.Generic; using RestSharp; -using Newtonsoft.Json; using Greg.Converters; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Greg.Responses { public class Response { - private static JsonSerializerSettings settings; + private static JsonSerializerOptions settings; - internal Response(IRestResponse response) + internal Response(RestResponse response) { - InternalRestReponse = response; + InternalRestResponse = response; } - public static JsonSerializerSettings Settings + public static JsonSerializerOptions Settings { get { if (settings == null) { - settings = new JsonSerializerSettings - { - Error = (sender, args) => - { - if (System.Diagnostics.Debugger.IsAttached) - { - System.Diagnostics.Debugger.Break(); - } - }, - Converters = new List() - { - new DependencyConverter() - } - }; + settings = new JsonSerializerOptions(JsonSerializerDefaults.Web); + settings.Converters.Add(new DependencyConverter()); } return settings; } @@ -45,8 +34,7 @@ public ResponseBody Deserialize() { try { - //return jsonDeserializer.Deserialize(InternalRestReponse); - return JsonConvert.DeserializeObject(InternalRestReponse.Content, Settings); + return JsonSerializer.Deserialize(InternalRestResponse.Content, Settings); } catch { @@ -54,20 +42,20 @@ public ResponseBody Deserialize() } } - internal IRestResponse InternalRestReponse { get; set; } + internal RestSharp.RestResponse InternalRestResponse { get; set; } } public class ResponseWithContent : Response { - public ResponseWithContent(IRestResponse response) : base(response) + //TODO does this need to be public? How to avoid leaking RestSharp types? + public ResponseWithContent(RestSharp.RestResponse response) : base(response) { } public ResponseWithContentBody DeserializeWithContent() { - return JsonConvert.DeserializeObject>(InternalRestReponse.Content, Settings); - //return jsonDeserializer.Deserialize>(InternalRestReponse); + return JsonSerializer.Deserialize>(InternalRestResponse.Content, Settings); } } diff --git a/src/GregClient/Utility/FileUtilities.cs b/src/GregClient/Utility/FileUtilities.cs index c78cdf7..b1880ae 100644 --- a/src/GregClient/Utility/FileUtilities.cs +++ b/src/GregClient/Utility/FileUtilities.cs @@ -62,7 +62,7 @@ public static byte[] GetMD5Checksum(string filename) /// public static byte[] GetFileHash(FileInfo fInfo) { - var mySHA256 = SHA256Managed.Create(); + var mySHA256 = SHA256.Create(); byte[] hashValue; diff --git a/src/GregClient/Utility/Utilities.cs b/src/GregClient/Utility/Utilities.cs index c0de602..9eb8456 100644 --- a/src/GregClient/Utility/Utilities.cs +++ b/src/GregClient/Utility/Utilities.cs @@ -1,16 +1,20 @@ -using RestSharp; + using System; using System.Collections; using System.Configuration; using System.IO; +using System.Net.Http; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Xml; namespace Greg.Utility { - public static class AppSettingMgr + internal static class AppSettingMgr { private static XmlDocument debugDoc; @@ -25,7 +29,7 @@ static AppSettingMgr() debugDoc = new XmlDocument(); debugDoc.Load(configPath); } - catch(Exception ex) + catch (Exception ex) { Console.WriteLine("The referenced configuration file, {0}, could not be loaded", configPath); Console.WriteLine(ex.Message); @@ -92,16 +96,9 @@ private static string getItem(String key) } return null; } -#if NETFRAMEWORK - [Obsolete] - public static KeyValueConfigurationElement GetItem(String key) - { - return new KeyValueConfigurationElement(key, getItem(key)); - } -#endif } - public static class DebugLogger + internal static class DebugLogger { private static readonly bool enabled = false; @@ -122,7 +119,7 @@ static DebugLogger() } } - public static void LogResponse(IRestResponse restResp) + static internal void LogResponse(RestSharp.RestResponse restResp) { if (!enabled) { @@ -151,7 +148,7 @@ public static void LogResponse(IRestResponse restResp) errException = restResp.ErrorException, logtimeStamp = ts }; - outputFile.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(logRespObj)); + outputFile.WriteLine(JsonSerializer.Serialize(logRespObj)); } } catch @@ -190,52 +187,34 @@ public static string Relaxed(string value) } } - public class StringValueAttribute : System.Attribute - { - - private string _value; - - public StringValueAttribute(string value) - { - _value = value; - } - - public string Value - { - get { return _value; } - } - } - - public class StringEnum + + internal static class RestSharpExtensions { - private static Hashtable _stringValues = new Hashtable(); - - public static string GetStringValue(Enum value) + internal static RestSharp.Method ToRestSharpHTTPMethod(this HttpMethod httpMethod) { - string output = null; - Type type = value.GetType(); - - //Check first in our cached results... - if (_stringValues.ContainsKey(value)) - output = (_stringValues[value] as StringValueAttribute).Value; - else + switch (httpMethod) { - //Look for our 'StringValueAttribute' - //in the field's custom attributes - FieldInfo fi = type.GetField(value.ToString()); - StringValueAttribute[] attrs = - fi.GetCustomAttributes(typeof(StringValueAttribute), - false) as StringValueAttribute[]; - if (attrs.Length > 0) - { - _stringValues.Add(value, attrs[0]); - output = attrs[0].Value; - } + case HttpMethod m when m == HttpMethod.Post: + return RestSharp.Method.Post; + case HttpMethod m when m == HttpMethod.Put: + return RestSharp.Method.Put; + case HttpMethod m when m == HttpMethod.Delete: + return RestSharp.Method.Delete; + case HttpMethod m when m == HttpMethod.Options: + return RestSharp.Method.Options; + case HttpMethod m when m == HttpMethod.Get: + return RestSharp.Method.Get; + case HttpMethod m when m == HttpMethod.Head: + return RestSharp.Method.Head; + case HttpMethod m when m == HttpMethod.Patch: + return RestSharp.Method.Patch; + case HttpMethod m when m == HttpMethod.Trace: + default: + throw new ArgumentOutOfRangeException($"no restsharp http method for {httpMethod.Method}"); } - - return output; } } + } diff --git a/src/GregClientSandbox/GregClientSandbox.csproj b/src/GregClientSandbox/GregClientSandbox.csproj deleted file mode 100644 index 0adf1dd..0000000 --- a/src/GregClientSandbox/GregClientSandbox.csproj +++ /dev/null @@ -1,74 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {12F6037C-A559-408E-AD10-4FBF05285AC3} - Exe - Properties - GregClientSandbox - GregClientSandbox - v4.8 - - - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - ..\packages\RestSharp.106.12.0\lib\net452\RestSharp.dll - - - - - - - - - - - - - - - - - {644207B4-7E7F-474A-952E-3453960D8A01} - GregClient - - - - - - - - - \ No newline at end of file diff --git a/src/GregClientSandbox/Program.cs b/src/GregClientSandbox/Program.cs deleted file mode 100644 index 894bf86..0000000 --- a/src/GregClientSandbox/Program.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using Greg; -using Greg.Requests; -using Greg.Responses; -using Greg.Utility; -using Greg.AuthProviders; -using RestSharp; -using RestSharp.Serialization.Json; - -namespace GregClientSandbox -{ - internal class Samples - { - /// - /// A basic auth provider specifying the test user - /// name and password that correspond to the test environment on Greg. - /// - private static BasicProvider provider = new BasicProvider("test", "e0jlZfJfKS"); - - /// - /// A GregClient specifying the local host. The alternate IP provided is for - /// production Reach. - /// - private static GregClient pmc = new GregClient(provider, "http://107.20.146.184/"); - //private static GregClient pmc = new GregClient(provider, "http://localhost:8080/"); - //private static GregClient pmc = new GregClient(provider, "http://dynamopackages.com/"); - - private static string DownloadPackageByIdTest() - { - var nv = new PackageDownload("5225e7dde2f476ca05000057"); - var response = pmc.Execute(nv); - var pathDl = PackageDownload.GetFileFromResponse(response); - var output = FileUtilities.UnZip(pathDl); - return pathDl; - } - - private static void UploadDynamoPackageVersionTest() - { - var keywords = new List() {"neat", "ok"}; - var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", - new List() { new PackageDependency("peter", "0.1.0"), new PackageDependency("stephen", "0.1.0") }, "", "", - false, new List(), new List(), "Dynamo Team", "2021"); - - var files = new List() {"../test/pedro.dyf", "../test/RootNode.dyf"}; - var request = new PackageVersionUpload(nv, files); - Console.WriteLine(request.RequestBody.AsJson()); - } - - private static void UploadDynamoPackageWithHostDependencyTest() - { - var keywords = new List() { "Civil" }; - var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", - new List() { new PackageDependency("Ram", "0.1.0"), new PackageDependency("Ian", "0.1.0") }, "", "", - false, new List(), new List() { "Civil3D" }, "Dynamo Team", "2021"); - - var files = new List() { "../test/pedro.dyf", "../test/RootNode.dyf" }; - var request = new PackageVersionUpload(nv, files); - Console.WriteLine(request.RequestBody.AsJson()); - } - - private static void UploadDynamoPackageVersionWithFilesTest() - { - var keywords = new List() { "neat", "ok" }; - var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", - new List() { new PackageDependency("peter", "0.1.0"), new PackageDependency("stephen", "0.1.0") }, "", "", false, new List(), new List(), "", ""); - - var files = new List() {"../../../../test/pedro.dyf", "../../../../test/RootNode.dyf"}; - - var request = new PackageVersionUpload(nv, files); - - var rr = new RestRequest(); - request.Build(ref rr); - - //var response = pmc.ExecuteAndDeserialize(nv); - Console.WriteLine(request.RequestBody.AsJson()); - } - - private static void DownloadDynamoPackageByEngineAndNameTest() - { - var nv = new HeaderDownload("dynamo", "Third .NET Package"); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent(nv); - Console.WriteLine(pkgResponse.content); // the package - } - - private static void DownloadDynamoPackageByIdTest() - { - var nv = new HeaderDownload("51eccaac7fa5b0146b000005"); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent(nv); - //var pkgResponse = pmc.Execute(nv); - - Console.WriteLine(pkgResponse.content.name); // the package - } - - private static void DownloadAllPackagesTest() - { - var nv = HeaderCollectionDownload.All(); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent>(nv); - Console.WriteLine(pkgResponse.content); - } - - private static void DownloadByEngineTest() - { - var nv = HeaderCollectionDownload.ByEngine("dynamo"); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent>(nv); - Console.WriteLine(pkgResponse.content); - } - - private static void DownloadDynamoPackageMaintainersByEngineAndNameTest() - { - var nv = new GetMaintainers("dynamo", "Third .NET Package"); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent(nv); - Console.WriteLine(pkgResponse.content); - } - - private static void SearchWithQueryTest() - { - var nv = new Search("*ython"); - var pkgResponse = pmc.ExecuteAndDeserializeWithContent>(nv); - Console.WriteLine(pkgResponse.content); - } - - private static void ValidateAuthTest() - { - var nv = new ValidateAuth(); - var pkgResponse = pmc.ExecuteAndDeserialize(nv); - Console.WriteLine(pkgResponse.message); - } - - private static void ListHostsTest() - { - var hosts = new Hosts(); - var hostsResponse = pmc.ExecuteAndDeserializeWithContent>(hosts); - Console.WriteLine(hostsResponse.content); - } - - private static void GetPackageVersionHeaderTest() - { - var req = new HeaderVersionDownload("dynamo", "get package version test", "0.1.1"); - var res = pmc.ExecuteAndDeserializeWithContent(req); - var serializer = new JsonSerializer(); - Console.WriteLine(serializer.Serialize(res.content)); - } - - static void Main(string[] args) - { - //ListHostsTest(); - //DownloadPackageByIdTest(); - //DownloadAllPackagesTest(); - //GetPackageVersionHeaderTest(); - Console.Read(); - } - } -} - diff --git a/src/GregClientSandbox/Properties/AssemblyInfo.cs b/src/GregClientSandbox/Properties/AssemblyInfo.cs deleted file mode 100644 index c13bf48..0000000 --- a/src/GregClientSandbox/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("GregClientSandbox")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Autodesk, Inc.")] -[assembly: AssemblyProduct("GregClientSandbox")] -[assembly: AssemblyCopyright("Copyright © Autodesk, Inc. 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a994b2a1-b16f-4b10-b6d7-752ac452d0b5")] - -// version information for an assembly consists of the following four values: -// -// Major version -// Minor version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/GregClientSandbox/app.config b/src/GregClientSandbox/app.config deleted file mode 100644 index 786a845..0000000 --- a/src/GregClientSandbox/app.config +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/GregClientSandbox/packages.config b/src/GregClientSandbox/packages.config deleted file mode 100644 index 2d8fd35..0000000 --- a/src/GregClientSandbox/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/GregClientTests/GlobalUsings.cs b/src/GregClientTests/GlobalUsings.cs new file mode 100644 index 0000000..cefced4 --- /dev/null +++ b/src/GregClientTests/GlobalUsings.cs @@ -0,0 +1 @@ +global using NUnit.Framework; \ No newline at end of file diff --git a/src/GregClientTests/GregClientTests.cs b/src/GregClientTests/GregClientTests.cs new file mode 100644 index 0000000..480fac5 --- /dev/null +++ b/src/GregClientTests/GregClientTests.cs @@ -0,0 +1,165 @@ +using Greg; +using Greg.Requests; +using Greg.Responses; +using Greg.Utility; +using RestSharp; +using System.Reflection; +using System.Text.Json; + +namespace GregClientTests +{ + public class Tests + { + [SetUp] + public void Setup() + { + } + + [Test] + public void GetPackageHeaderTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + //meshtoolkit + var req = new HeaderDownload("56273e18662bf0e908000278"); + var res = pmc.ExecuteAndDeserializeWithContent(req); + //assert that dependency objects were deserialzied correctly when they were json objects. + Assert.That(res.content.used_by.All(x => x.name is not null)); + Assert.That(res.content.name == "MeshToolkit"); + } + + [Test] + public void GetPackageVersionHeaderTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + + var req = new HeaderVersionDownload("dynamo", "DynaShape", "0.8.0"); + var res = pmc.ExecuteAndDeserializeWithContent(req); + //assert that dependency objects were deserialzied correctly when they were just strings, name should be null. + Assert.That(res.content.full_dependency_ids.Count == 2); + Assert.That(res.content.full_dependency_ids.All(x => x.name is null)); + } + [Test] + public void DownloadPackageByIdTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var nv = new PackageDownload("5225e7dde2f476ca05000057"); + var response = pmc.Execute(nv); + var pathDl = PackageDownload.GetFileFromResponse(response); + var output = FileUtilities.UnZip(pathDl); + Assert.That(!string.IsNullOrEmpty(output)); + Assert.That(new DirectoryInfo(output).Exists); + } + + [Test] + public void UploadDynamoPackageVersionTest() + { + var keywords = new List() { "neat", "ok" }; + var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", + new List() { new PackageDependency("peter", "0.1.0"), new PackageDependency("stephen", "0.1.0") }, "", "", + false, new List(), new List(), "Dynamo Team", "2021"); + + var files = new List() { "../test/pedro.dyf", "../test/RootNode.dyf" }; + var request = new PackageVersionUpload(nv, files); + Assert.That(request.RequestBody.AsJson().Equals("{\"file_hash\":null,\"name\":\"Third .NET Package\",\"version\":\"2.1.0\",\"description\":\"\",\"group\":\"group\",\"keywords\":[\"neat\",\"ok\"],\"dependencies\":[{\"name\":\"peter\",\"version\":\"0.1.0\"},{\"name\":\"stephen\",\"version\":\"0.1.0\"}],\"host_dependencies\":[],\"contents\":\"contents\",\"engine_version\":\"0.1.0\",\"engine\":\"dynamo\",\"engine_metadata\":\"metadata\",\"site_url\":\"\",\"repository_url\":\"\",\"contains_binaries\":false,\"node_libraries\":[],\"copyright_holder\":\"Dynamo Team\",\"copyright_year\":\"2021\"}")); + Console.WriteLine(request.RequestBody.AsJson()); + } + + [Test] + public void UploadDynamoPackageWithHostDependencyTest() + { + var keywords = new List() { "Civil" }; + var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", + new List() { new PackageDependency("Ram", "0.1.0"), new PackageDependency("Ian", "0.1.0") }, "", "", + false, new List(), new List() { "Civil3D" }, "Dynamo Team", "2021"); + + var files = new List() { "../test/pedro.dyf", "../test/RootNode.dyf" }; + var request = new PackageVersionUpload(nv, files); + Assert.That(request.RequestBody.AsJson().Equals("{\"file_hash\":null,\"name\":\"Third .NET Package\",\"version\":\"2.1.0\",\"description\":\"\",\"group\":\"group\",\"keywords\":[\"Civil\"],\"dependencies\":[{\"name\":\"Ram\",\"version\":\"0.1.0\"},{\"name\":\"Ian\",\"version\":\"0.1.0\"}],\"host_dependencies\":[\"Civil3D\"],\"contents\":\"contents\",\"engine_version\":\"0.1.0\",\"engine\":\"dynamo\",\"engine_metadata\":\"metadata\",\"site_url\":\"\",\"repository_url\":\"\",\"contains_binaries\":false,\"node_libraries\":[],\"copyright_holder\":\"Dynamo Team\",\"copyright_year\":\"2021\"}")); + Console.WriteLine(request.RequestBody.AsJson()); + } + + [Test] + public void UploadDynamoPackageVersionWithFilesTest() + { + var keywords = new List() { "neat", "ok" }; + var nv = new PackageVersionUploadRequestBody("Third .NET Package", "2.1.0", "", keywords, "contents", "dynamo", "0.1.0", "metadata", "group", + new List() { new PackageDependency("peter", "0.1.0"), new PackageDependency("stephen", "0.1.0") }, "", "", false, new List(), new List(), "", ""); + + var files = new List() {Assembly.GetExecutingAssembly().Location }; + + var request = new PackageVersionUpload(nv, files); + + var rr = new RestRequest(); + request.Build(ref rr); + Assert.That(request.Files.Count, Is.EqualTo(1)); + Console.WriteLine(request.RequestBody.AsJson()); + } + + [Test] + public void DownloadDynamoPackageByEngineAndNameTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + + var nv = new HeaderDownload("dynamo", "MeshToolkit"); + var pkgResponse = pmc.ExecuteAndDeserializeWithContent(nv); + Assert.That(pkgResponse.content.name, Is.EqualTo("MeshToolkit")); + Console.WriteLine(JsonSerializer.Serialize(pkgResponse.content)); // the package + } + + [Test] + public void DownloadAllPackagesTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var nv = HeaderCollectionDownload.All(); + var pkgResponse = pmc.ExecuteAndDeserializeWithContent>(nv); + Assert.That(pkgResponse.content.Count > 2000); + Assert.That(pkgResponse.content.All(x => x.banned is false)); + Assert.That(pkgResponse.content.Any(x => x.num_versions is >1)); + //seems like package headers don't actually contain the host deps - that makes sense,each version is different. + Assert.That(pkgResponse.content.All(x => x.host_dependencies is null)); + Assert.That(pkgResponse.content.Any(x => x.versions.Last().host_dependencies is not null)); + Assert.That(pkgResponse.content.Any(x => x.num_dependents is not 0)); + Assert.That(pkgResponse.content.Any(x=>x.site_url is not null)); + Assert.That(pkgResponse.content.Any(x => x.repository_url is not null)); + } + [Test] + public void DownloadByEngineTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var nv = HeaderCollectionDownload.ByEngine("dynamo"); + var pkgResponse = pmc.ExecuteAndDeserializeWithContent>(nv); + Assert.IsNotEmpty(pkgResponse.content); + } + + [Test] + public void DownloadDynamoPackageMaintainersByEngineAndNameTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var nv = new GetMaintainers("dynamo", "MeshToolkit"); + var pkgResponse = pmc.ExecuteAndDeserializeWithContent(nv); + Assert.That(pkgResponse.content.maintainers.Count, Is.EqualTo(1)); + } + + [Test] + + public void ValidateAuthTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var nv = new ValidateAuth(); + //this will be null as the string Unauthorized is not valid json + Assert.Null(pmc.ExecuteAndDeserialize(nv)); + Assert.That(pmc.Execute(nv).InternalRestResponse.Content, Is.EqualTo("Unauthorized")); + } + [Test] + + public void ListHostsTest() + { + GregClient pmc = new GregClient(null, "http://dynamopackages.com/"); + var hosts = new Hosts(); + var hostsResponse = pmc.ExecuteAndDeserializeWithContent>(hosts); + Console.WriteLine(JsonSerializer.Serialize(hostsResponse.content)); + Assert.That(hostsResponse.content.Count, Is.EqualTo(5)); + } + + } +} \ No newline at end of file diff --git a/src/GregClientTests/GregClientTests.csproj b/src/GregClientTests/GregClientTests.csproj new file mode 100644 index 0000000..ae7a002 --- /dev/null +++ b/src/GregClientTests/GregClientTests.csproj @@ -0,0 +1,24 @@ + + + + net6.0 + enable + enable + + false + true + + + + + + + + + + + + + + + diff --git a/third_party/RestSharp b/third_party/RestSharp deleted file mode 160000 index cc283fb..0000000 --- a/third_party/RestSharp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit cc283fb0843e1141f717dcc6b3009206b6c95b62