Sunday, 17 February 2013

How to resize a website dynamically as per the window size

Today I got some requirement to re-size the some website that should doesn't have scroll bar and need to adjust dynamically as per the window size.

To do that you need to do it JQuery or CSS. I am posting here how you will do it in JQuery.

Just put this script in the page which you want to adjust its size.

<script type="text/javascript">
    $(document).ready(function () {
        Resize();
    });
    

 $(window).resize(function () { Resize(); location.reload(true); }); // when the window get re-sized
   
    function Resize() {
        var height = window.innerHeight ? window.innerHeight : $(window).height();
        height = height - 96; // Height of the Logo and the Footer is 96px so it is deducted.
        $("#leftNav").height(height);
    }
</script>


Here i am concerned about the height. I you want to resize with width also you can use $(window).width().

Note: Be cautious if you are still want to work the code in IE7 the do remember the following things, you need to deduct the view port


    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 7) {
            viewportHeight -= 3;
        }
    }

    if($('#leftNav').height() > viewportHeight) {
        $('#leftNav').height($('#leftNav').height() - viewportHeight);
    }

    if($('#leftNav').height() < viewportHeight) {
        $('#leftNav').height(viewportHeight - $('#leftNav').height());
    }
 

Friday, 1 February 2013

How to get all the Emails as Comma separatesd string in Sql Server.

SQL Server provides a function named Coalesce to do the task to join all the column value by comma separated string.

The Query is below:
Go
Declare @strEmail varchar(max)

SELECT @strEmail=coalesce(@strEmail+',','')+[Email]
       FROM Users      
print @strEmail  

Images are not updating in the IE on updating the Image file in websites using asp.net

This is a situation that occurs to each and every web developer who is developing the website.
Being a web developer using Microsoft .Net Framework i found this issue almost every next user it has. So, there are lot of solutions to this problem but I had found one of them is to be a very fine for the website  I am developing.


These are Some of the solutions that peoples nearby told me and some I find out in googling.

1) You need to remove the cache while updating the record, so the previous image is removed from the cache.

2)Force loading the web-page once image  is updated.

3) Load the image asynchronously only as per the current time.

However I like the last solution, i.e. is as below:

solution:
<img alt="Image" id="imgApp" src="@Url.Content("~/Images/Thumbnails/Apps/" + Model.App.ID + ".png?version=" + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture))"

I had done this thing in mvc3 but you can do it any language.

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!!!!!!!!