Archive for May, 2015

How to make a CheckBoxList items single select in Asp.Net

Introduction:

In this article I am going to explain how to make a CheckBoxList single select in asp.net

Description:

Usually RadioButtonList is the control which allow the user to select a single selection of items inside it and users will use CheckBoxList control to allow multiple selection of items. However in some cases we need to make the CheckBoxList control a single select one. You can make use of Javascript to achieve this.

The logic here is to attach a Javascript function in onclick event of each items in CheckboxList.

Javascript Function

<script type = "text/javascript">
            function UncheckOthers(objchkbox) {
                //Get the parent control of checkbox which is the checkbox list
                var objchkList = objchkbox.parentNode.parentNode.parentNode;
                //Get the checkbox controls in checkboxlist
                var chkboxControls = objchkList.getElementsByTagName("input");
                //Loop through each check box controls
                for (var i = 0; i < chkboxControls.length; i++) {
                    //Check the current checkbox is not the one user selected
                    if (chkboxControls[i] != objchkbox && objchkbox.checked) {
                        //Uncheck all other checkboxes
                        chkboxControls[i].checked = false;
                    }
                }
            }
</script>

HTML:

 <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Text="FirstValue" Value="1" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Second Value" Value="2" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Third Value" Value="3" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fourth Value" Value="4" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fifth Value" Value="5" onclick="UncheckOthers(this);">
            </asp:ListItem>
</asp:CheckBoxList>

Demo

, , ,

3 Comments

How to find the installed location of svcutil.exe of VisualStudio in your machine

In this article I am going to explain an option to find the installer location of svcutil.exe in each machine. Usually the location of svcutil.exe depends on the Visual Studio installation location and Visual Studio version which you installed. So normally the links which you will find in one machine may or may not work for other machines.

Your best option to get the location of svcutil.exe is to use the VisualStudio Command Prompt and then use the command “where svcutil.exe”

Please follow the below steps for Visual Studio 2010( Mostly the path will be same for other versions of visual studio)

  • Start
  • All Programs
  • Select Microsoft Visual Studio 2010
  • Visual  Studio Tools
  • Visual Studio Command Prompt(2010)

when you select the above option you will get a window like given below and to that you need to type “where svcutil.exe

Press Enter after putting in the command and you will get the details listed out in command prompt.

, ,

2 Comments

How to Crop the Image using CropImage.Net tool in Asp.Net

Introduction:

In this article I am going to explain how to crop an Image using CropImage.Net

Prerequisites:

You can download the dll files needed to use CropImage.Net from this link. Once you have a downloaded the files you need to add the dll files to your solution. You can follow the below steps to add the dlls.

  • Open your Project within the Solution Explorer
  • Right-click the References folder and Choose Add Reference options
  • Find and select the dlls which needs to be added to your solution
    • ImageResizer.dll
    • Imazen.Crop.dll
    • System.Web.Extensions.dll (You may need to use the browse button if you are not finding the dll in available list)
  • Click the Ok button to add it to your Project.

Now you have all the files added to your project

Details of CropImage.Net Control:

CropImage.Net exposes method called Crop, which actually Crops the original image and saves it to the specified path. This method have two overrides one with destinationpath as parameter and another one with destinationpath and appendCorrectExtension.

public void Crop(string destPath);
public void Crop(string destPath, bool appendCorrectExtension)

 Implementation:

Here I am going to explain the steps on how to use CropImage.Net tool to crop the images using Asp.Net.

In this demo I will upload a file and then the uploaded file will be shown in an image control. Then with the help of CropImage control the image will be cropped and shown in another image control called result.

First Step is to register the ImageCrop control in your page like given below

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

Then you need add the below CropImage control to your page and then set it Image property to the Image control from which Image is used to crop.

<ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

Then we use the Crop method to crop and save the image to the destination path provided.

//Save the copy in local folder
CropImage1.Crop(MapPath("~/images"), true);

You also need to add the below configurations to your webconfig file

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" />
    <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </httpModules>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </modules>
  </system.webServer>
</configuration>

Complete Code:

HTML:

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Croping Image using ImageResizer in .Net</h3>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <asp:Image ID="Image1" runat="server" ImageUrl="" />
            

            <ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />
            

            <asp:Button ID="Button1" runat="server" Text="Crop" OnClick="btnCrop_Click" />
            <h3>The result</h3>
            <asp:Image ID="Result" runat="server" Visible="false" />
        </div>
    </form>
</body>
</html>

C#:

protected void btnCrop_Click(object sender, EventArgs e)
    {

        //Show the Result Image control 
        Result.Visible = true;
        //Assign the image url from CropImage control
        Result.ImageUrl = CropImage1.CroppedUrl;

        //Save the copy in local folder
        CropImage1.Crop(MapPath("~/images"), true);

        //You can also get the coordinates from CropImage if you want to show to the user
        this.Title = CropImage1.X + "," + CropImage1.Y + "," + CropImage1.X2 + "," + CropImage1.Y2;

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check if file upload is having any value
        if (FileUpload1.HasFile)
        {
            try
            {
                //Get the uploaded filename from FileUpload Control
                string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                //Save the file to folder
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                //Show the uploaded image in Image Control which is tagged to the Image Cropping Control
                Image1.ImageUrl = "~/images/" + filename;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.ToString());
            }
        }
    }

