Saturday, June 26, 2010

How to add tool tip for Dropdownlist Item in asp.net

In this post i am going to show you how to add tool tip for dropdownlist item in asp.net.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ToolTip_DropDownList.aspx.cs"
    Inherits="ToolTip_DropDownList" %>

<!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>
        <asp:DropDownList ID="ddlDemo" runat="server">
            <asp:ListItem Text="Asp.net" Value="ASP.NET, the next version of ASP, is a programming framework used to create enterprise-class Web Applications" />
            <asp:ListItem Text="C#" Value="C# (pronounced C-sharp) is an object-oriented programming language from Microsoft" />
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ToolTip_DropDownList: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        //Check it is postback or not.
        if (!IsPostBack)
        {
            BindToolTip(ddlDemo);

        }
    }
    /// <summary>
    /// Use of this function is to bind title attribute
    /// to each element of ListControl.
    /// </summary>
    /// <param name="list"></param>
    private void BindToolTip(ListControl list)
    {
        foreach (ListItem item in list.Items)
        {
            item.Attributes.Add("title", item.Value);

        }
    }
}

See here the {{demo}}

Thursday, June 24, 2010

How to add Ajax activity indicator while calling webservice in asp.net


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryLoader.aspx.cs" Inherits="JqueryLoader" %>

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

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#ajaxStatus").ajaxStart(function() {
                $(this).show();
            }).ajaxStop(function() {

                $(this).hide();
            });
            // Start our ajax request when doAjaxButton is clicked
            $('#AjaxButton').click(function() {
                $.ajax({
                    type: 'POST',
                    url: 'JqueryLoader.aspx/HelloWorld',
                    data: '{}',
                    dataType: 'json',
                    contentType: 'application/json',

                    success: function(json) {
                        // Data processing code.you can process your response
                    $('#response').append('Response Value: ' + json.d);
                    }
                });
            });
        });
    </script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="ajaxStatus" style="display: none; background-color: Red; width: 100px;">
        Loading....</div>
    <div>
    </div>
    <div id="response"></div>
    <input type="button" id="AjaxButton" value="Ajax" />
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JqueryLoader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static string HelloWorld()
    {
        System.Threading.Thread.Sleep(5000);
        return "Hello World";
    }
}

See the {{Demo}}

Wednesday, June 23, 2010

Gridview and Jquery Confirm

In this post i am going to show you how to add pop-up (confirm)  window that ask user to confirm if they want to delete this row or not.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewConfirm.aspx.cs"
    Inherits="GridViewConfirm" %>

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

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            //To remove the row on click on click of the row
            $("#<%=grdStudent.ClientID%> tr").click(function() {
                //Get confirmation from the user
                var answer = confirm('Are you sure you want to delete->' + $(this).find("td:first").html());
                //if answer is true remove the row(here you can remove row from database)
                if (answer) {
                    //Change the backgroupd color while removing the GridView row and fade out feel to the user
                    $(this).css("background-color", "green");
                    $(this).fadeOut(500, function() {
                        $(this).remove();
                    });
                }
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdStudent" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GridViewConfirm: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grdStudent.DataSource = new Student().GetAll();
            grdStudent.DataBind();
          
        }
    }
}
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public List<Student> GetAll()
    {
        List<Student> list = new List<Student>()
        {
            new Student{FirstName="S001",LastName="L01",Age=21},
            new Student{FirstName="S002",LastName="L21",Age=31},
            new Student{FirstName="S003",LastName="L341",Age=51},
            new Student{FirstName="S004",LastName="L021",Age=51},
            new Student{FirstName="S005",LastName="L0231",Age=45},
            new Student{FirstName="S006",LastName="L0231",Age=26},
            new Student{FirstName="S007",LastName="L021",Age=14},
            new Student{FirstName="S008",LastName="L5401",Age=21},
            new Student{FirstName="S009",LastName="L231",Age=21},
            new Student{FirstName="S009",LastName="L0231",Age=21},
            new Student{FirstName="S011",LastName="L0231",Age=21},

        };

        return list;
    }
}
 
 
 
click here to see the  {{Demo}}

Sunday, June 20, 2010

Flash message using Jquery

