Showing posts with label Asp.net/C#. Show all posts
Showing posts with label Asp.net/C#. Show all posts

Monday, 2 December 2024

How to Create a Generic Method to Get the Enum Description in C#

        public static SelectList GetSelectListForEnumWithDescription(Type enumType)
        {
            var list = new List<Object>();
            Array enumValues = Enum.GetValues(enumType);
         
            foreach (Enum enumValue in enumValues)
            {
                list.Add(new
                              {
                                 ID = (int)Enum.Parse(enumType, enumValue.ToString()),
                                 Value = GetEnumDescription(enumValue)});
                               }
              return new SelectList(list, "ID", "Value");
        }

        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();
        }
    }

Tuesday, 23 April 2013

How to check all the check box when All check-box is checked and uncheck All check-box, if one of the check-box from the group is unchecked


       
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="Bowler" class="chkGroup">Bowler
<input type="checkbox" name="Batsman" class="chkGroup">Batsman
<input type="checkbox" name="AllRounder" class="chkGroup">AllRounder
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});


Happy Coding!

Blank out a form/ reset a form with jQuery


First method:
<form id="form">
<input type="text" value="Here is some data" id="data" />
<input type="button" value="Clear Input" id="button" />
</form>

$(function(){
 
    $('#button').click(function(){
       $(':input','#form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked,selected');
    });
});

Second method:
function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

Happy Coding!

Monday, 18 February 2013

Center an element on the screen using jQuery



    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

 This is how you use it:  $('#window').center();

The above method will show the control @ center of the Window.

Thursday, 31 January 2013

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.

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);
                }
            });

Monday, 5 November 2012

Issue with the sorting the telerik grid for Asp.net MVC

While working on telerik grid , I found a peculiar issue in Internet Explorer(IE) browsers. The issue is that on the column bound HeaderTemplate if you are providing a link for sorting purpose and if you used a label inside the link then the link will not work in IE but will work for all other browsers.


Solution: So, while providing the link text for sorting the grid on that column, just be care full that u must not used any label for that link. See below:

The code below will  not work:
column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> <label>Name<label> </a>  ---> This will not work
    </text>);



The code below will work:
 column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> Name </a>  ---> This will work.
    </text>);



Enjoy!.......

Friday, 2 November 2012

In MVC4 Telerik grid I got an error that telerik.textbox.js not found in the 'Script\telerik.textbox.js'

This is the tricky one, there is no problem in any where but it is throwing the problem because you might have passed some integer value to the column bound in the telerik grid in mvc3/mvc4.

There are two ways to fix it:

Method 1:

  Download the telerik.textbox.js and put in the specified location and it will work fine.

Note: Don't go for this method, since you are adding some more bytes to the  size of the Cod.

 Method 2:

 Just while binding the int value to the grid just convert it into a string. That's all, now your code will work fine



Enjoy!...

Friday, 26 October 2012

How to Write a Extension method to strip html-tags from a rich text Editor in ASP.Net/ MVC

Today while working with CKEditor , I find out that what ever I provide in the Editor body and saved, it is not properly translating the html tags such as paragraph in the Editor body.

So to fix it I had written an extension method to strip the HTML tags as :


        public static string StripHtml(string inputString)
        {
            if (!string.IsNullOrEmpty(inputString))
                return Regex.Replace(inputString, "<.*?>", string.Empty);

            return string.Empty;

        }


How to call: Classname.StripHtml("some string");

How to Minimize Long Title or Overflowed text with less text followed with ellipsis using Jquery or CSS


While working on a project I got a requirement  of showing a limited amount of text followed with ellipsis(...)  in  a telerik grid, to do it I thought I will use the CSS property  text-overflow: ellipsis; but unable to succeed. I thought a lot and at last done it with CSS.

What I had done with CSS:
So in order to get the text as "Hello Hai how Are..." I used the following CSS

#divContainer td:first-child + td {height: 45px;width:280px;max-width: 280px;overflow: hidden;
text-overflow: ellipsis; display:block;white-space: nowrap;}

Here divContainer is the Container and td:first-child + td  : refers to the second column of a table. InOrder to make it work you need to specify the width,max-width(for IE), white-space and Overflow:hidden and text-overflow: ellipsis;

The output is:
 


 *Note: Here We get the desired result with single line only but I need multiple line with  ellipsis, so to do it I followed JQuery.


What I had done with JQuery:

In order to fix this issue I just write below the two line to get multiple lines followed with ellipsis(...)

$("#divContainer td:first-child + td").each(function() {
            $(this).text($(this).text().substr(0,75)+"...");
        });


The Output is:

Thursday, 17 May 2012

Function to find GCD using Euclidean Algorithm

int GCD(int a, int b)
{
     while (a != 0 && b != 0)
     {
         if (a > b)
            a %= b;
         else
            b %= a;
     }

     if (a == 0)
         return b;
     else
         return a;
}

Thursday, 5 April 2012

Is it possible to make a radio button a required field? or Adding a required field to radio button


 yes, see the example below.

<asp:RadioButtonList runat="server" ID="radio">

                <%--Creaint Items to be display in Radio Button List--%>

                <asp:ListItem Value="0">Male</asp:ListItem>

                <asp:ListItem Value="1">Female</asp:ListItem>

            </asp:RadioButtonList>

            <%--Creating RequiredFieldValidator control to validate RadioButtonList that we have created--%>

            <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  errormessage="Select One option"></asp:RequiredFieldValidator>



