swagger-api / swagger-api/swagger-codegen

C# Call ApiClient.Deserialize method if type be Nullable<bool> will faill.

Open
#10,934 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Mustache
Stars
17.8k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

Description

Call ApiClient.Deserialize method if type be Nullable will faill.

  • Example:
        [Test]
        public void UserValidateTest()
        {
            // TODO uncomment below to test the method and replace null with proper value
            var body       = new ValidateRequest("pass@w0rd1~");
            var domainName = "dc.demo.com.tw";
            var userId     = "yao";
            var response   = this.instance.UserValidate(body, domainName, userId);
            Assert.IsInstanceOf<bool?>(response, "response is bool?");
        }
Swagger-codegen version

swagger-codegen-cli-3.0.25

Swagger declaration file content or url
{"swagger":"2.0","info":{"version":"V1","title":"ActiveDirectory Management REST API","x-swagger-net-version":"8.3.38.001"},"host":"localhost:44350","schemes":["https"],"paths":{"/ad/user/v1/{domainName}/{userId}/disable":{"get":{"tags":["Admin"],"summary":"停用","operationId":"User_Disable","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/enable":{"get":{"tags":["Admin"],"summary":"啟用","operationId":"User_Enable","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名檉名稱","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/employeeid":{"get":{"tags":["User"],"summary":"取得工號","operationId":"User_GetEmployeeId","consumes":[],"produces":["text/plain;charset=UTF-8"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"200":{"description":"成功","schema":{"type":"string"},"examples":{"text/plain;charset=UTF-8":"A001"}},"204":{"description":"找不到資料"}}}},"/ad/user/v1/{domainName}/locked":{"get":{"tags":["User"],"summary":"取得已鎖定帳號","operationId":"User_GetLocked","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"description":"Defines a command that asynchronously creates an {System.Net.Http.HttpResponseMessage}.","type":"object"}}}}},"/ad/user/v1/{domainName}/{userId}/info":{"get":{"tags":["User"],"summary":"取得帳號資訊","operationId":"User_GetUserInfo","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"200":{"description":"成功","schema":{"$ref":"#/definitions/FilterResponse"}},"204":{"description":"查無此帳號"}}}},"/ad/user/v1/{domainName}/users/info":{"get":{"tags":["User"],"summary":"取得所有帳號","operationId":"User_GetUsers","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"}],"responses":{"200":{"description":"成功","schema":{"items":{"$ref":"#/definitions/FilterResponse"},"xml":{"name":"FilterResponse","wrapped":true},"type":"array"}}}}},"/ad/user/v1/{domainName}/{userId}/status":{"get":{"tags":["User"],"summary":"取得帳號狀態","operationId":"User_GetUserStatus","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"200":{"description":"成功","schema":{"$ref":"#/definitions/FilterResponse"}},"204":{"description":"查無此帳號"}}}},"/ad/user/v1/{domainName}":{"post":{"tags":["Admin"],"summary":"新增用戶","operationId":"User_Insert","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"request","in":"body","description":"請求參數","required":true,"schema":{"$ref":"#/definitions/InsertRequest"}}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/isexist":{"get":{"tags":["User"],"summary":"帳號是否存在","operationId":"User_IsExist","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"200":{"description":"成功","schema":{"type":"boolean"}}}}},"/ad/user/v1/{domainName}/{userId}/employeeId":{"post":{"tags":["Admin"],"summary":"設定工號","operationId":"User_SetEmployeeId","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"},{"name":"request","in":"body","description":"請求","required":true,"schema":{"$ref":"#/definitions/ChangeEmployeeIdRequest"}}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/changePassword":{"post":{"tags":["Admin"],"summary":"變更密碼","operationId":"User_SetPassword","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"},{"name":"request","in":"body","required":true,"schema":{"$ref":"#/definitions/ChangePasswordRequest"}}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/unlock":{"post":{"tags":["Admin"],"summary":"解鎖","operationId":"User_Unlock","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域","required":true,"type":"string"},{"name":"userId","in":"path","description":"用戶帳號","required":true,"type":"string"}],"responses":{"202":{"description":"已接受"}}}},"/ad/user/v1/{domainName}/{userId}/validate":{"post":{"tags":["User"],"summary":"驗證帳號密碼","operationId":"User_Validate","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"domainName","in":"path","description":"網域名稱","required":true,"type":"string"},{"name":"userId","in":"path","required":true,"type":"string"},{"name":"request","in":"body","description":"驗證資訊","required":true,"schema":{"$ref":"#/definitions/ValidateRequest"}}],"responses":{"200":{"description":"成功","schema":{"type":"boolean"}}}}}},"definitions":{"CancellationToken":{"properties":{"IsCancellationRequested":{"readOnly":true,"type":"boolean"},"CanBeCanceled":{"readOnly":true,"type":"boolean"},"WaitHandle":{"$ref":"#/definitions/WaitHandle","readOnly":true}},"xml":{"name":"CancellationToken"},"type":"object"},"WaitHandle":{"properties":{"Handle":{"type":"object"},"SafeWaitHandle":{"$ref":"#/definitions/SafeWaitHandle"}},"xml":{"name":"WaitHandle"},"type":"object"},"SafeWaitHandle":{"properties":{"IsInvalid":{"readOnly":true,"type":"boolean"},"IsClosed":{"readOnly":true,"type":"boolean"}},"xml":{"name":"SafeWaitHandle"},"type":"object"},"FilterResponse":{"properties":{"GivenName":{"type":"string"},"MiddleName":{"type":"string"},"Surname":{"type":"string"},"EmailAddress":{"type":"string"},"VoiceTelephoneNumber":{"type":"string"},"EmployeeId":{"type":"string"},"Enabled":{"type":"boolean"},"AccountLockoutTime":{"type":"string","format":"date-time"},"LastLogon":{"type":"string","format":"date-time"},"PermittedLogonTimes":{"type":"string","format":"byte"},"AccountExpirationDate":{"type":"string","format":"date-time"},"SmartcardLogonRequired":{"type":"boolean"},"DelegationPermitted":{"type":"boolean"},"BadLogonCount":{"type":"integer","format":"int32"},"HomeDirectory":{"type":"string"},"HomeDrive":{"type":"string"},"ScriptPath":{"type":"string"},"LastPasswordSet":{"type":"string","format":"date-time"},"LastBadPasswordAttempt":{"type":"string","format":"date-time"},"PasswordNotRequired":{"type":"boolean"},"PasswordNeverExpires":{"type":"boolean"},"UserCannotChangePassword":{"type":"boolean"},"AllowReversiblePasswordEncryption":{"type":"boolean"},"ContextType":{"type":"string","enum":["Machine","Domain","ApplicationDirectory"]},"Description":{"type":"string"},"DisplayName":{"type":"string"},"SamAccountName":{"type":"string"},"UserPrincipalName":{"type":"string"},"Sid":{"type":"string"},"Guid":{"example":"00000000-0000-0000-0000-000000000000","type":"string","format":"uuid"},"DistinguishedName":{"type":"string"},"StructuralObjectClass":{"type":"string"},"Name":{"type":"string"},"Initials":{"description":"英文縮寫","type":"string"},"OfficeName":{"type":"string"}},"xml":{"name":"FilterResponse"},"type":"object"},"InsertRequest":{"properties":{"OrganizationUnit":{"description":"組織單位,簡稱OU","type":"string"},"UserName":{"description":"帳戶名稱","type":"string"},"Password":{"description":"密碼","type":"string"},"GivenName":{"description":"名","type":"string"},"Surname":{"description":"姓","type":"string"}},"xml":{"name":"InsertRequest"},"type":"object"},"ChangeEmployeeIdRequest":{"required":["EmployeeId"],"properties":{"EmployeeId":{"type":"string"}},"xml":{"name":"ChangeEmployeeIdRequest"},"type":"object"},"ChangePasswordRequest":{"required":["NewPassword"],"properties":{"NewPassword":{"type":"string"}},"xml":{"name":"ChangePasswordRequest"},"type":"object"},"ValidateRequest":{"required":["UserPassword"],"properties":{"UserPassword":{"type":"string"}},"xml":{"name":"ValidateRequest"},"type":"object"}},"securityDefinitions":{"basic":{"type":"basic","description":"Basic HTTP Authentication"}},"tags":[{"name":"User"}]}
Command line used for generation
Steps to reproduce
Related issues/PRs
Suggest a fix/enhancement

Modify codegen of code below

public partial class ApiClient
{
    public static object ChangeType(object value, Type conversion)
    {
        var t = conversion;

        if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return null;
            }

            t = Nullable.GetUnderlyingType(t);
        }

        return Convert.ChangeType(value, t);
    }

    /// <summary>
    ///     Deserialize the JSON string into a proper object.
    /// </summary>
    /// <param name="response">The HTTP response.</param>
    /// <param name="type">Object type.</param>
    /// <returns>Object representation of the JSON string.</returns>
    public object Deserialize(IRestResponse response, Type type)
    {
        var headers = response.Headers;
        if (type == typeof(byte[])) // return byte array
        {
            return response.RawBytes;
        }

        // TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
        if (type == typeof(Stream))
        {
            if (headers != null)
            {
                var filePath = string.IsNullOrEmpty(this.Configuration.TempFolderPath)
                                   ? Path.GetTempPath()
                                   : this.Configuration.TempFolderPath;
                var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
                foreach (var header in headers)
                {
                    var match = regex.Match(header.ToString());
                    if (match.Success)
                    {
                        var fileName =
                            filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
                        File.WriteAllBytes(fileName, response.RawBytes);
                        return new FileStream(fileName, FileMode.Open);
                    }
                }
            }

            var stream = new MemoryStream(response.RawBytes);
            return stream;
        }

        if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
        {
            return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind);
        }

        if (type == typeof(string)
            || type.Name.StartsWith("System.Nullable")
            || type.FullName.StartsWith("System.Nullable`1[")
        ) 
        {
            return ChangeType(response.Content, type);
        }

        // at this point, it must be a model (json)
        try
        {
            return JsonConvert.DeserializeObject(response.Content, type, this.serializerSettings);
        }
        catch (Exception e)
        {
            throw new ApiException(500, e.Message);
        }
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the C# ApiClient.Deserialize entry point and the User_Validate response in the supplied Swagger document, which is declared as boolean. Reproduce the failure with swagger-codegen-cli-3.0.25 and trace how the nullable response is handled; done means deserialization succeeds for that generated client.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.