Monday, April 21, 2014

Implementing bit masking in C#



Requirement: Check the verified fields in contact and unverified fields should remain unchecked. Store the values as flags in a database table column.



Solution: Use bit-masking and store each flag as a bit in the 16-bit table column.

In Model: Define bool properties for each flag.
       
Public class details
{
   public bool EmailChked { get; set; }
   public bool OtherEmailChked { get; set; }
   public bool MobileChked { get; set; }
   public bool OtherMobilechked { get; set; }


 public details()
 {
   this.EmailChked = false;
   this.OtherEmailChked = false;
   this.MobileChked = false;
   this.OtherMobilechked = false;

 }

}


In your FillData method in repository(model)

After getting the value from the database table column compare and set:

if ((value & 1) > 0 )
        {
           ld.EmailChked = true;
         }

if ((value & 2) > 0)
         {
            ld.MobileChked = true;
         }
if ((value & 4) > 0)
         {
            ld.OtherMobilechked = true;
         }
if ((value & 8) > 0)
         {
            ld.OtherEmailChked = true;
         }





To save the flag status updation, in controller, in the POST action method
Use FormCollection and get the checked/unchecked status(to see how to get the checked/unchecked status from view to Controller, scroll down) and then pass the status to the save method.

Int16 status = 0;
            if (form["ChkEmail"].Contains("true"))
            {
                status |= 1;
            }
            else
            {
                status &= ~1;
            }

            if (form["ChkOtherEmail"].Contains("true"))
            {
                status |= 8;
            }
            else
            {
                status &= ~8;
            }

            if (form["ChkMobile"].Contains("true"))
            {
                status |= 2;
            }
            else
            {
                status &= ~2;
            }

            if (form["ChkOtherMobile"].Contains("true"))
            {
                status |= 4;
            }
            else
            {
                status &= ~4;
            }

         if (ModelState.IsValid)
            {           
                    Repository.VerificationStatus(status, id);
                     }





How to get the checked/unchecked status from view to Controller:

Use the checkbox’s string “name” and bool “IsChecked” parameters

<div>@Html.CheckBox("ChEmail", Model.OtherEmailChked)</div>
<div>@Html.CheckBox("ChOtherEmail", Model.OtherEmailChked)</div>
<div>@Html.CheckBox("ChMobile", Model.MobileChked)</div>
<div>@Html.CheckBox("ChOtherMobile ", Model.OtherMobileChked)</div>

When the FormCollection is passed to the controller each checkbox’s status can be known using:  form["keyName"].Contains("true")


                                        

No comments:

Post a Comment