Convert HTML color to OLEHow to simplify these delegate functions?Binary converter and sufficient testsAssigning a value to a class variableConstructing query conditions from answers that may be nullRemoving doubles from a stringRectangle ClassGenerate URLs, Download, extract and add filesCaching an integer - distinguishing no value from zeroUse filename to determine file typeCreate HTML structure dynamically

Chord with lyrics - What does it mean if there is an empty space instead of a Chord?

Do predators tend to have vertical slit pupils versus horizontal for prey animals?

Can my Boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?

Nuclear decay triggers

I think my coworker went through my notebook and took my project ideas

Moons that can't see each other

Land Registry Clause

Repurpose telephone line to ethernet

How to think about joining a company whose business I do not understand?

How could Tony Stark wield the Infinity Nano Gauntlet - at all?

Can I submit a paper under an alias so as to avoid trouble in my country?

Does the Symbiotic Entity damage apply to a creature hit by the secondary damage of Green Flame Blade?

Why do some academic journals requires a separate "summary" paragraph in addition to an abstract?

Designing a prison for a telekinetic race

Could sidesticks be linked?

Can others monetize my project with GPLv3?

Interaction between Ethereal Absolution versus Edgar Markov with Captivating Vampire

Why should someone be willing to write a strong recommendation even if that means losing a undergraduate from their lab?

How can I pack my food so it doesn't smell?

Is "stainless" a bulk or a surface property of stainless steel?

Multicolumn in table not centered

What are the ramifications of this change to upcasting spells?

Why doesn't the Falcon-9 first stage use three legs to land?

"Silverware", "Tableware", and "Dishes"



Convert HTML color to OLE


How to simplify these delegate functions?Binary converter and sufficient testsAssigning a value to a class variableConstructing query conditions from answers that may be nullRemoving doubles from a stringRectangle ClassGenerate URLs, Download, extract and add filesCaching an integer - distinguishing no value from zeroUse filename to determine file typeCreate HTML structure dynamically






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








2












$begingroup$


I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.

However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way.



I know this isn't a big deal but I am curious to see what you guys might suggest for this :)

What do you think is the best possible way to remove this redundancy?



private int GetOleFromHTML(string stringRep)

Color c;
if (string.IsNullOrWhiteSpace(stringRep))

c = Color.FromArgb(224, 224, 224);

else

try

c = ColorTranslator.FromHtml(stringRep);

catch

c = Color.FromArgb(224, 224, 224);



return ColorTranslator.ToOle(c);










share|improve this question











