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")


                                        

MVC4 Validation (Client Side) using Ajax



Requirement: Validate the input by the user on client side.




Solution:
In the web.config check if the namespace is there, if not add it
<add namespace="System.Web.Mvc.Ajax" />

In the View add the following:
@section Scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}



Add the “validationMessageFor” Html Helper like this-
<table width="100%">
  <tr>
    <td> 
      <div>First Name</div>                                                              
      <div>@Html.EditorFor(model =>  @item.FName)</div>
           @Html.ValidationMessageFor(model => @item.FName)
                                 
                                                                                   
                                          
      <div>Last Name</div>
      <div>@Html.EditorFor(model => @contact.LName)</div>
           @Html.ValidationMessageFor(model => @contact.LName)
     </td>
    </tr>                                                                                              
    <tr>
      <td><input type="submit" title="Save" /></td>
    </tr>
  </table>

In the Model:
[Required( ErrorMessage = "First Name is required.") ]
  public String FName { get; set; }

[Required]
   public String LName { get; set; }

[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                   @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                   ErrorMessage = "Email is not valid")]
   public String Email { get; set; }

//other way of using Email data annotation
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
   public String OtherEmail { get; set; }

      
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Please enter proper phone
                   number.")]                   
   public String Mobile { get; set; }


[RegularExpression(@"^(\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1}
                   *\d{1}[A-Z]{1}\d{1})$", ErrorMessage = "Invalid Zip")]           
   public String Postal { get; set; }

      

LINQ to display list of values separated by a comma



Requirement: We need to display data as a single row of values separated by commas.

Solution:
   Object obj = new Object();

var dbquery = (from g in db.table1
               join gc in db.table2
               on g.id equals gc.id
               where g.prop1 == value1 && gc.prop2 == value2
               select g);

          if (dbquery!= null && dbquery.Count() > 0)
            {
         // Gets all the groups/tags the lead belongs to and joins them with a ','
                obj.PropName=string.Join(",",dbquery.Select(x=>                                                x.propName)); 
           

            }

Formatting DateTime type to display just the date in C#

                     Formatting DateTime type to display just the date.

Requirement: To display just the date using the object of DateTime type.

Solution: Declare a string type variable to hold the date.

                   public String NextDate { get; set; }

             
        NextDate = string.Format("{0:MM/dd/yyyy}", DateTimeVariableToBeFormatted)


It will let you display the DateTime format of “4/30/2014 12:00:00 AM” type to

Date format “04/30/2014”

Jquery DatePicker in MVC4

Jquery DatePicker in MVC4 (Displaying the calendar and capturing the selected value to save it)

Requirement:
Show the date on in a view and this display should allow user to set a new date using a calendar. The calendar should show on the click of the textbox where the date is displayed.



Solution:
For the view
In the _Layout.cshtml(which resides in the Shared folder under Views) ,define
@RenderSection("scripts", required: false)

In the view where the datepicker is defined, use the follwing jQuery code

@section scripts{
 <script type="text/javascript">
     $(function () {
         $("#txtNewDate").datepicker({
             onSelect: function (date) { $("#_newDate").val(date) }

         });
     });
</script>


To format the styling (size, font etc) of the ui-datepicker, include the following code:

<style type="text/css">
    .ui-datepicker {
        font-family:Garamond;
        font-size: 12px;
        margin-left:10px
     }
 </style>



In the form tag, define a hidden field to capture the new date, also get the current date value from the database

@using (@Html.BeginForm())
{
       <input type="hidden" id="_newDate" name="_ newDate "/> 


<div>

                            <div>Date:</div><div ><input style="width:5em;height:2em; " type="text" id=" txtNewDate "  value="@Html.Raw(Model.NextCall)"/></div>
                            </div>
<div>
                               <div><input type="submit" style="height:2em" value="save" name="save" title="Save" id="btnSave" /></div>                              
                            </div>

}

For the Controller:

In the POST action method , use formCollection
[HttpPost]
[ActionName("details")]
 public ActionResult details_Post(int id, FormCollection form)
        {
//define a datetime variable
DateTime Nxtdate = DateTime.MinValue;

if (form["_newDate "] != "")
            {
               //convert the form variable containing date to datetime type
 Nxtdate = Convert.ToDateTime(form["_newDate "]);
            }


if (ModelState.IsValid)
            {
                //call method to update the date
                Repository.SaveDate(Nxtdate);

             
            }
Return view();


}




For the Repository(Model):
Saving the NewDate

  public static void SaveDate(DateTime NxtCall, int Id)
        {

            try
            {
                   //open the connection
                    using (SWSData db = new ef.SWSData())
                    {
                        //get the row to be updated
                        var dbDate = db.Date.SingleOrDefault(ld => ld.id == Id);

                        if ( dbDate != null)
                        {
                            if (NxtCall != DateTime.MinValue)
                            {
                                dbDate.CallDate = NxtCall;
                            }
                           
                       }

                        //if the data does not exist already, insert a new record for the same.
                        else
                        {
                            Date ld = new Date()
                            {
                                CallDate = NxtCall,
                               
                            };

                            db.AddToDate(ld);

                           
                        }
                        //save changes to database
                        db.SaveChanges();
                    }
               
            }

            catch (Exception ex)
            {

                if (HttpContext.Current.IsDebuggingEnabled)
                {

                    throw ex;
                }
            }

        }


Thursday, April 17, 2014

Sliding checkbox for MVC4

Sliding checkbox for MVC4

Requirement:

Show the checkbox as a slider and allow user to check or uncheck the option, save the updation in the database.




Solution:

For the CSS:
.checkSwitch {
       position: relative;
       margin: 4px 0 0 2px;
       width: 70px;
       height: 21px;
       border-radius: 3px;
       box-shadow: 0 0 0 1px rgba(0,0,0,0.3), 0 1px 0 1px rgba(255,255,255,0.3);
       cursor: pointer;
       overflow: hidden;
       display: inline-block;
       background: #e9e9e9;
}

.checkSwitch:hover {
      
}

.checkSwitch input {
       position: absolute;
       z-index: -1;
       opacity: 0;
       margin: 0;
       padding: 0;
       width: 100%;
       height: 100%;
}

.checkSwitchInner {
       position: absolute;
       top: 0;
       left: -45px;
       width: 115px;
       height: 100%;
       -webkit-transition: all .2s ease;
       -moz-transition: all .2s ease;
       -o-transition: all .2s ease;
       transition: all .2s ease;
}

.checkSwitch.on .checkSwitchInner {
       left: 0;
}

.checkSwitchOn, .checkSwitchOff, .checkSwitchHandle {
       width: 45px;
       height: 100%;
       font-family: Arial, Tahoma, sans-serif;
       font-size: 12px;
       text-align: center;
       line-height: 22px;
       font-weight: 100;
       color: #ffffff;
       text-shadow: -1px -1px 0 rgba(0,0,0,0.15);
       float: left;
}

.checkSwitchOn, .checkSwitchOff {
       box-shadow: inset 0 0 10px rgba(0,0,0,0.1);
}

.checkSwitchOn {
       position: relative;
       border-radius: 2px 0 0 2px;
       background: #4CA1FF;
}

.checkSwitchOff {
       position: relative;
       border-radius: 0 2px 2px 0;
       background: #aaaaaa;
}

.checkSwitchHandle {
       position: relative;
       width: 25px;
       font-size: 16px;
       line-height: 23px;
       font-weight: 100;
       color: #4b4b4b;
       text-shadow: none;
       border-radius: 3px;
       box-shadow: inset 0 -16px 20px -10px rgba(0,0,0,0.12);
       background: #ffffff url('drag_handle.png') center 6px no-repeat;
}




For the JQuery:
function checkSwitch()
{
       $('input.checkSwitch').each(function() {

              if($(this).attr('checked') == 'checked'){
                     $(this).wrap('<div class="checkSwitch on" />');
              } else {
                     $(this).wrap('<div class="checkSwitch off" />');
              }

              $(this).parent('div.checkSwitch').each(function() {
                     $(this).append('<div class="checkSwitchInner"><div class="checkSwitchOn"></div><div class="checkSwitchHandle"></div><div class="checkSwitchOff"></div></div>');
              });

       });
}

$(document).on('click', 'div.checkSwitch', function() {

       var $this = $(this);

       if($this.hasClass('off')){
              $this.addClass('on');
              $this.removeClass('off');
              $this.children('input.checkSwitch').attr('checked', 'checked');
       } else if($this.hasClass('on')){
              $this.addClass('off');
              $this.removeClass('on');
              $this.children('input.checkSwitch').removeAttr('checked');
       }


});


The code for the CSS and Jquery has been taken from http://labs.lukepeters.me/iphone-checkbox-switch/


In the View:

insert the checkSwitch();  function after the checkbox has been rendered,

@section JavaScript{
<script type="text/javascript" src="../../Scripts/checkswitch.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
         checkSwitch();
     });

    </script>
}

