Thursday, 31 January 2013

How to show the content of a Multiselect List in a sorting order using LINQ


Here is the code below to sort the multiselect list box content in sort order.

Here I am getting the states list and binding it to a multi select List Box.
         public static MultiSelectList GetStatesList(bool selected = false)
        {

            List<string> list = new List<string>();
            if (selected)
                list = RetailManager.GetAllStateList();
            return new MultiSelectList(list.OrderBy(s => s));
        }


The trick lies here i.e s=>s does the task. How it is doing is that internally it is comparing s[i] with s[j].

Generate Random Numbers of n length in C# / Asp.net

Sometimes it is required to generate  random numbers of length=n, so in that case the code below will help you to generate. Here by default it will generate random number of size 10 because i had used default value for the length=10 if no value are passed while calling it.


//Method to generate Random Numbers of n length
        public static string GenerateRandomNumbers(int length = 10)
        {
            //Initiate objects & vars 
            byte[ ] seed = Guid.NewGuid().ToByteArray();
            Random random = new Random(BitConverter.ToInt32(seed, 0));
            int randNumber = 0;
            //Loop ‘length’ times to generate a random number or character
            String randomNumber = "";
            for (int i = 0; i < length; i++)
            {
                randNumber = random.Next(48, 58);
               
randomNumber = randomNumber + (char)randNumber;
                //append random char or digit to
randomNumber string

            }
            return
randomNumber ;
        }


How to call the Method:
1)  string randomNumber= GenerateRandomNumbers( ); will generate a  random number of length=10.

2) string randomNumber= GenerateRandomNumbers(5); will generate a  random number of length=5.

 

A simplest way of Encrypting and Decrypting in C#.

Microsoft has provided a simplest way of encoding and decoding of strings  by using the System.Text.Here is the Code below to do Encryption and Decryption.


using System.Text;
For Encryption
 string encryptedString= Convert.ToBase64String(Encoding.Unicode.GetBytes("Text to Encrypt"));

For Decryption
 string decryptedString=Encoding.Unicode.GetString(Convert.FromBase64String("Text to Decrypt"));


How simple is it?

Note:This type of Encryption is not good for encrypting the passwords or credit card or Debit card information's or Online transactions as these are prone to decoding easily and can be hacked. so these are good for sending email in coding format through URL etc.

How to make a group of checkbox behave like a Radio button or toggle button using JQuery

 I got a message from my project manager that the client wants check-box like look rather than radio buttons for Roles(such as Admin, Site Manager) but it need to behave like the radio button. so to do it I had applied below the Jquery snippet to achieve it.

 $('input[name="Roles"]:checkbox').click(function () {
            var group = "input:checkbox[name='" + $(this).attr("name") + "']";
            $(group).attr("checked", false);
            $(this).attr("checked", true);
        });


Note:Here I am showing two check-boxes but you can keep n-numbers of and select only one like the radio button group.

Dynamically adding Controls in the Asp.Net MVC3 / MVC4.

This post is so simple that you can easily understand how to add controls to your view dynamically and delete controls dynamically, i.e. here the controls are created dynamically and are deleted dynamically.

The Above thing can be achieved  in 3 steps:

1. Creating the View.
2. Handling the Click event and creating/deleting the Dynamic Control.
3. Pulling the data from the View to the Controller.


1.Creating the View:

First of all you need to create a view for the Dynamic control Adding.

For Example:
<div>
    <label class="smallFontForAppSelector">Name</label>
    &nbsp;&nbsp;
    <label class="smallFontForAppSelector">
        Degree of Similarity
    </label>
    <label class="smallFontForAppSelector">
        URL/Location
    </label>
    <label class="smallFontForAppSelector">
        Info
    </label>
    <label class="smallFontForAppSelector">
        GUID
    </label>
</div>
<div id='AppSelectorGroup'>
    <div id="AppSelectorBox_1" style="display: block; float: left;">
        <div class="editor-label">@Html.Label("Best Alternative App:")</div>
        <div class="editor-field">
            @Html.TextBox("Name", null, new { id = "textboxName1" })
            &nbsp;&nbsp;
            @Html.DropDownList("Degree", Util.GetSelectListForDegreeOfSimilarity(typeof(DegreeOfSimilarity)),"--Select--", new { id = "ddlDegree1" })
            &nbsp;&nbsp;
             @Html.TextBox("Location", null, new { id = "textboxLocation1" })
            &nbsp;&nbsp;
             @Html.TextBox("Info", null, new { id = "textboxInfo1" })
            &nbsp;&nbsp;
             @Html.TextBox("GUID", null, new { id = "textboxGUID1", @class="deleteAppselector" })
        </div>
    </div>

    <a href="#Add" class="addURL addURLBlack" id="addAppSelector">+</a> <a href="#Delete" class="addURL addURLRed" id="removeAppSelector">-</a>
    <div class="clear-fix"></div>
