Parsing XML file from the REST API

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












Please suggest how I can improve my code (like memory leakage, which pattern to use etc.). I have to parse a book XML in two ways: first from an FTP file and second from the REST API. I implemented the methods in one class.



public void GetBooksFromApi(int bookId, int bookNumber = 0)

string ApiBookIDPrefix = ConfigurationManager.AppSettings["ApiBookIDPrefix"].ToString();
string key = ConfigurationManager.AppSettings["BookApiKey"].ToString();
string apiBookIdValue = $"ApiBookIDPrefixbookId";
string restApiBookUrl = $"ApiDownloadUrl?BookID=apiBookIdValue&key=key&bookNumber=bookNumber&limit=1";
string bookName = String.Empty;
string clientFolderPath = String.Empty;
string bookContent = String.Empty;

try
//here to get response, parse xml and creating files process
using (Stream xmlResponseStream = GetRestApiResponse(restApiBookUrl))

IEnumerable<XElement> xmlRecords = ParseBookXml(xmlResponseStream);
if (xmlRecords == null)
throw new NullReferenceException($"No Book found to parse from rest api xml");

foreach (var xmlRecord in xmlRecords)

if (xmlRecord.Element("BookError") == null)

bookName = GetBookName(xmlRecord, bookId);
clientFolderPath = $@"BaseFolderbookId";
bookContent = xmlRecord.ToString();

if (!string.IsNullOrEmpty(bookContent))
CreateFile(clientFolderPath, bookName, bookContent);








catch (Exception ex)

log.Error($"Unable to retrieve Book for bookId.ToString() with URL", ex);
throw ex;




public IEnumerable<XElement> ParseBookXml(Stream response)

IEnumerable<XElement> bookRecords = null;
try


XDocument bookDoc = new XDocument();
bookDoc = XDocument.Load(response);
bookRecords = bookDoc.Root.Elements("bookReport").ToList();

return bookRecords;

catch (Exception ex)

log.Error($"Unable to load XML response from Rest Api Url .", ex);
return bookRecords;





public string GetBookName(XElement bookXmlRecord, int bookId)

string bookName = string.Empty;
string bookNumberString = String.Empty;

string bookNumberVal = bookXmlRecord.Element("bookNumber")?.Value;
DateTime bookDateVal = now(); // today date
bool validBookDate = DateTime.TryParse(bookXmlRecord.Element("BookDate")?.Value, out bookDateVal);

if (!validBookDate)
throw new InvalidCastException($"Unable to parse Book Date from rest api xml");


bookNumberString = GetBookNumberString(int.Parse(bookNumberVal));

bookName = $"Book-bookId.ToString().PadLeft(4, '0')-reportDate:yyyyMMddbookNumberString.xml";

return bookName;



public bool CreateFile(string clientFolder, string fileName, string xmlResponse)

try

string filePath = $@"clientFolderfileName";
if (!Directory.Exists(clientFolder))
Directory.CreateDirectory(clientFolder);

File.WriteAllText(filePath, xmlResponse);
return true;

catch (Exception ex)

log.Error($"Unable to create book in path clientFolder.", ex);
return false;