Note that I have used the folder which is inside in my solution.You can see that in the image given above. If you have a different you need to change the path accordingly.

Demo

, , , , ,

3 Comments

Null Conditional Operator in C# 6.0

Introduction:

In this article I am going to explain about one of the new feature introduced with C# 6.0 – Null Conditional Operator.

Explanation:

Null reference is one of the common exception which normally faced by most of the developers if you didn’t handled by adding proper checking for null values in code.

To resolve this null reference exception till now what we did was to add proper check condition for null values in code like given below

string firstname = null;
//Check if Firstname is null or not 
if(firstname != null)
{
     string res = firstname.Substring(0, 4);
}

Even though above code will works fine, we need to add additional code like if condition and all to safeguard the code from null reference exception. Wouldn’t it be nice if you have a single line of code which actually checks for null condition and the handles it.

With C# 6.0 they introduced a new operator called Null Conditional Operator (?). This will handles the above line of code in a single statement like given below

string firstname = null;
//Handle the null case using the operator(?) this wont throw null reference exception
string res = firstname?.Substring(0, 4);

Internally what the null conditional operator do is it will check for null before calling the following methods and if there is any null value the code execution will won’t proceed further and return the null value which subsequently stop the null reference exception from occurring.

Ex: In below code

string res = firstname?.Substring(0, 4);

Null conditional operator first check for null values in firstname and it will call the following method Substring method only if firstname is not null.

A word of caution while using null conditional operator is that you need to ensure that the variable you are assigning the result will be of nullable type

Ex:

The below code will throw an exception

DataTable dttable = new DataTable();
dttable = null;
int rowcount = dttable?.Rows.Count;

You need to make it nullable using nullableint to resolve the issue

DataTable dttable = new DataTable();
dttable = null;
int? rowcount = dttable?.Rows.Count;

, , , ,

Leave a comment

How to get the selected item value from RadiobuttonList using JQuery

Introduction:

In this article I am going to explain how to get the selected value from RadioButtonList control using JQuery in Asp.Net.

Prerequisites:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Implementation:

Here we will make use of Jquery selectors to get the selected item value and text  from RadioButtonList and then get the value.

To get the selected value

//Get the selected item value from RadioButtonList
var rblSelectedValue = $("#<%= RadioButtonList1.ClientID %> input:checked").val();

To get the selected item text value

//Get the selected item text value from RadioButtonList
var rblSelectedText = $("#<%= RadioButtonList1.ClientID %> input:checked").next().html();

Complete Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //Attach click event to button
            $('#Button1').click(function (e) {
                //Get the selected item value from RadioButtonList
                var rblSelectedValue = $("#<%= RadioButtonList1.ClientID %> input:checked").val();

                $("#<%= lblSelectedValue.ClientID %>").text(rblSelectedValue);

                //Get the selected item text value from RadioButtonList
                var rblSelectedText = $("#<%= RadioButtonList1.ClientID %> input:checked").next().html();

                $("#<%= lblSelectedItem.ClientID %>").text(rblSelectedText);

                //Cancel the postback
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem Value="1" Text="First"></asp:ListItem>
            <asp:ListItem Value="2" Text="Second"></asp:ListItem>
            <asp:ListItem Value="3" Text="Third"></asp:ListItem>
            <asp:ListItem Value="4" Text="Fourth"></asp:ListItem>
            <asp:ListItem Value="5" Text="Fifth"></asp:ListItem>
        </asp:RadioButtonList>
        <asp:Button ID="Button1" runat="server" Text="GetSelectedValue" />


        Selected Value
        <asp:Label ID="lblSelectedValue" runat="server" Text=""></asp:Label>

        Selected Item
        <asp:Label ID="lblSelectedItem" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>

Demo

, , , , ,

1 Comment

Removal of ToolkitScriptManager from latest version of AjaxControlToolkit v15.1

Introduction:

Recently DevExpress team took over the support of AjaxControlToolkit controls and from then on they have introduced nice and good features in AjaxControlToolkit. One such good feature they implemented is the removal of AjaxControlToolkit ToolkitScriptManager.

This change will resolves one of the common issues which most of the developers face when they use AjaxControlToolkit control. Usually as per design AjaxControlToolkit mandates the use of ToolKitScriptManager prior to using any controls. This will cause issues when user have to use asp:ScriptManager for any other controls.

 Solution:

Now with the latest release v15.1 You can use asp:ScriptManger with AjaxControlToolkit controls.

, , , ,

Leave a comment

How to disable Future dates in AjaxControlToolkit CalendarExtender control in ASP.Net

Introduction:

In this article I am going to explain how to disable the Future dates in AjaxControl Toolkit CalendarExtender control.

Prerequisites:

This example needs AjaxControlToolkit’s to be installed in your machine. I have explained the procedure to install AjaxControlToolkit in my previous article.

Implementation

HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
    <form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
        <asp:TextBox ID="txtCalendar" runat="server"></asp:TextBox>
        <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtCalendar"></asp:CalendarExtender>
    </form>
</body>
</html>

C#:

protected void Page_Load(object sender, EventArgs e)
{
      //To Disable the Future Dates in CalendarExtender control
      CalendarExtender1.EndDate = DateTime.Now; 
}

Sample Demo

, , , , ,

Leave a comment