</div>

Css:

#AppSelectorGroup input {
    width: 140px!important;
}

.smallFontForAppSelector {
    display: block;
    float: left;
    font-size: 12px;
    position: relative;
    text-align: center;
    top: 10px;
    width: 165px;
}

.divinline {
    display: inline;
    float: left;
    width: 1100px;
}



.addURL {
    background-color: #FFF;
    border: 1px solid Gray;
    font-weight: bold;
    cursor: pointer;
    display: block;
    font-size: 15px;
    height: 23px;
    margin-left: 13px;
    margin-top: 10px;
    text-align: center;
    width: 25px;
    float: left;
}

.addURLRed {
    color: red!important;
}

.addURLBlack {
    color: #000 !important;
}

In the Enum Class:
public enum DegreeOfSimilarity
    {
        [Description("Identical")]
        Identical,
        [Description("Knock off")]
        Knockoff,
        [Description("3rd party client")]
        ThirdPartyClient,
        [Description("Functionality similar")]
        FunctionalitySimilar,
        [Description("Competitor's app")]
        CompetitorsApp,
        [Description("Mobile site substitute")]
        Substitute
    }

MY Util Class:

  public static SelectList GetSelectListForDegreeOfSimilarity(Type enumType)
        {
            List<AppDegreeOfSimilarity> appDegreeOfSimilarity = new List<AppDegreeOfSimilarity>();
            var categories = new List<string>(Enum.GetNames(enumType));

            foreach (var item in categories)
            {
                string description = ModelUtil.GetEnumDescription((DegreeOfSimilarity)Enum.Parse(typeof(DegreeOfSimilarity), item));
                appDegreeOfSimilarity.Add(new AppDegreeOfSimilarity() { Name = description, Value = item });     //LocalizationResourceProvider.GetLocalizedString("lbl" + item));
            }
            return new SelectList(appDegreeOfSimilarity, "Value", "Name");
        }


Get the Enum Description:

  public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
Jquery for handling the Click Event and Creating the Dynamic Controls:
   //----------Begin: For Creating App Selector Groups---------------//
        var deleteAppSelectror = $(".deleteAppselector").length;




/* For Adding the Control */
 $("#addAppSelector").click(function () {
     if (deleteAppSelectror == 10) {
                $("#addAppSelector").hide();
                $("#removeAppSelector").show();
                //alert("Only 10 URLs are allowed");
                return false;
            }
            else {
                $("#addAppSelector").show();
                $("#removeAppSelector").show();
            }
     deleteAppSelectror++;
     var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'AppSelectorBox__' + deleteAppSelectror);
              

            newTextBoxDiv.append('<div class="editor-label"><label>Best Alternative App: </label></div>' +
                '<div class="editor-field"><input type="text" name="Name" id="textboxName' + deleteAppSelectror + '" value="" />' + '&nbsp;&nbsp;&nbsp; <select name="Degree" id="ddlDegree' + deleteAppSelectror + '" class="valid"><option value="Identical">Identical</option> <option value="Knockoff">Knock off</option> <option value="ThirdPartyClient">3rd party client</option> <option value="FunctionalitySimilar">Functionality similar</option> <option value="CompetitorsApp">Competitors app</option> <option value="Substitute">Mobile site substitute</option> </select>' +
                '&nbsp;&nbsp;<input type="text" name="Location" id="textboxLocation' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
              '&nbsp;&nbsp;<input type="text" name="Info" id="textboxGUID' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                  '&nbsp;&nbsp;<input type="text" name="GUID" class="deleteAppselector" id="textboxInfo' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                '</div><div class="clear-fix"></div>');

            newTextBoxDiv.appendTo("#AppSelectorGroup");


            if (deleteAppSelectror == 10) {
                 $("#addAppSelector").hide();
                 $("#removeAppSelector").show();

                 return false;
             }
             return true;
         });

/* For Removing the Control */   
     $("#removeAppSelector").click(function () {
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            else {
                $("#removeAppSelector").show();
                $("#addAppSelector").show();
            }

            $('.deleteAppselector').last().parent().parent().remove();
            deleteAppSelectror--;
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            return true;
        });

        //----------End: For Creating App Selector Groups---------------//