aspdotnetcodebook


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FlashMessage.aspx.cs" Inherits="FlashMessage" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnInsert").click(function() {
                var name = $("#txtName").val();
                var age = $("#txtAge").val();
                $.ajax(
            {
                type: "POST",
                data: "{'name':'" + name + "',age:'" + age + "'}",
                dataType: "json",
                contentType: "application/json",
                url: "FlashMessage.aspx/InsertEmployee",
                success: function(response) {
                    $("#gridView").html(response.d);
                    $("#message").html("");
                    $("#message").html("Employee inserted successfully!").fadeIn("6000").fadeOut("2000");
                }
            });
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="gridView">
        </div>
        <table class="style1">
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" id="btnInsert" value="Insert" />
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div id="message" style="background-color: #ffaa00; width: 200px; display: none">
                    </div>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class FlashMessage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private static string ConvertControlToHTML(Control source)
    {
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        source.RenderControl(htw);
        return sw.ToString();
    }
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static string InsertEmployee(string name, int age)
    {
        Employee emoloyeeObject = new Employee();
        emoloyeeObject.InsertEmployee(name, age);
        GridView gv = new GridView();
        gv.ShowHeader = true;
        gv.AutoGenerateColumns = true;
        gv.DataSource = HttpContext.Current.Session["emp"];
        gv.DataBind();
        return ConvertControlToHTML(gv);

    }
}

public class Employee
{

    public string Name { get; set; }
    public int Age { get; set; }

    public void InsertEmployee(string name, int age)
    {
         List<Employee> list = new List<Employee>();
         if (HttpContext.Current.Session["emp"] == null)
         {
             list.Add(new Employee() { Name = name, Age = age });
             HttpContext.Current.Session["emp"] = list;
         }
         else
         {
             list = HttpContext.Current.Session["emp"] as List<Employee> ;
             list.Add(new Employee() { Name = name, Age = age });
         }
    }
}


{{Demo}}

jQuery Autocomplete and ASP.NET

In this post i am going to show how to use jquery Autocomplte plugin in asp.net.


aspdotnetcodebook
  • Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new WebSite
  • Right click on new website and add a new class(DummyDAL.cs) in App_Code folder and copy the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Country
{
    public int ID { get; set; }
    public string CountryName { get; set; }


    public System.Collections.Generic.List<Country> GetList()
    {
        System.Collections.Generic.List<Country> list = new System.Collections.Generic.List<Country>()
        {
            new Country(){ID=1,CountryName="Inida"},
            new Country(){ID=1,CountryName="Indonesia"},
            new Country(){ID=2,CountryName="USA"},
            new Country(){ID=3,CountryName="UK"},
            new Country(){ID=4,CountryName="Australia"},
            new Country(){ID=5,CountryName="Newzeland"}

        };
        return list;
    }
}





  •  Right click on website and add new Generic Handler named AutoComplete.ashx and add following code
     
    <%@ WebHandler Language="C#" Class="AutoComplte" %>
    
    using System;
    using System.Web;
    using System.Linq;
    using System.Linq.Expressions;
    
    public class AutoComplete : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            string param = HttpContext.Current.Request.Params["q"];
            Country objCountry = new Country();
            var query = from p in objCountry.GetList()
                        where p.CountryName.ToLower().StartsWith(param.ToLower())
                        select p;
            foreach (var item in query)
            {
                context.Response.Write(item.CountryName + Environment.NewLine);
    
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
    } 
     
    In this last add following code in Default.aspx(in my case autocomplete.aspx)
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoComplete.aspx.cs" Inherits="AutoComplete" %>
    
    <!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>
    
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    
        <script src="Scripts/jquery-autocomplete.js" type="text/javascript"></script>
    
        <style type="text/css">
            .ac_results
            {
                padding: 0px;
                border: 1px solid WindowFrame;
                background-color: Window;
                overflow: hidden;
            }
            .ac_results ul
            {
                width: 100%;
                list-style-position: outside;
                list-style: none;
                padding: 0;
                margin: 0;
            }
            .ac_results iframe
            {
                display: none; /*sorry for IE5*/
                display: /**/ block; /*sorry for IE5*/
                position: absolute;
                top: 0;
                left: 0;
                z-index: -1;
                filter: mask();
                width: 3000px;
                height: 3000px;
            }
            .ac_results li
            {
                margin: 0px;
                padding: 2px 5px;
                cursor: pointer;
                display: block;
                width: 100%;
                font: menu;
                font-size: 12px;
                overflow: hidden;
            }
            .ac_loading
            {
                background: Window url('./indicator.gif') right center no-repeat;
            }
            .ac_over
            {
                background-color: Highlight;
                color: HighlightText;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h3>
                Country</h3>
            <input type="text" id="country" name="country" />
    
            <script>
                $("#country").autocomplete("AutoComplete.ashx");
            </script>
    
        </div>
        </form>
    </body>
    </html>
     
     
     
     
     
    Click here for {{Demo}}

Saturday, June 19, 2010

Photoalbum using ListView and Lightbox jquery plugin

In this post i am going to show you how to create a simple photo album in asp.net using ListView and Jquery Lightbox plugin
aspdotnetcodebook

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script src="Scripts/jquery.lightbox-0.5.js" type="text/javascript"></script>

    <link href="css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />
    <title></title>
    <style type="text/css">
        .productlist li
        {
            dispaly: inline;
            float: left;
            margin-left: 15px;
            margin-bottom: 15px;
        }
        *
        {
            border: 0;
            margin: 0;
            padding: 0;
        }
        body
        {
            background: #fff;
            color: #777;
            padding: 50px;
        }
        #page
        {
            position: relative;
        }
        #images
        {
            float: left;
            width: 600px;
        }
        #details
        {
            color: #000;
        }
        h1
        {
            background: inherit;
            border-bottom: 1px dashed #ccc;
            color: #933;
            font: 32px Georgia, serif;
            font-weight: bold;
            margin: 0 0 20px;
            padding: 0 0 15px;
            text-align: center;
        }
        .gallery
        {
            width: 700px;
            cursor: default;
            list-style: none;
        }
        .gallery img
        {
            background: #fff;
            border-color: #aaa #ccc #ddd #bbb;
            border-style: solid;
            border-width: 1px;
            color: inherit;
            padding: 2px;
            vertical-align: top;
            width: 100px;
            height: 75px;
        }
        .gallery li
        {
            background: #eee;
            border-color: #ddd #bbb #aaa #ccc;
            border-style: solid;
            border-width: 1px;
            color: inherit;
            display: inline;
            float: left;
            margin: 3px;
            padding: 5px;
            position: relative;
        }
    </style>

    <script type="text/javascript">
        $(function() {
            $('#images  a').lightBox({ fixedNavigation: true });

        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <h1>
        Image Gallery</h1>
    <div id="page">
        <div id="images">
            <asp:ListView ID="lvPhotoViewer" runat="server" ItemPlaceholderID="itemContainer">
                <LayoutTemplate>
                    <ul class="gallery">
                        <asp:PlaceHolder ID="itemContainer" runat="server" />
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                    <li><a href='<%# "~"+Eval("ImageUrl") %>' runat="server" id="imgHref">
                        <asp:Image runat="server" ID="imPhoto" Width="150px" Height="150px" ImageUrl='<%# "~"+Eval("ImageUrl") %>' />
                    </a>
                        <br />
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
                    </li>
                </ItemTemplate>
            </asp:ListView>
        </div>
    </div>
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lvPhotoViewer.DataSource = new Photo().GetAll();
        lvPhotoViewer.DataBind();
    }
}
public class Image
{
    public string Name { get; set; }
    public string ImageUrl { get; set; }
    public List<Image> GetAll()
    {
        List<Image> images = new List<Image>()
        {
            new Image(){Name="Creek",ImageUrl="/images/Creek.jpg"},
            new Image(){Name="Dock",ImageUrl="/images/Dock.jpg"},
            new Image(){Name="Forest",ImageUrl="/images/Forest.jpg"},
            new Image(){Name="Garden",ImageUrl="/images/Garden.jpg"},
            new Image(){Name="Creek",ImageUrl="/images/Creek.jpg"},
        };
        return images;

    }


}






{Download }

Monday, June 14, 2010

How to use Schtasks.exe to Schedule Tasks in Windows

This particular code is about a pretty common functionality which I think most of the software engineers face in their projects. Even I came across the same situation many times. Previously I used to achieve the functionality via Window Service, which really worked perfectly. But in this post i am going to achieve the same goal using Window Scheduler.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace ScheduleDemo_CS
{
    class Program
    {
        public static readonly string Constans = "SCHTASKS.exe";
        static void Main(string[] args)
        {
            CreateScheduleTask("MINUTE", 1, "aspdotnetcodebook", @"C:\Windows\System32\notepad.exe");
        }

        public static bool CreateProcess(string strProcessName, string strCommandLineParams)
        {
            // set process parameters and invoke the process
            ProcessStartInfo processInfo = new ProcessStartInfo();
            processInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            processInfo.Arguments = strCommandLineParams;
            processInfo.FileName = strProcessName;
            Process process = Process.Start(processInfo);
            process.WaitForExit();
            if (0 != process.ExitCode)
                return false;
            return true;
        }
        public static bool CreateScheduleTask(string strScheduleType, int intTimeInterval, string strTaskName, string strProgramPath)
        {
            StringBuilder commandLineParams = new StringBuilder();
            commandLineParams.AppendFormat("/Create /RU SYSTEM /SC {0} /MO {1} /TN {2} /TR \"\\\"{3}\\\"", strScheduleType.ToUpper(), intTimeInterval, strTaskName, strProgramPath);
            return CreateProcess(Constans, commandLineParams.ToString());
        }
    }
}