Either you can use initialvalue property required filed validator. which is like  

 <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  initialvalue="0" errormessage="Select one option"></asp:RequiredFieldValidator>

For radio buttons:

Radio Buttons do not support the Required Field Validator. You can
either have a button selected by default or employ javascript. Here's a
simple example that forces a user to select either a Male or Female radio
button. There are plenty of variations of this on the Internet if you do a
little digging:

if ( ( document.myForm.gender[0].checked == false ) && (
document.myForm.gender[1].checked == false ) )
{
alert ( "Please select either Male or Female" );
valid = false;
}

Wednesday, 21 March 2012

How to Access the Windows Registry from C#?

Sometimes it may require to develop a application which can able to retrive the information from the Registry.
This can be done using the Registry class and RegisteryKey class. Here is a small Application to get a bit knowledge about it.


By using the Registry and RegistryKey classes in Microsoft.Win32, one can easily access the registry.
The following is a sample that reads a key and displays its value:
using System;
using Microsoft.Win32;
class regTest
{
public static void Main(String[] args)
{
RegistryKey regKey;
Object value;
regKey = Registry.LocalMachine;
regKey =
regKey.OpenSubKey("HARDWAREDESCRIPTIONSystemCentralProcessor ");
value = regKey.GetValue("VendorIdentifier");
Console.WriteLine("The central processor of this machine is: {0}.", value);
}
}

Tuesday, 20 March 2012

How to set master page file at run time

When you are developing a web site using Master and Content page model, you have noticed that after creating your Master page in the web application when you use Wizard to add Content page, it asks you to pick the master page that you would like to associate with this page. And if you choose the option of not selecting a master page, then wizard gives you a standard web form. Then you will have to manually delete markup for body, header etc. to convet it to a content page.
If you do pick the option of selecting a master page, then your content page's declaration at the top looks like the following snippet.

<%@ Page Title="" Language="C#" 
MasterPageFile="~/Themes/Default/ByteBlocks.master" 
AutoEventWireup="true" 
CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

Notice use of MasterPageFile attribute that specifies what master page this content page is associated with. What if you want to switch your master page at run time based on some configuration settings or some use choice. Does this mean you will have to find a way to modify your ASPX file to do. No there is a easier solution to it.
For example in my project I added a drop down in master page to change the theme on the fly. And then PreInit event handler of the page, I set MasterPageFile property of the page object. This is the same attribute that was set at top of the page when we added content page using wizard.

protected override void OnPreInit(EventArgs e)
{
if (Session["theme"] != null)
{
MasterPageFile = 
string.Format("~/Themes/{0}/ByteBlocks.master", Session["theme"]);
}
base.OnPreInit(e);
}

It is very important that you set MasterPageFile property in or before PreInit step of life of ASPX page. Otherwise applicaiton will throw run time exception.
System.InvalidOperationException: The 'MasterPageFile' property can only be set in or before the 'Page_PreInit' event.

Friday, 16 March 2012

Sorting a List of Objects on a particular field.

   public static List<Participant> SortedObjects(IEnumerable<Participant> myList) {
     SortedList<string,Participant> sortedList = new SortedListstringParticipant>();
     foreach (Participant participant in myList) {
         sortedList.Add(participant.RegistrationNo, participant);
     }
     return new List<Participant>(sortedList.Values);
  }

Monday, 12 March 2012

Create a Drop Shadow around Form

public partial class MyCustomForm : Form
{
private static Int32 CS_DROPSHADOW = 0x00020000;

protected override CreateParams CreateParams
{
get
{
CreateParams parameters = base.CreateParams;
parameters.ClassStyle |= CS_DROPSHADOW;

return parameters;
}
}
}

Printing Web Page Controls/Forms Using C# 2.0

Create a web form like below. Put all the controls inside one Panel.

On click event of the “Print Page” button write below code.


//Write the below code for click event of the "Print Page" button

protected void btnPrintPage_Click(object sender,EventArgs e)

{

Session["ctrl"] = Panel1;

Control ctrl = (Control)Session["ctrl"];

PrintWebControl(ctrl);

}

using System.IO;

Create the function PrintWebControl which is calling from the click event of the “Page Print” button.

public static void PrintWebControl(Control ControlToPrint)

{

StringWriter stringWrite = new StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);

if (ControlToPrint is WebControl)

{

Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ControlToPrint).Width = w;

}

Page pg = new Page();

pg.EnableEventValidation = false;

HtmlForm frm = new HtmlForm();

pg.Controls.Add(frm);

frm.Attributes.Add("runat", "server");

frm.Controls.Add(ControlToPrint);

pg.DesignerInitialize();

pg.RenderControl(htmlWrite);

string strHTML = stringWrite.ToString();

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.Write(strHTML);

HttpContext.Current.Response.Write("");

HttpContext.Current.Response.End();

}

Hiding a particular column of a Grid

Some times it is required to hide a particular column or of a grid view or data grid then you can use this function below:
  
public static void HideGridColumn(DataGrid dgParticipantList, string columnName)
{
 GridColumn gridColumn = dgParticipantList.Columns.FindByUniqueNameSafe(columnName);
 if (gridColumn != null)
 {
    gridColumn .Visible = false;
 }
}

Downloading a file from remote server using asp.net

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

Tuesday, 6 March 2012

How to get the Paged GridView row count


var currentCount = (gv.PageIndex - 1) * gv.PageSize + gv.Rows.Count;
  if gv is the grid view