This is how the Checkbox is used,
Here HtmlHelper for checkbox is used with the first argument taking the (string)name attribute, second argument taking the (bool) isChecked attribute, third argument is the class name for our css.
         
@using(Html.BeginForm("ActionMethod","Controller",FormMethod.Post,new{id="grpForm"}))
{
    <div>
 <div>@Html.CheckBox(group.GroupName + "_" + group.Id.ToString(), group.IsSelected, new { @class = "checkSwitch"})</div>                                                
                                </div>

}



In the Model:

//model for selection
    public class Selection
    {
        public int Id { get; set; }
        public String SelectionName { get; set; }

        //Boolean value to select a checkbox on the list
        public bool IsSelected { get; set; }

        public Selection ()
        {
            this.Id = 0;
            this. SelectionName = String.Empty;
        }
    }




The method to get all the selections and showing which of them is checked/                                                                                                                                                                                                                                                                                                                                                                   unchecked
This is also a part of the model
public static List<Selection> GetAvailableSelections()
{
                           var dbExists = your linq query to get the record for     each option

                            if (dbExists != null)
                            {
                                avlgrp.IsSelected = true;
                            }
                            else
                            {
                                avlgrp.IsSelected = false;
                            }                         
                        }


For saving the Selections

  public static void SaveSelections(List<int> groupIdT, List<int> groupIdF,int leadid)
        {

            try
            {
                //for updating the current selection of tags/groups
                foreach (var gid in groupIdT)
               {
                   
                    //open the connection
                    using (SWSData db = new ef.SWSData())
                    {
                        //get the row to be updated
                        var dbGroup = db.Selections.SingleOrDefault(ld => ld.LeadId == leadid && ld.groupid == gid);

                        if (dbGroup != null)
                        {

                        }
                       
                        //if the selection does not exist already, insert a new record for the same.
                        else
                        {
                             Selection gc = new Selection()
                            {
                                groupid = gid,
                               LeadId = leadid
                              
                            };

                            db.AddToSelections(gc);

                            //save changes to database
                            db.SaveChanges();
                        }
                    }
                }

                //for deleting unselected selections from the database
                foreach (var gid in groupIdF)
                {

                   //open the connection
                    using (SWSData db = new ef.SWSData())
                    {
                        //get the row to be updated
                        var dbGroup = db.Selections.SingleOrDefault(ld => ld.LeadId == leadid && ld.groupid == gid);

                        if (dbGroup != null)
                        {
                            db.DeleteObject(dbGroup);
                            //save the changes to the database.
                            db.SaveChanges();
                        }
                    
                    }
                }

            }

            catch (Exception ex)
            {

                if (HttpContext.Current.IsDebuggingEnabled)
                {

                    throw ex;
                }
            }

        }





For the Controller:

[HttpPost]
[ActionName("Selection")]
        public ActionResult Selection_Post(int id, FormCollection form)
        {
            try
            {
               List<int> GrpIdsT = new List<int>();
               List<int> GrpIdsF = new List<int>();
               int gidt, gidf = 0;

               //loop through the form collection
                foreach (string key in form.Keys)
                {
                   //If the Selection is checked then add the selectionid to the list-GrpIdsT
                    bool isCheckedT = form[key].Contains("true");
                    if (isCheckedT)
                    {
//split the key on ‘_’                       
string[] st = key.Split('_');
                        gidt = Convert.ToInt32(st[1]);

                        GrpIdsT.Add(gidt);
                    }

                    //If the group is unchecked then add the selectionid to the list-GrpIdsF
                    else
                    {
                        string[] st = key.Split('_');
                        gidf = Convert.ToInt32(st[1]);

                        GrpIdsF.Add(gidf);
                    }
                }
              

                //save list of selections
                Repository.SaveSelections(GrpIdsT, GrpIdsF, id);

                   Return View();
  }
            catch (Exception ex)
            {

                ViewBag.ErrorMessage = "ERROR:" + ex.Message;
                return View("Error");
            }

}