Controller: Action Method to Get the Data from View and to do processing
         [HttpPost]
        public ActionResult CreateAppSelector(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info,List<string> guid)
        {
            GetAllBestAltApp(model, name, degree, location, info, guid);
            return CreateAppSelector(model);
        }


 private void GetAllBestAltApp(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info, List<string> guid)
        {
            int count = 0;
            List<BestAlternatives> bestAltApps = new List<BestAlternatives>();
            if (name != null)
            {
                foreach (var n in name)
                {
                    if (n != string.Empty)
                    {
                        BestAlternatives bestAltApp = new BestAlternatives { Name = name[count], DegreeOfSimilarity = degree[count], Location = location[count], Info = info[count], GUID = guid[count] };
                        count++;
                        bestAltApps.Add(bestAltApp);
                    }
                }

                if (bestAltApps.Any())
                {

                    model.AppSelector.BestAlternatives = ModelUtil.SerializeObject(bestAltApps);
                }
                else
                {
                    model.AppSelector.BestAlternatives = null;
                }
            }
            else
                model.AppSelector.BestAlternatives = null;
        }


Result: 





Check All the CheckBox when a "All" Check box is Checked using Jquery

 Sometimes it is required that to do bulk action, you need to select a checkbox so all the check-box corresponding to it get checked. This can be done as below.

Here you can use a ID instead of a class and rather than change you can go for a click event.
 $(".chkAll").live("change", function () {
 if ($(this).is(":checked")) {
                    $(this).siblings(".selectedSchool:checkbox").each(function () {
                        $(this).attr('checked', true);
                    });
                }
                else {
                    $(this).siblings(".selectedSchool:checkbox").each(function () {
                        $(this).attr('checked', false);
                    });
                }
            });


This code is used to check whether the total check-box is equal to the checked check-box or not & change the checked attribute for "All" check-box.

            $(".selectedSchool:checkbox").live("change", function () {

                if ($(".selectedSchool:checkbox:checked").length === 0) {
                    $(".chkAll").attr('checked', false);
                }
                if ($(".selectedSchool:checkbox:checked").length === $(".selectedSchool:checkbox").length) {
                    $(".chkAll").attr('checked', true);
                }
                if ($(".selectedSchool:checkbox:checked").length != $(".selectedSchool:checkbox").length) {
                    $(".chkAll").attr('checked', false);
                }
            });

Tuesday, 22 January 2013

Overflow Scroll Y is not working in IE9 standards


While Working on a project I find out that the overflow-y:scroll doesn't work in IE9
for the Telerik Grid but it is working fine in all other browsers. so in order to fix it I had tried with
position:relative for both the fixed and the scrollable window but unable to succeed
Then after reading some books and googling I find out that by adding meta tags with
content specified will fix the issue.

The simple solution to this is below:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Just put this meta tag inside the head tag of the
.html/.cshtml(Asp.net MVC3/MVC4) /.aspx master page /.jsp file.



Just Enjoy!!!!!!!!

Friday, 11 January 2013

Creating Asynchrous File Uploader in MVC3 with Kendo UI



Asynchronous Upload
View: UploadFile.cshtml
@using Kendo.Mvc.UI
@{
    ViewBag.Title = "UploadFile";
    //Layout = "~/Views/Shared/_PlainLayout.cshtml";
}

<h2>Upload File</h2>

<div style="width:45%">
    @(Html.Kendo().Upload()
          .Name("files")
          .Async(a => a
                          .Save("SaveFiles", "Upload")
                          .Remove("RemoveFiles", "Upload")
                          .AutoUpload(true)
          )
          )
</div>

<script type="text/javascript">
    $(document).ready(function () {
       
        $(".k-dropzone").css("height","100px");

    });
</script>
<script src="~/Scripts/kendo.all.min.js"></script>
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />

Controller:
  public class UploadController : Controller
    {
        public ActionResult UploadFile()
        {
            return View();
        }

        public ActionResult SaveFiles(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                   
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                    // Saving the File
                    file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

        public ActionResult RemoveFiles(string[] fileNames)
        {
           if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    var fileName = Path.GetFileName(fullName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                   

                    if (System.IO.File.Exists(physicalPath))
                    {
                        // Deleting the File from the Location
                         System.IO.File.Delete(physicalPath);
                    }
                }
            }
            return Content("");
        }
    }

Calling to the File Upload Control
$('#Searchwindow').kendoWindow({
        title: "Upload File",
        content: "/Upload/UploadFile",
        height: "400px",
        width: "600px",
        iframe: true,
        visible: false
    }).data('kendoWindow').center();
<div id="grid">
            <div id="Searchwindow"></div>
</div>