Results 1 to 6 of 6

Thread: Code Review Request - Feedback/Suggestions Wanted

  1. #1

    Thread Starter
    Member G_Hosa_Phat's Avatar
    Join Date
    May 2008
    Location
    Oklahoma City, OK
    Posts
    44

    Post Code Review Request - Feedback/Suggestions Wanted

    Hello, all. I'm currently working on trying to build a somewhat "generic" class for interacting with web-based API's. I'm working on a premise that the API's this will work with return JSON structures that I can deserialize using Newtonsoft's JSON.NET library. Since I know that each API will return different JSON structures, I've built response classes for most of the API's I'm currently working with.

    As you can see in the code listings below, there are a few helper methods (extension methods, etc.) and other referenced classes that I'm not explicitly including here to try to prevent this post from getting out of control (I can provide any of that code if you really want to see it). Also, I've tried to obfuscate a few details here and there, so you certainly may find the occasional typo. Still, with the production code, everything here seems to be working as expected. I'm just trying to make it "better".

    I do realize it's a pretty big ask to go over all of this, so I understand completely if you just ignore this post and move on. It's just that I feel like I've taken this about as far as I can and, since I'm the only developer/programmer I personally know, I really want to run this through someone else's filters before going too much further.

    vbnet Code:
    1. Imports System.Net
    2. Imports System.ComponentModel
    3. Imports Newtonsoft.Json
    4.  
    5. Public MustInherit Class APIBase
    6.     Protected Friend Enum WebMethod
    7.         <Description("GET")> HTTPGET = 1
    8.         <Description("POST")> HTTPPOST = 2
    9.         <Description("PUT")> HTTPPUT = 3
    10.         <Description("DELETE")> HTTPDELETE = 4
    11.     End Enum
    12.  
    13.     Protected Property API_URL As String
    14.  
    15.     Protected Function SubmitAPIRequest(ByVal APIURL As String, ByVal Method As WebMethod, ByVal APIEndpoint As String,
    16.                                         Optional ByVal RequestParameters As List(Of String) = Nothing,
    17.                                         Optional ByVal BodyContentType As String = "text/plain, application/json",
    18.                                         Optional ByVal SubmitBody As Object = Nothing,
    19.                                         Optional ByVal AdditionalHeaders As WebHeaderCollection = Nothing,
    20.                                         Optional ByVal Protocol As SecurityProtocolType = SecurityProtocolType.Tls12,
    21.                                         Optional ByVal IgnoreCertificateErrors As Boolean = True) As String
    22.  
    23.         Dim JSONResponse As String = String.Empty
    24.  
    25.         If APIURL Is Nothing OrElse String.IsNullOrEmpty(APIURL) Then
    26.             Throw New ArgumentNullException(NameOf(APIURL), "A valid API URL is required")
    27.         End If
    28.  
    29.         Me.API_URL = APIURL
    30.  
    31.         If APIEndpoint IsNot Nothing AndAlso Not String.IsNullOrEmpty(APIEndpoint) Then
    32.             Dim APIRequest As HttpWebRequest = Nothing
    33.             Dim RequestURL As String = Me.API_URL & APIEndpoint
    34.  
    35.             Try
    36.                 If Not RequestParameters Is Nothing Then
    37.                     If RequestParameters.Count > 0 Then
    38.                         RequestURL = RequestURL & "?"
    39.  
    40.                         For Each Parameter As String In RequestParameters
    41.                             RequestURL = RequestURL & Parameter.ToString & "&"
    42.                         Next Parameter
    43.                     End If
    44.                 End If
    45.  
    46.                 RequestURL = RequestURL.TrimEnd("&"c)
    47.                 APIRequest = WebRequest.Create(RequestURL)
    48.                 ServicePointManager.SecurityProtocol = Protocol
    49.  
    50.                 With APIRequest
    51.                     Dim IPBuffer As IPAddress = Nothing
    52.  
    53.                     If IPAddress.TryParse(APIRequest.RequestUri.Host, IPBuffer) Then
    54.                         If IPBuffer.IsPrivate Then
    55.                             .ServerCertificateValidationCallback = New Security.RemoteCertificateValidationCallback(AddressOf IgnoreCertificateErrorsOnCallback)
    56.                         End If
    57.                     End If
    58.  
    59.                     .Method = Method.GetDescription
    60.                     .ContentType = BodyContentType
    61.                     .Accept = "text/plain, application/json"
    62.                     .PreAuthenticate = True
    63.                     .Headers("Accept-Encoding") = "text/plain, application/json"
    64.                     .Headers("Charset") = "UTF-8"
    65.  
    66.                     If AdditionalHeaders IsNot Nothing Then
    67.                         For I As Integer = 0 To AdditionalHeaders.Count - 1
    68.                             Dim HeaderKey As String = AdditionalHeaders.GetKey(I)
    69.                             Dim HeaderValues As String() = AdditionalHeaders.GetValues(I)
    70.  
    71.                             .Headers(HeaderKey) = String.Join(", ", HeaderValues)
    72.                         Next
    73.                     End If
    74.  
    75.                     If SubmitBody IsNot Nothing Then
    76.                         Dim BodyBytes As Byte() = Nothing
    77.  
    78.                         If TypeOf SubmitBody Is String Then
    79.                             If Not String.IsNullOrEmpty(SubmitBody.ToString) Then
    80.                                 BodyBytes = Text.Encoding.UTF8.GetBytes(SubmitBody.ToString)
    81.                             End If
    82.                         ElseIf TypeOf SubmitBody Is Byte() Then
    83.                             .ContentType = "application/octet-stream"
    84.                             .Accept = "application/octet-stream"
    85.                             BodyBytes = SubmitBody
    86.                         ElseIf TypeOf SubmitBody Is IO.FileInfo Then
    87.                             Dim SubmitFile As IO.FileInfo = CType(SubmitBody, IO.FileInfo)
    88.  
    89.                             Dim ContentMIMEType As String = Utility.MIME.GetMIMETypeFromFile(SubmitFile)
    90.  
    91.                             .ContentType = ContentMIMEType
    92.                             .Accept = ContentMIMEType
    93.  
    94.                             Using FileStream As New IO.FileStream(CType(SubmitBody, IO.FileInfo).FullName, IO.FileMode.Open)
    95.                                 Using APIStream As IO.Stream = APIRequest.GetRequestStream()
    96.                                     FileStream.CopyTo(APIStream)
    97.                                 End Using
    98.                             End Using
    99.                         End If
    100.  
    101.                         If BodyBytes IsNot Nothing Then
    102.                             APIRequest.ContentLength = BodyBytes.Length
    103.  
    104.                             Using APIStream As IO.Stream = APIRequest.GetRequestStream()
    105.                                 APIStream.Write(BodyBytes, 0, BodyBytes.Length)
    106.                                 APIStream.Close()
    107.                             End Using
    108.                         End If
    109.                     End If
    110.                 End With
    111.  
    112.                 Using APIResponse As HttpWebResponse = APIRequest.GetResponse
    113.                     Using APIReader As New IO.StreamReader(APIResponse.GetResponseStream)
    114.                         JSONResponse = APIReader.ReadToEnd
    115.                         APIReader.Close()
    116.                     End Using
    117.                 End Using
    118.             Catch wex As WebException
    119.                 If wex.Message.ToUpper.Contains("UNAUTHORIZED") Then
    120.                     JSONResponse = "NOT AUTHORIZED - " & wex.Message
    121.                 End If
    122.             Finally
    123.                 If APIRequest IsNot Nothing Then
    124.                     APIRequest = Nothing
    125.                 End If
    126.  
    127.                 GC.Collect()
    128.                 GC.WaitForPendingFinalizers()
    129.                 GC.Collect()
    130.             End Try
    131.         Else
    132.             Throw New ArgumentNullException(NameOf(APIEndpoint), "A valid API endpoint is required")
    133.         End If
    134.  
    135.         Return JSONResponse
    136.     End Function
    137.  
    138.     <DebuggerStepThrough>
    139.     Private Function IgnoreCertificateErrorsOnCallback(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
    140.         Return True
    141.     End Function
    142. End Class

    And, an example API-specific class inherited from that base:
    vbnet Code:
    1. Imports System.Web
    2. Imports System.Net
    3. Imports System.Text
    4. Imports System.ComponentModel
    5. Imports Newtonsoft.Json
    6. Imports MyApp.Common
    7. Imports MyApp.Common.JSON
    8.  
    9. Public Class SonicWallAPI
    10.     Inherits APIBase
    11.  
    12.     Public Enum SonicOSVersion
    13.         <Description("https://{0}:{1}/api/sonicos/")> Gen6
    14.         <Description("https://{0}:{1}/api/sonicos/")> Gen7
    15.     End Enum
    16.  
    17.     Private Const SonicOSFTPURI As String = "ftp://{0}:{1}@{2}/"
    18.  
    19.     Private LoggedIn As Boolean = False
    20.     Private APIHeaders As WebHeaderCollection
    21.     Private APIEndpoint As String = String.Empty
    22.     Private JSONResponse As String = String.Empty
    23.  
    24.     Protected Property AuthorizationString As String
    25.  
    26.     Private ReadOnly APIVersion As SonicOSVersion
    27.     Private ReadOnly FTPServer As FileTransferServerSettings = ApplicationSettings.CertifyToolsConfiguration.CertifyTools.FTPServer
    28.     Private ReadOnly PFXCredentials As NetworkCredential
    29.     Private ReadOnly BaseURL As String
    30.  
    31.     Public Sub New(ByVal SonicOSHost As String, ByVal SonicOSPort As Integer, ByVal SonicOSCredentials As NetworkCredential,
    32.                    Optional ByVal Version As SonicOSVersion = SonicOSVersion.Gen6,
    33.                    Optional ByVal PFXCredential As NetworkCredential = Nothing,
    34.                    Optional ByVal FTPSettings As FileTransferServerSettings = Nothing)
    35.         MyBase.New
    36.  
    37.         If Version <> SonicOSVersion.Gen6 AndAlso Version <> SonicOSVersion.Gen7 Then
    38.             Throw New ArgumentException("Invalid API version selected", NameOf(Version))
    39.         End If
    40.  
    41.         Me.LoggedIn = False
    42.         Me.APIVersion = Version
    43.         Me.BaseURL = Me.APIVersion.GetDescription
    44.         Me.API_URL = String.Format(BaseURL, SonicOSHost, SonicOSPort.ToString)
    45.         Me.APIHeaders = New WebHeaderCollection
    46.         Me.FTPServer = FTPSettings
    47.  
    48.         If PFXCredential IsNot Nothing Then
    49.             Me.PFXCredentials = New NetworkCredential(PFXCredential.Username, PFXCredential.Password)
    50.         End If
    51.  
    52.         Me.AuthorizationString = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(SonicOSCredentials.Username + ":" + SonicOSCredentials.Password))
    53.         Me.APIHeaders.Add("Authorization", Me.AuthorizationString)
    54.     End Sub
    55.  
    56.     ''' <summary>
    57.     ''' Log in and create a new session on the SonicWALL appliance
    58.     ''' </summary>
    59.     Public Sub Login()
    60.         Me.APIEndpoint = "auth"
    61.         Me.JSONResponse = SubmitAPIRequest(Me.API_URL, WebMethod.HTTPPOST, Me.APIEndpoint, AdditionalHeaders:=Me.APIHeaders)
    62.  
    63.         If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    64.             Dim Authorization As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    65.  
    66.             If Authorization.Status.Success Then
    67.                 Me.LoggedIn = True
    68.             Else
    69.                 Me.LoggedIn = False
    70.                 Throw New Exception("Login to SonicWALL appliance failed")
    71.             End If
    72.         Else
    73.             Me.LoggedIn = False
    74.             Throw New Exception(Me.JSONResponse)
    75.         End If
    76.     End Sub
    77.  
    78.     ''' <summary>
    79.     ''' Log out of the current session on the SonicWALL appliance
    80.     ''' </summary>
    81.     Public Sub Logout()
    82.         Me.APIEndpoint = "auth"
    83.         Me.JSONResponse = SubmitAPIRequest(Me.API_URL, WebMethod.HTTPDELETE, Me.APIEndpoint, AdditionalHeaders:=Me.APIHeaders)
    84.  
    85.         If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    86.             Dim Authorization As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    87.  
    88.             If Authorization.Status.Success Then
    89.                 Me.LoggedIn = False
    90.             End If
    91.         End If
    92.     End Sub
    93.  
    94.     ''' <summary>
    95.     ''' Import a new SSL certificate from a PFX file provided by the Certificate Authority
    96.     ''' </summary>
    97.     ''' <param name="PFXFile">The PKCS12 file provided by the Certificate Authority containing the SSL certificate to be installed</param>
    98.     ''' <returns></returns>
    99.     Public Function ImportCertificate(ByVal PFXFile As IO.FileInfo) As Boolean
    100.         If Me.LoggedIn Then
    101.             Dim FriendlyName As String = $"SSL Cert Issued {PFXFile.LastWriteTimeUtc.ToString("yyyy-MM-dd")}"
    102.            
    103.             If Me.APIVersion = SonicOSVersion.Gen6 Then
    104.                 Me.APIEndpoint = "certificates/import/cert-key-pair/name/{0}/password/{1}"
    105.             Else
    106.                 Me.APIEndpoint = "import/certificates/cert-key-pair/name/{0}/password/{1}"
    107.             End If
    108.  
    109.             If Me.FTPServer IsNot Nothing AndAlso Me.FTPServer.FTPServerHost IsNot Nothing AndAlso Not String.IsNullOrEmpty(Me.FTPServer.FTPServerHost) Then
    110.                 Dim FTPServerIP As IPAddress = Nothing
    111.  
    112.                 IPAddress.TryParse(Me.FTPServer.FTPServerHost, FTPServerIP)
    113.  
    114.                 If FTPServerIP Is Nothing Then
    115.                     IPAddress.TryParse(Dns.GetHostEntry(FTPServer.FTPServerHost).AddressList(0).ToString, FTPServerIP)
    116.                 End If
    117.  
    118.                 If FTPServerIP IsNot Nothing Then
    119.                     Dim FTPURL As String = String.Format(SonicOSFTPURI,
    120.                                                          Me.FTPServer.FTPUser.Username,
    121.                                                          Me.FTPServer.FTPUser.Password,
    122.                                                          FTPServerIP.ToString) & PFXFile.Name
    123.  
    124.                     Me.APIEndpoint += "/ftp/{2}"
    125.  
    126.                     If Utility.FTP.FTPUpload(Me.FTPServer.FTPServerHost, Me.FTPServer.FTPUser, PFXFile) Then
    127.                         Me.JSONResponse = SubmitAPIRequest(Me.API_URL,
    128.                                                            WebMethod.HTTPPUT,
    129.                                                            String.Format(Me.APIEndpoint,
    130.                                                                          HttpUtility.UrlEncode(FriendlyName),
    131.                                                                          HttpUtility.UrlEncode(Me.PFXCredentials.Password),
    132.                                                                          HttpUtility.UrlEncode(FTPURL)),
    133.                                                            AdditionalHeaders:=Me.APIHeaders)
    134.  
    135.  
    136.                         If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    137.                             Dim APISuccess As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    138.  
    139.                             If APISuccess.Status.Success Then
    140.                                 Return SetActiveSSLCertificate(FriendlyName)
    141.                             End If
    142.                         End If
    143.                     End If
    144.                 End If
    145.             Else
    146.                 Dim MIMEType As String = "application/octet-stream"
    147.  
    148.                 If Me.APIVersion <> SonicOSVersion.Gen6 Then
    149.                     MIMEType = Utility.MIME.GetMIMETypeFromFile(PFXFile)
    150.                 End If
    151.  
    152.                 Me.JSONResponse = SubmitAPIRequest(Me.API_URL,
    153.                                                    WebMethod.HTTPPUT,
    154.                                                    String.Format(Me.APIEndpoint,
    155.                                                                  HttpUtility.UrlEncode(FriendlyName),
    156.                                                                  HttpUtility.UrlEncode(Me.PFXCredentials.Password)),
    157.                                                    SubmitBody:=PFXFile,
    158.                                                    BodyContentType:=MIMEType,
    159.                                                    AdditionalHeaders:=Me.APIHeaders)
    160.                 If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    161.                     Dim APISuccess As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    162.  
    163.                     If APISuccess.Status.Success Then
    164.                         Return SetActiveSSLCertificate(FriendlyName)
    165.                     End If
    166.                 End If
    167.             End If
    168.         Else
    169.             Login()
    170.             Return ImportCertificate(PFXFile)
    171.         End If
    172.  
    173.         Return False
    174.     End Function
    175.  
    176.     ''' <summary>
    177.     ''' Specifies the active SSL certificate for the SonicWALL appliance to use
    178.     ''' </summary>
    179.     ''' <param name="FriendlyName">The Friendly Name of the certificate to set as active</param>
    180.     ''' <returns></returns>
    181.     Private Function SetActiveSSLCertificate(ByVal FriendlyName As String) As Boolean
    182.         If Me.LoggedIn Then
    183.             Dim GlobalSettings As New SonicWALLAdministrationSettings With {
    184.                     .AdminSettingsGroup = New SonicWALLAdministrationSettings.AdminSettings With {
    185.                         .WebManagementConfiguration = New SonicWALLAdministrationSettings.AdminSettings.WebManagementSettings With {
    186.                             .Certificate = New SonicWALLAdministrationSettings.AdminSettings.WebManagementSettings.SSLCertificate With {
    187.                                 .FriendlyName = FriendlyName
    188.                             }
    189.                         }
    190.                     }
    191.                 }
    192.  
    193.             Me.APIEndpoint = "administration/global"
    194.             Me.JSONResponse = SubmitAPIRequest(Me.API_URL,
    195.                                                WebMethod.HTTPPUT,
    196.                                                Me.APIEndpoint,
    197.                                                SubmitBody:=JsonConvert.SerializeObject(GlobalSettings, ApplicationSettings.JSONSettings),
    198.                                                AdditionalHeaders:=Me.APIHeaders)
    199.  
    200.             If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    201.                 Dim APISuccess As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    202.  
    203.                 If APISuccess.Status.Success Then
    204.                     Return CommitPendingChanges()
    205.                 Else
    206.                     Return False
    207.                 End If
    208.             Else
    209.                 Return False
    210.             End If
    211.         Else
    212.             Login()
    213.             Return SetActiveSSLCertificate(FriendlyName)
    214.         End If
    215.     End Function
    216.  
    217.     ''' <summary>
    218.     ''' Commits any pending changes to the SonicWALL appliance's configuration
    219.     ''' </summary>
    220.     ''' <param name="RestartDevice">Whether or not the SonicWALL appliance should be restarted after a successful commit</param>
    221.     ''' <returns></returns>
    222.     Private Function CommitPendingChanges(Optional ByVal RestartDevice As Boolean = False) As Boolean
    223.         If Me.LoggedIn Then
    224.             Me.APIEndpoint = "config/pending"
    225.             Me.JSONResponse = SubmitAPIRequest(Me.API_URL, WebMethod.HTTPPOST, Me.APIEndpoint, AdditionalHeaders:=Me.APIHeaders)
    226.  
    227.             If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    228.                 Dim Authorization As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    229.  
    230.                 Return Authorization.Status.Success
    231.             Else
    232.                 Return False
    233.             End If
    234.         Else
    235.             Login()
    236.             Return CommitPendingChanges(RestartDevice)
    237.         End If
    238.     End Function
    239.  
    240.     ''' <summary>
    241.     ''' Restart the SonicWALL appliance at the specified day/time
    242.     ''' </summary>
    243.     ''' <param name="RestartTime"></param>
    244.     ''' <returns></returns>
    245.     Friend Function ScheduleRestart(ByVal RestartTime As Date) As Boolean
    246.         If Me.LoggedIn Then
    247.             Dim AT_TIME As String = RestartTime.ToString("yyyy:MM:dd:HH:mm:ss")
    248.  
    249.             Me.APIEndpoint = $"restart/at/{AT_TIME}"
    250.             Me.JSONResponse = SubmitAPIRequest(Me.API_URL, WebMethod.HTTPPOST, Me.APIEndpoint, AdditionalHeaders:=Me.APIHeaders)
    251.  
    252.             If Not Me.JSONResponse.StartsWith("NOT AUTHORIZED") Then
    253.                 Dim Authorization As SonicWALLAPIResponse = JsonConvert.DeserializeObject(Of SonicWALLAPIResponse)(Me.JSONResponse)
    254.  
    255.                 Return Authorization.Status.Success
    256.             Else
    257.                 Return False
    258.             End If
    259.         Else
    260.             Login()
    261.             Return ScheduleRestart(RestartTime)
    262.         End If
    263.     End Function
    264. End Class

    And, finally, here is the API-specific response object definition:

    vbnet Code:
    1. Imports Newtonsoft.Json
    2.  
    3. Namespace MyApp.Common.JSON
    4. #Region "STANDARD RESPONSE OBJECT FROM SONICWALL API"
    5.     Public Class SonicWALLAPIResponse
    6.         <JsonProperty("status")>
    7.         Public Property Status As SonicWALLAPIStatus
    8.     End Class
    9.  
    10.     Public Class SonicWALLAPIStatus
    11.         <JsonProperty("success")>
    12.         Public Success As Boolean
    13.  
    14.         <JsonProperty("info")>
    15.         Public Details As List(Of SonicWALLAPIStatusDetail)
    16.     End Class
    17.  
    18.     Public Class SonicWALLAPIStatusDetail
    19.         <JsonProperty("level")>
    20.         Public LogLevel As String
    21.  
    22.         <JsonProperty("code")>
    23.         Public LogCode As String
    24.  
    25.         <JsonProperty("message")>
    26.         Public LogMessage As String
    27.     End Class
    28. #End Region
    29. End Namespace

    I think I've made something fairly solid here, but there are a few things I still want to build in. A couple of examples of where I think it's still lacking:

    • I want to create a generic API response "wrapper" object that can take the API-specific JSON responses and "merge" them into something that can then be passed back to the derived classes and other methods for reading and processing. I stumbled across this bit of code (C#? JavaScript? I'm not sure.) on StackOverflow that seems to be something like I want for this wrapper, but I've yet to actually implement it.

      Code:
      Smth smth = new Smth()
      {
          Something = "dsfdsfdsfs"
      };
      var serializer = new JavaScriptSerializer();
      string json = serializer.Serialize(this.GetResponse(true, smth));
      var response = this.Request.CreateResponse(HttpStatusCode.OK);
      response.Content = new StringContent(json, Encoding.UTF8, "application/json");
      return response;
      Obviously, the Smth class would be my API-specific response object, but I think I'd rather return the fully populated "wrapper" object than an HttpResponseMessage
    • I also want to create a base exception object/handler that can take either an API-specific JSON response object (and all of its children) or simply another exception (or even just that exception's message) and create something that can be used elsewhere for logging or whatever.


    There may be other things I'm missing/overlooking, but this is as far as I've made it so far. Any help, feedback, critiques, and/or suggestions on how to improve this whole mess are definitely welcome and greatly appreciated. Thank you so much for your time.
    Last edited by G_Hosa_Phat; Mar 24th, 2022 at 03:23 PM. Reason: Minor formatting changes and clarification

  2. #2
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,945

    Re: Code Review Request - Feedback/Suggestions Wanted

    A few things I noticed:

    1. There's is no need to give every item in an enumeration a number. Just set the first item to "1" and the rest will be handled automatically.
    2. Look up on string interpolation and System.Text.StringBuilder. Those methods should be used rather than the concatenation I see in your code.

  3. #3

    Thread Starter
    Member G_Hosa_Phat's Avatar
    Join Date
    May 2008
    Location
    Oklahoma City, OK
    Posts
    44

    Re: Code Review Request - Feedback/Suggestions Wanted

    Thank you so much for the feedback! I've taken some elements of this code from some of my older projects when I was still new to a lot of concepts. I've tried to update most of them to use more effective methods, but there are still plenty of opportunities for me to increase my understanding. I'll take a look at some of my string concatenation and see where I can improve things. I truly appreciate the pointers.

  4. #4
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,945

    Re: Code Review Request - Feedback/Suggestions Wanted

    You're welcome. Your code looks better than a lot of code I come across.

    I have two more suggestions:
    1. Enumerations support a data type declaration. ("Enum ... As ...")
    2. Some parts of your code probably could be shortened using the If() ternary operator. (No, it doesn't have the same issues as vb6's IIf() function btw.)

    These go something like:
    Code:
    If .... Then
       Return ...
    Else
      Return ...
    End If
    This probably can be turned into "Return If(..., ..., ...)"

  5. #5

    Thread Starter
    Member G_Hosa_Phat's Avatar
    Join Date
    May 2008
    Location
    Oklahoma City, OK
    Posts
    44

    Re: Code Review Request - Feedback/Suggestions Wanted

    All right, so here's what I take from your feedback:
    1. Since I'm not dealing with extensive enumeration lists in the code above, possibly declare them like "Enum ... As UShort", or something to minimize the memory allocation required. Also, I can probably remove the explicitly defined values I've assigned on both of them.

    2. Look over the string concatenation/interpolation bits. Like I said, I've tried to update things to use more current methods - mostly converting to interpolation as much as possible - but I could easily have overlooked a few bits here and there.

    3. I see your point about using the ternary operator form in some of the If...Then...Else statements. I actually had them broken out that way intentionally simply because I personally feel it makes it a bit easier to read, but I also realize that it can cause some "clutter" for more seasoned developers/programmers.

    I do have to say, though, I really appreciate the compliment. The truth is that I'm entirely self-taught, so I'm kinda "flying by the seat of my pants" on most of this.

  6. #6
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,945

    Re: Code Review Request - Feedback/Suggestions Wanted

    1. Would it be more than a few bytes? Still you could explicitly declare a type just to be thorough. I believe vb defaults to Integer.
    2. Yeah, I know. It's not always easy to stay up to date and to maintain your code.
    3. I like to be thorough but try to avoid overly long code where possible.

    I am self-taught too. :-)
    Last edited by Peter Swinkels; Apr 8th, 2022 at 05:25 AM. Reason: typo

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width