share|improve this question



























    up vote
    2
    down vote

    favorite












    Please suggest how I can improve my code (like memory leakage, which pattern to use etc.). I have to parse a book XML in two ways: first from an FTP file and second from the REST API. I implemented the methods in one class.



    public void GetBooksFromApi(int bookId, int bookNumber = 0)

    string ApiBookIDPrefix = ConfigurationManager.AppSettings["ApiBookIDPrefix"].ToString();
    string key = ConfigurationManager.AppSettings["BookApiKey"].ToString();
    string apiBookIdValue = $"ApiBookIDPrefixbookId";
    string restApiBookUrl = $"ApiDownloadUrl?BookID=apiBookIdValue&key=key&bookNumber=bookNumber&limit=1";
    string bookName = String.Empty;
    string clientFolderPath = String.Empty;
    string bookContent = String.Empty;

    try
    //here to get response, parse xml and creating files process
    using (Stream xmlResponseStream = GetRestApiResponse(restApiBookUrl))

    IEnumerable<XElement> xmlRecords = ParseBookXml(xmlResponseStream);
    if (xmlRecords == null)
    throw new NullReferenceException($"No Book found to parse from rest api xml");

    foreach (var xmlRecord in xmlRecords)

    if (xmlRecord.Element("BookError") == null)

    bookName = GetBookName(xmlRecord, bookId);
    clientFolderPath = $@"BaseFolderbookId";
    bookContent = xmlRecord.ToString();

    if (!string.IsNullOrEmpty(bookContent))
    CreateFile(clientFolderPath, bookName, bookContent);








    catch (Exception ex)

    log.Error($"Unable to retrieve Book for bookId.ToString() with URL", ex);
    throw ex;




    public IEnumerable<XElement> ParseBookXml(Stream response)

    IEnumerable<XElement> bookRecords = null;
    try


    XDocument bookDoc = new XDocument();
    bookDoc = XDocument.Load(response);
    bookRecords = bookDoc.Root.Elements("bookReport").ToList();

    return bookRecords;

    catch (Exception ex)

    log.Error($"Unable to load XML response from Rest Api Url .", ex);
    return bookRecords;





    public string GetBookName(XElement bookXmlRecord, int bookId)

    string bookName = string.Empty;
    string bookNumberString = String.Empty;

    string bookNumberVal = bookXmlRecord.Element("bookNumber")?.Value;
    DateTime bookDateVal = now(); // today date
    bool validBookDate = DateTime.TryParse(bookXmlRecord.Element("BookDate")?.Value, out bookDateVal);

    if (!validBookDate)
    throw new InvalidCastException($"Unable to parse Book Date from rest api xml");


    bookNumberString = GetBookNumberString(int.Parse(bookNumberVal));

    bookName = $"Book-bookId.ToString().PadLeft(4, '0')-reportDate:yyyyMMddbookNumberString.xml";

    return bookName;



    public bool CreateFile(string clientFolder, string fileName, string xmlResponse)

    try

    string filePath = $@"clientFolderfileName";
    if (!Directory.Exists(clientFolder))
    Directory.CreateDirectory(clientFolder);

    File.WriteAllText(filePath, xmlResponse);
    return true;

    catch (Exception ex)

    log.Error($"Unable to create book in path clientFolder.", ex);
    return false;










    share|improve this question























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      Please suggest how I can improve my code (like memory leakage, which pattern to use etc.). I have to parse a book XML in two ways: first from an FTP file and second from the REST API. I implemented the methods in one class.



      public void GetBooksFromApi(int bookId, int bookNumber = 0)

      string ApiBookIDPrefix = ConfigurationManager.AppSettings["ApiBookIDPrefix"].ToString();
      string key = ConfigurationManager.AppSettings["BookApiKey"].ToString();
      string apiBookIdValue = $"ApiBookIDPrefixbookId";
      string restApiBookUrl = $"ApiDownloadUrl?BookID=apiBookIdValue&key=key&bookNumber=bookNumber&limit=1";
      string bookName = String.Empty;
      string clientFolderPath = String.Empty;
      string bookContent = String.Empty;

      try
      //here to get response, parse xml and creating files process
      using (Stream xmlResponseStream = GetRestApiResponse(restApiBookUrl))

      IEnumerable<XElement> xmlRecords = ParseBookXml(xmlResponseStream);
      if (xmlRecords == null)
      throw new NullReferenceException($"No Book found to parse from rest api xml");

      foreach (var xmlRecord in xmlRecords)

      if (xmlRecord.Element("BookError") == null)

      bookName = GetBookName(xmlRecord, bookId);
      clientFolderPath = $@"BaseFolderbookId";
      bookContent = xmlRecord.ToString();

      if (!string.IsNullOrEmpty(bookContent))
      CreateFile(clientFolderPath, bookName, bookContent);








      catch (Exception ex)

      log.Error($"Unable to retrieve Book for bookId.ToString() with URL", ex);
      throw ex;




      public IEnumerable<XElement> ParseBookXml(Stream response)

      IEnumerable<XElement> bookRecords = null;
      try


      XDocument bookDoc = new XDocument();
      bookDoc = XDocument.Load(response);
      bookRecords = bookDoc.Root.Elements("bookReport").ToList();

      return bookRecords;

      catch (Exception ex)

      log.Error($"Unable to load XML response from Rest Api Url .", ex);
      return bookRecords;





      public string GetBookName(XElement bookXmlRecord, int bookId)

      string bookName = string.Empty;
      string bookNumberString = String.Empty;

      string bookNumberVal = bookXmlRecord.Element("bookNumber")?.Value;
      DateTime bookDateVal = now(); // today date
      bool validBookDate = DateTime.TryParse(bookXmlRecord.Element("BookDate")?.Value, out bookDateVal);

      if (!validBookDate)
      throw new InvalidCastException($"Unable to parse Book Date from rest api xml");


      bookNumberString = GetBookNumberString(int.Parse(bookNumberVal));

      bookName = $"Book-bookId.ToString().PadLeft(4, '0')-reportDate:yyyyMMddbookNumberString.xml";

      return bookName;



      public bool CreateFile(string clientFolder, string fileName, string xmlResponse)

      try

      string filePath = $@"clientFolderfileName";
      if (!Directory.Exists(clientFolder))
      Directory.CreateDirectory(clientFolder);

      File.WriteAllText(filePath, xmlResponse);
      return true;

      catch (Exception ex)

      log.Error($"Unable to create book in path clientFolder.", ex);
      return false;










      share|improve this question













      Please suggest how I can improve my code (like memory leakage, which pattern to use etc.). I have to parse a book XML in two ways: first from an FTP file and second from the REST API. I implemented the methods in one class.



      public void GetBooksFromApi(int bookId, int bookNumber = 0)

      string ApiBookIDPrefix = ConfigurationManager.AppSettings["ApiBookIDPrefix"].ToString();
      string key = ConfigurationManager.AppSettings["BookApiKey"].ToString();
      string apiBookIdValue = $"ApiBookIDPrefixbookId";
      string restApiBookUrl = $"ApiDownloadUrl?BookID=apiBookIdValue&key=key&bookNumber=bookNumber&limit=1";
      string bookName = String.Empty;
      string clientFolderPath = String.Empty;
      string bookContent = String.Empty;

      try
      //here to get response, parse xml and creating files process
      using (Stream xmlResponseStream = GetRestApiResponse(restApiBookUrl))

      IEnumerable<XElement> xmlRecords = ParseBookXml(xmlResponseStream);
      if (xmlRecords == null)
      throw new NullReferenceException($"No Book found to parse from rest api xml");

      foreach (var xmlRecord in xmlRecords)

      if (xmlRecord.Element("BookError") == null)

      bookName = GetBookName(xmlRecord, bookId);
      clientFolderPath = $@"BaseFolderbookId";
      bookContent = xmlRecord.ToString();

      if (!string.IsNullOrEmpty(bookContent))
      CreateFile(clientFolderPath, bookName, bookContent);








      catch (Exception ex)

      log.Error($"Unable to retrieve Book for bookId.ToString() with URL", ex);
      throw ex;




      public IEnumerable<XElement> ParseBookXml(Stream response)

      IEnumerable<XElement> bookRecords = null;
      try


      XDocument bookDoc = new XDocument();
      bookDoc = XDocument.Load(response);
      bookRecords = bookDoc.Root.Elements("bookReport").ToList();

      return bookRecords;

      catch (Exception ex)

      log.Error($"Unable to load XML response from Rest Api Url .", ex);
      return bookRecords;





      public string GetBookName(XElement bookXmlRecord, int bookId)

      string bookName = string.Empty;
      string bookNumberString = String.Empty;

      string bookNumberVal = bookXmlRecord.Element("bookNumber")?.Value;
      DateTime bookDateVal = now(); // today date
      bool validBookDate = DateTime.TryParse(bookXmlRecord.Element("BookDate")?.Value, out bookDateVal);

      if (!validBookDate)
      throw new InvalidCastException($"Unable to parse Book Date from rest api xml");


      bookNumberString = GetBookNumberString(int.Parse(bookNumberVal));

      bookName = $"Book-bookId.ToString().PadLeft(4, '0')-reportDate:yyyyMMddbookNumberString.xml";

      return bookName;



      public bool CreateFile(string clientFolder, string fileName, string xmlResponse)

      try

      string filePath = $@"clientFolderfileName";
      if (!Directory.Exists(clientFolder))
      Directory.CreateDirectory(clientFolder);

      File.WriteAllText(filePath, xmlResponse);
      return true;

      catch (Exception ex)

      log.Error($"Unable to create book in path clientFolder.", ex);
      return false;












      share|improve this question












      share|improve this question




      share|improve this question








      edited Jun 4 at 6:34









      t3chb0t

      31.9k54195




      31.9k54195









      asked Jun 4 at 1:20









      user171148

      111




      111

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f195782%2fparsing-xml-file-from-the-rest-api%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f195782%2fparsing-xml-file-from-the-rest-api%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?