$endgroup$




















    2












    $begingroup$


    I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.

    However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way.



    I know this isn't a big deal but I am curious to see what you guys might suggest for this :)

    What do you think is the best possible way to remove this redundancy?



    private int GetOleFromHTML(string stringRep)

    Color c;
    if (string.IsNullOrWhiteSpace(stringRep))

    c = Color.FromArgb(224, 224, 224);

    else

    try

    c = ColorTranslator.FromHtml(stringRep);

    catch

    c = Color.FromArgb(224, 224, 224);



    return ColorTranslator.ToOle(c);










    share|improve this question











    $endgroup$
















      2












      2








      2





      $begingroup$


      I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.

      However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way.



      I know this isn't a big deal but I am curious to see what you guys might suggest for this :)

      What do you think is the best possible way to remove this redundancy?



      private int GetOleFromHTML(string stringRep)

      Color c;
      if (string.IsNullOrWhiteSpace(stringRep))

      c = Color.FromArgb(224, 224, 224);

      else

      try

      c = ColorTranslator.FromHtml(stringRep);

      catch

      c = Color.FromArgb(224, 224, 224);



      return ColorTranslator.ToOle(c);










      share|improve this question











      $endgroup$




      I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.

      However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way.



      I know this isn't a big deal but I am curious to see what you guys might suggest for this :)

      What do you think is the best possible way to remove this redundancy?



      private int GetOleFromHTML(string stringRep)

      Color c;
      if (string.IsNullOrWhiteSpace(stringRep))

      c = Color.FromArgb(224, 224, 224);

      else

      try

      c = ColorTranslator.FromHtml(stringRep);

      catch

      c = Color.FromArgb(224, 224, 224);



      return ColorTranslator.ToOle(c);







      c# beginner converting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 9 hours ago









      t3chb0t

      37.4k7 gold badges60 silver badges141 bronze badges




      37.4k7 gold badges60 silver badges141 bronze badges










      asked 9 hours ago









      JoeliusJoelius

      1615 bronze badges




      1615 bronze badges























          3 Answers
          3






          active

          oldest

          votes


















          2












          $begingroup$

          Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.



          private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

          private int GetOleFromHTML(string stringRep)

          Color c;
          if (string.IsNullOrWhiteSpace(stringRep))

          c = DefaultColor

          else

          try

          c = ColorTranslator.FromHtml(stringRep);

          catch

          c = DefaultColor



          return ColorTranslator.ToOle(c);



          Another approach would be to directly store the OLE color as int.



          const int DefaultOleColor = 14737632; // R=224, G=224, B=224

          private int GetOleFromHTML(string stringRep)

          if (string.IsNullOrWhiteSpace(stringRep))

          return DefaultOleColor;

          try

          return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

          catch

          return DefaultOleColor;




          Or calculated explicitly:



          const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;


          Or with bit shift operations



          const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.


          These expressions can be used to initialize the constant as they can be fully evaluated at compile time.



          You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).




          Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).



          This variant avoids the repetition by restructuring the code, but still uses a constant.



          const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

          private int GetOleFromHTML(string stringRep)

          if (!String.IsNullOrWhiteSpace(stringRep))

          try

          return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

          catch



          return DefaultOleColor;






          share|improve this answer











          $endgroup$














          • $begingroup$
            This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
            $endgroup$
            – dfhwze
            8 hours ago






          • 1




            $begingroup$
            Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
            $endgroup$
            – Olivier Jacot-Descombes
            8 hours ago











          • $begingroup$
            Ah I was afraid it would be too complex. Thanks for this feedback.
            $endgroup$
            – dfhwze
            8 hours ago


















          2












          $begingroup$

          Another option, though not without caveats, is to reverse the logic. Something like this should work:



          private int GetOleFromHTML(string stringRep)

          Color c = Color.FromArgb(224, 224, 224);
          if (!string.IsNullOrWhiteSpace(stringRep))

          try

          c = ColorTranslator.FromHtml(stringRep);

          catch

          //Use default color value if the string is invalid.



          return ColorTranslator.ToOle(c);






          share|improve this answer











          $endgroup$






















            2












            $begingroup$

            You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:



            • parsing html

            • converting the result into OLE color

            Start with extracting the default value and make it a field:



            static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);


            Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:



            public Color ParseHtmlColorOrDefault(string value, Color defaultColor)

            return
            !string.IsNullOrWhiteSpace(value) && TryParseHtmlColor(value, out var color)
            ? color
            : defaultColor;



            The parsing with its try/catch as the TrySomething pattern:



            private static bool TryParseHtmlColor(string value, out Color color)

            try

            color = ColorTranslator.FromHtml(value);
            return true;

            catch

            color = Color.Empty;
            return false;




            Finally, create an extension for the final step of converting Color to OLE color:



            public static int ToOle(this Color color) => ColorTranslator.ToOle(color);


            Use it like that:



            var oleColor = ParseHtmlColorOrDefault("#FFAABB", DefaultColor).ToOle();





            share|improve this answer









            $endgroup$

















              Your Answer






              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',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              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%2f226427%2fconvert-html-color-to-ole%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2












              $begingroup$

              Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.



              private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

              private int GetOleFromHTML(string stringRep)

              Color c;
              if (string.IsNullOrWhiteSpace(stringRep))

              c = DefaultColor

              else

              try

              c = ColorTranslator.FromHtml(stringRep);

              catch

              c = DefaultColor



              return ColorTranslator.ToOle(c);



              Another approach would be to directly store the OLE color as int.



              const int DefaultOleColor = 14737632; // R=224, G=224, B=224

              private int GetOleFromHTML(string stringRep)

              if (string.IsNullOrWhiteSpace(stringRep))

              return DefaultOleColor;

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch

              return DefaultOleColor;




              Or calculated explicitly:



              const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;


              Or with bit shift operations



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.


              These expressions can be used to initialize the constant as they can be fully evaluated at compile time.



              You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).




              Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).



              This variant avoids the repetition by restructuring the code, but still uses a constant.



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

              private int GetOleFromHTML(string stringRep)

              if (!String.IsNullOrWhiteSpace(stringRep))

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch



              return DefaultOleColor;






              share|improve this answer











              $endgroup$














              • $begingroup$
                This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
                $endgroup$
                – dfhwze
                8 hours ago






              • 1




                $begingroup$
                Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
                $endgroup$
                – Olivier Jacot-Descombes
                8 hours ago











              • $begingroup$
                Ah I was afraid it would be too complex. Thanks for this feedback.
                $endgroup$
                – dfhwze
                8 hours ago















              2












              $begingroup$

              Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.



              private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

              private int GetOleFromHTML(string stringRep)

              Color c;
              if (string.IsNullOrWhiteSpace(stringRep))

              c = DefaultColor

              else

              try

              c = ColorTranslator.FromHtml(stringRep);

              catch

              c = DefaultColor



              return ColorTranslator.ToOle(c);



              Another approach would be to directly store the OLE color as int.



              const int DefaultOleColor = 14737632; // R=224, G=224, B=224

              private int GetOleFromHTML(string stringRep)

              if (string.IsNullOrWhiteSpace(stringRep))

              return DefaultOleColor;

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch

              return DefaultOleColor;




              Or calculated explicitly:



              const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;


              Or with bit shift operations



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.


              These expressions can be used to initialize the constant as they can be fully evaluated at compile time.



              You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).




              Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).



              This variant avoids the repetition by restructuring the code, but still uses a constant.



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

              private int GetOleFromHTML(string stringRep)

              if (!String.IsNullOrWhiteSpace(stringRep))

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch



              return DefaultOleColor;






              share|improve this answer











              $endgroup$














              • $begingroup$
                This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
                $endgroup$
                – dfhwze
                8 hours ago






              • 1




                $begingroup$
                Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
                $endgroup$
                – Olivier Jacot-Descombes
                8 hours ago











              • $begingroup$
                Ah I was afraid it would be too complex. Thanks for this feedback.
                $endgroup$
                – dfhwze
                8 hours ago













              2












              2








              2





              $begingroup$

              Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.



              private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

              private int GetOleFromHTML(string stringRep)

              Color c;
              if (string.IsNullOrWhiteSpace(stringRep))

              c = DefaultColor

              else

              try

              c = ColorTranslator.FromHtml(stringRep);

              catch

              c = DefaultColor



              return ColorTranslator.ToOle(c);



              Another approach would be to directly store the OLE color as int.



              const int DefaultOleColor = 14737632; // R=224, G=224, B=224

              private int GetOleFromHTML(string stringRep)

              if (string.IsNullOrWhiteSpace(stringRep))

              return DefaultOleColor;

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch

              return DefaultOleColor;




              Or calculated explicitly:



              const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;


              Or with bit shift operations



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.


              These expressions can be used to initialize the constant as they can be fully evaluated at compile time.



              You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).




              Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).



              This variant avoids the repetition by restructuring the code, but still uses a constant.



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

              private int GetOleFromHTML(string stringRep)

              if (!String.IsNullOrWhiteSpace(stringRep))

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch



              return DefaultOleColor;






              share|improve this answer











              $endgroup$



              Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly field is what comes closest to a const.



              private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);

              private int GetOleFromHTML(string stringRep)

              Color c;
              if (string.IsNullOrWhiteSpace(stringRep))

              c = DefaultColor

              else

              try

              c = ColorTranslator.FromHtml(stringRep);

              catch

              c = DefaultColor



              return ColorTranslator.ToOle(c);



              Another approach would be to directly store the OLE color as int.



              const int DefaultOleColor = 14737632; // R=224, G=224, B=224

              private int GetOleFromHTML(string stringRep)

              if (string.IsNullOrWhiteSpace(stringRep))

              return DefaultOleColor;

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch

              return DefaultOleColor;




              Or calculated explicitly:



              const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;


              Or with bit shift operations



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.


              These expressions can be used to initialize the constant as they can be fully evaluated at compile time.



              You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))).




              Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).



              This variant avoids the repetition by restructuring the code, but still uses a constant.



              const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;

              private int GetOleFromHTML(string stringRep)

              if (!String.IsNullOrWhiteSpace(stringRep))

              try

              return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));

              catch



              return DefaultOleColor;







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 8 hours ago

























              answered 9 hours ago









              Olivier Jacot-DescombesOlivier Jacot-Descombes

              2,84512 silver badges19 bronze badges




              2,84512 silver badges19 bronze badges














              • $begingroup$
                This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
                $endgroup$
                – dfhwze
                8 hours ago






              • 1




                $begingroup$
                Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
                $endgroup$
                – Olivier Jacot-Descombes
                8 hours ago











              • $begingroup$
                Ah I was afraid it would be too complex. Thanks for this feedback.
                $endgroup$
                – dfhwze
                8 hours ago
















              • $begingroup$
                This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
                $endgroup$
                – dfhwze
                8 hours ago






              • 1




                $begingroup$
                Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
                $endgroup$
                – Olivier Jacot-Descombes
                8 hours ago











              • $begingroup$
                Ah I was afraid it would be too complex. Thanks for this feedback.
                $endgroup$
                – dfhwze
                8 hours ago















              $begingroup$
              This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
              $endgroup$
              – dfhwze
              8 hours ago




              $begingroup$
              This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the catch could somehow be prevented?
              $endgroup$
              – dfhwze
              8 hours ago




              1




              1




              $begingroup$
              Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
              $endgroup$
              – Olivier Jacot-Descombes
              8 hours ago





              $begingroup$
              Here you can see the Reference Source of the ColorTranslator.FromHtml(String) Method. It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle.
              $endgroup$
              – Olivier Jacot-Descombes
              8 hours ago













              $begingroup$
              Ah I was afraid it would be too complex. Thanks for this feedback.
              $endgroup$
              – dfhwze
              8 hours ago




              $begingroup$
              Ah I was afraid it would be too complex. Thanks for this feedback.
              $endgroup$
              – dfhwze
              8 hours ago













              2












              $begingroup$

              Another option, though not without caveats, is to reverse the logic. Something like this should work:



              private int GetOleFromHTML(string stringRep)

              Color c = Color.FromArgb(224, 224, 224);
              if (!string.IsNullOrWhiteSpace(stringRep))

              try

              c = ColorTranslator.FromHtml(stringRep);

              catch

              //Use default color value if the string is invalid.



              return ColorTranslator.ToOle(c);






              share|improve this answer











              $endgroup$



















                2












                $begingroup$

                Another option, though not without caveats, is to reverse the logic. Something like this should work:



                private int GetOleFromHTML(string stringRep)

                Color c = Color.FromArgb(224, 224, 224);
                if (!string.IsNullOrWhiteSpace(stringRep))

                try

                c = ColorTranslator.FromHtml(stringRep);

                catch

                //Use default color value if the string is invalid.



                return ColorTranslator.ToOle(c);






                share|improve this answer











                $endgroup$

















                  2












                  2








                  2





                  $begingroup$

                  Another option, though not without caveats, is to reverse the logic. Something like this should work:



                  private int GetOleFromHTML(string stringRep)

                  Color c = Color.FromArgb(224, 224, 224);
                  if (!string.IsNullOrWhiteSpace(stringRep))

                  try

                  c = ColorTranslator.FromHtml(stringRep);

                  catch

                  //Use default color value if the string is invalid.



                  return ColorTranslator.ToOle(c);






                  share|improve this answer











                  $endgroup$



                  Another option, though not without caveats, is to reverse the logic. Something like this should work:



                  private int GetOleFromHTML(string stringRep)

                  Color c = Color.FromArgb(224, 224, 224);
                  if (!string.IsNullOrWhiteSpace(stringRep))

                  try

                  c = ColorTranslator.FromHtml(stringRep);

                  catch

                  //Use default color value if the string is invalid.



                  return ColorTranslator.ToOle(c);







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 7 hours ago

























                  answered 8 hours ago









                  tinstaafltinstaafl

                  7,4871 gold badge9 silver badges31 bronze badges




                  7,4871 gold badge9 silver badges31 bronze badges
























                      2












                      $begingroup$

                      You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:



                      • parsing html

                      • converting the result into OLE color

                      Start with extracting the default value and make it a field:



                      static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);


                      Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:



                      public Color ParseHtmlColorOrDefault(string value, Color defaultColor)

                      return
                      !string.IsNullOrWhiteSpace(value) && TryParseHtmlColor(value, out var color)
                      ? color
                      : defaultColor;



                      The parsing with its try/catch as the TrySomething pattern:



                      private static bool TryParseHtmlColor(string value, out Color color)

                      try

                      color = ColorTranslator.FromHtml(value);
                      return true;

                      catch

                      color = Color.Empty;
                      return false;




                      Finally, create an extension for the final step of converting Color to OLE color:



                      public static int ToOle(this Color color) => ColorTranslator.ToOle(color);


                      Use it like that:



                      var oleColor = ParseHtmlColorOrDefault("#FFAABB", DefaultColor).ToOle();





                      share|improve this answer









                      $endgroup$



















                        2












                        $begingroup$

                        You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:



                        • parsing html

                        • converting the result into OLE color

                        Start with extracting the default value and make it a field:



                        static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);


                        Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:



                        public Color ParseHtmlColorOrDefault(string value, Color defaultColor)

                        return
                        !string.IsNullOrWhiteSpace(value) && TryParseHtmlColor(value, out var color)
                        ? color
                        : defaultColor;



                        The parsing with its try/catch as the TrySomething pattern:



                        private static bool TryParseHtmlColor(string value, out Color color)

                        try

                        color = ColorTranslator.FromHtml(value);
                        return true;

                        catch

                        color = Color.Empty;
                        return false;




                        Finally, create an extension for the final step of converting Color to OLE color:



                        public static int ToOle(this Color color) => ColorTranslator.ToOle(color);


                        Use it like that:



                        var oleColor = ParseHtmlColorOrDefault("#FFAABB", DefaultColor).ToOle();





                        share|improve this answer









                        $endgroup$

















                          2












                          2








                          2





                          $begingroup$

                          You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:



                          • parsing html

                          • converting the result into OLE color

                          Start with extracting the default value and make it a field:



                          static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);


                          Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:



                          public Color ParseHtmlColorOrDefault(string value, Color defaultColor)

                          return
                          !string.IsNullOrWhiteSpace(value) && TryParseHtmlColor(value, out var color)
                          ? color
                          : defaultColor;



                          The parsing with its try/catch as the TrySomething pattern:



                          private static bool TryParseHtmlColor(string value, out Color color)

                          try

                          color = ColorTranslator.FromHtml(value);
                          return true;

                          catch

                          color = Color.Empty;
                          return false;




                          Finally, create an extension for the final step of converting Color to OLE color:



                          public static int ToOle(this Color color) => ColorTranslator.ToOle(color);


                          Use it like that:



                          var oleColor = ParseHtmlColorOrDefault("#FFAABB", DefaultColor).ToOle();





                          share|improve this answer









                          $endgroup$



                          You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:



                          • parsing html

                          • converting the result into OLE color

                          Start with extracting the default value and make it a field:



                          static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);


                          Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:



                          public Color ParseHtmlColorOrDefault(string value, Color defaultColor)

                          return
                          !string.IsNullOrWhiteSpace(value) && TryParseHtmlColor(value, out var color)
                          ? color
                          : defaultColor;



                          The parsing with its try/catch as the TrySomething pattern:



                          private static bool TryParseHtmlColor(string value, out Color color)

                          try

                          color = ColorTranslator.FromHtml(value);
                          return true;

                          catch

                          color = Color.Empty;
                          return false;




                          Finally, create an extension for the final step of converting Color to OLE color:



                          public static int ToOle(this Color color) => ColorTranslator.ToOle(color);


                          Use it like that:



                          var oleColor = ParseHtmlColorOrDefault("#FFAABB", DefaultColor).ToOle();






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 7 hours ago









                          t3chb0tt3chb0t

                          37.4k7 gold badges60 silver badges141 bronze badges




                          37.4k7 gold badges60 silver badges141 bronze badges






























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226427%2fconvert-html-color-to-ole%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                              Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                              François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480