Tuesday, January 22, 2013

Cool features in Visual Studio 2012



Microsoft has gifted developer community many cool features with the introduction of the Visual Studio 2012. This article speaks about some of the cool features in Visual Studio 2012.
You need to have Visual Studio installed in your computer to check these cool features. If you do not have it installed and if you do not have license for the same you can download the trial version and can test the new version.
Feature 1: Preview Images
We will first discuss the ability to see preview of the image. To do this I have added a JPG file to my existing project as below:



Now place your mouse on the jpg file added in the project and observe. It shows preview of the image.



Pretty cool feature right!!!
Feature 2: View Multiple Solution Explorers (Copy of Solution Explorer in multiple windows)
Will it not be good if we can have two solution explorers where you can select the project from any one of them and drag the explorers anywhere in the screen? It is a fantastic feature provided by Microsoft to the developers.
Let us see how we can view multiple solution explorers. If you observe we already have one solution explorer opened in the Visual Studio and now if you select another one, it will open a copy of the same explorer in another window.


Now right click on the Solution and you will come up with the following options:

You can now expand the one project in one explorer and work on the files.

You can drag the windows anywhere in the Visual Studio editor. This will be helpful when you are working on complex solutions. You can use the features like Scoping and Filtering with the New Solution Explorer feature that we discussed now.
Feature 3: Filters in the Solution Explorer

In the solution Explorer you will find an icon for filtering the files listed in the solution explorer. There are two features available for filtering.

Filtering options:
1.       Pending Changes Filter
2.       Open Files Filter
Before going to test the filter options we need to add our solution to Team Foundation Server so that we can check-in and check-out the files. Pending Changes Filter is used to list only the files that are newly added or modified and are pending for check-in. I have added a JPG file to the project in the solution explorer. So, when I select the option 1 it should show me only the JPG file.

You see that only one project is selected and only the image file is listed.
Open Files Filter is to show only the files opened in the editor and want to get rid of unopened files in the solution explorer.
In my editor I have opened only 3 files and so when I select the second option it should show only the 3 files that were opened.


Now check the files listed in the Solution Explorer:

Now let us see how multiple explorer features helps in regarding to filtering. I have opened a new solution explorer. In the first explorer I have selected Pending Changes Filter and in the second one I have selected the Open Files filter.

Feature 4: Scoping
Let say if you have a solution explorer with multiple projects with many number of files. If you are working on one of the project, you may not like to see all the projects listed out. In that case, the only option available before Visual Studio 2012 is minimize the Projects tree view. But you cannot get rid of them.
Visual Studio 2012 came up with a feature called Scoping. This feature helps you to scope your solution explorer to show only the project that you are working up on.
In my solution explorer I have two projects listed out as below:

Imagine I am working on the project called “AnotherConsole” and so I would like to scope it to this project.
Right click on the project to scope the solution explorer.

Now you see that only one project is listed out in the solution explorer as below:

You can use multiple solution explorers for one window having scoping enabled and other one filtering enabled as below:

If you want to reset the scope option in the solution explorer select “Home” icon on the top.

We will discuss other cool features in the next article. Hope you all have enjoyed this article. Try using these features for your benefit. Happy coding guys!!!!

Monday, January 14, 2013

Calling JavaScript function from Link Button in ASP.NET


This is a simple article which demonstrates how to use Link Button control of ASP.NET in the web applications. This article explains on how to execute client side functions when the link button is clicked.

Example projects are created using Visual Studio 2008 and the project type created is Web Application.

Purpose: Calling JavaScript function and passing the property value.

Here is my UI code:

I have added a Grid View control of ASP.NET to display a list of products. The columns displayed are Product Name and Description.

To display the Product Name, I have added a Link Button control which has got text value as the Product Name. I have added one custom property called “myCustomID” and setting the property with a value of the Product ID.

Note: You can add as many custom properties in controls and can access them wherever is needed though you will not see when using the Intellisense while defining them.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HyperLinkExample._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">

    <title>Untitled Page</title>


    <script type="text/javascript" src="JS/jquery.js"></script>


    <script type="text/javascript">

$(document).ready(function() {

   jQuery('[id$="LinkProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');;

            alert(customID);

        });

    });


    </script>


</head>

<body>

    <form id="form1" runat="server">

    <div>

<asp:GridView ID="ShowProducts" runat="server" AutoGenerateColumns="false">

            <Columns>

                <asp:TemplateField HeaderText="Product Name">

                    <ItemTemplate>

<asp:LinkButton ID="LinkProducts" runat="server" myCustomID='<%# Eval("ID")%>' Text='<%# Eval("Name")%>'></asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

<asp:BoundField DataField="Description" HeaderText="Description" />

            </Columns>

        </asp:GridView>

    </div>

    </form>

</body>

</html>


In the code behind file, I have added a class called “Product” which has got 3 public properties: ID, Name, and Description.

    public class Product

    {

       public string Name { get; set; }

       public string ID { get; set; }

       public string Description { get; set; }

    }

Now include the name space System.Collection.Generic for using the collections in your example.

using System.Collections.Generic;

Now create a collection of objects of type “Product” and define the property values. In a real-time application, you might get data from the databases.

Add the following code in the Page Load event of the class:

List<Product> ProductList = new List<Product>

            {

new Product(){Name="Product1", ID="1",Description = "Description1"},

new Product(){Name="Product2", ID="2",Description = "Description2"},

new Product(){Name="Product3", ID="3",Description = "Description3"}

            };


            ShowProducts.DataSource = ProductList;

            ShowProducts.DataBind();

The above code initializes a collection object ProductList with 3 Product type data and binds the data to the Grid View.

When you run your application, your browser should be displayed as below:



Now we need to write client side script for Link Button Click event. I am using jQuery in my example. You can download the jQuery from the jQuery website or from the code attachment with this article.

Include the jQuery in the page and then write code for click function. Get the custom property value and display as an alert.

<script type="text/javascript" src="JS/jquery.js"></script>


<script type="text/javascript">

$(document).ready(function() {

   jQuery('[id$="LinkProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');;

            alert(customID);

        });

    });


    </script>


Now click on the hyperlink in your browser and you should see that the javascript function is invoked and an alert with the ID of the Product Name is displayed.



Conclusion:

In real-time applications, the custom property value will be used for other purposes like displaying corresponding client side data for the value or hiding/showing some of the elements and calculating some of the values based on the requirements.

This article is intentionally made short so that if someone searches for this requirement, he/she should be able to get the proper help.

In my next article we would see how to execute server side functions when user clicks the Link Button.

Happy Coding!!!

Calling Server side function from Link Button in ASP.NET


This article explains on how to execute Server side functions when the link button is clicked.

Example projects are created using Visual Studio 2008 and the project type created is Web Application.

Purpose: Calling server side function and passing the property value.

Here is my UI code:

I have added a Grid View control of ASP.NET to display a list of products. The columns displayed are Product Name and Description.

To display the Product Name, I have added a Link Button control which has got text value as the Product Name. I have added one custom property called “myCustomID” and setting the property with a value of the Product ID.

Note: You can add as many custom properties in controls and can access them wherever is needed though you will not see when using the Intellisense while defining them.

I am going to add a div tag to the UI that we used in the previous article “Calling JavaScript function from Link Button in ASP.NET

This is how my UI body looks like:


We can set the value for Command Argument for Link Button which can be accessed on the server side. We can specify the server side method by specifying OnCommand event handler.


<body>

    <form id="form1" runat="server">

    <div>

<asp:GridView ID="ShowProducts" runat="server" AutoGenerateColumns="false">

            <Columns>

                <asp:TemplateField HeaderText="Product Name">

                    <ItemTemplate>

                        <asp:LinkButton

                        ID="LinkProducts"

                        runat="server"

                        CommandArgument='<%#Eval("ID")%>'

                        OnCommand="Product_Command"

                        Text='<%# Eval("Name")%>'></asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

<asp:BoundField DataField="Description" HeaderText="Description" />

            </Columns>

        </asp:GridView>

    </div>

    <div id="displayDetails" runat="server">

    <asp:Label ID="ShowDetails" runat="server"></asp:Label>

    </div>

    </form>

</body>


We are going to use the same server side code with the new methods.

   /// <summary>

        /// Page Load Event

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void Page_Load(object sender, EventArgs e)

        {

            List<Product> ProductList = new List<Product>

            {

new Product(){Name="Product1", ID="1",Description = "Description1"},

new Product(){Name="Product2", ID="2",Description = "Description2"},

new Product(){Name="Product3", ID="3",Description = "Description3"}

            };


            ShowProducts.DataSource = ProductList;

            ShowProducts.DataBind();

        }


        /// <summary>

        /// OnCommand Method for Link Button

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void Product_Command(Object sender, CommandEventArgs e)

        {

            //Get the Product ID from the Command Argument

            String productID = e.CommandArgument.ToString();


            //Call the method to display the selected product ID

            ShowDetailsOfProduct(productID);

        }


        /// <summary>

        /// Show the product id selected

        /// </summary>

        /// <param name="productID"></param>

        protected void ShowDetailsOfProduct(string productID)

        {

            StringBuilder sbreport = new StringBuilder();

sbreport.Append("<table width='95%' border='0' cellpadding='0' cellspacing='0' align='center'>");

            sbreport.Append("<tr class='tdcolbg'>");

            sbreport.Append("<td>");

            sbreport.Append("You have clicked :" + productID);

            sbreport.Append("</td>");

            sbreport.Append("</tr>");

            sbreport.Append("</table>");

            ShowDetails.Text = sbreport.ToString();

        }

Now run the application and check. If you want you can put break point to understand the flow.

When you click on the Product Name Links, it should execute Server side code and display the information in the Label control in the Div tag.






Conclusion:

This article discusses on how to invoke server side code when the Link Button is clicked in the ASPX file.

In my next article we would see how to execute server side function through AJAX and jQuery. In today’s world customers mostly would like to see the application to access the server side code from client code so that the page will not get post back and also, can reduce the performance issues. Since, to get some data from the server and if post back of whole page is not needed it is always a best practice to go for AJAX.

Happy Coding!!!

Sunday, January 13, 2013

List all files in a folder based on file extension


This is a very simple article on how to search and list all the files in a folder based on the file extension provided.  I am here taking an ASP.NET Website example developed using Visual Studio 2008. You can use any version of .NET to work on this example.

I have placed few files in the location C:\Test for this example.



Now create a web site and add a text box control, listbox and a submit button. The textbox takes the file extension to be searched and by default, if no extension is specified “.txt” is taken and searched against the folder.

My ASPX file content looks like below:

<%@ 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">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    Enter Extension of the file to be searched:<asp:TextBox ID="FileExtension" runat="server"></asp:TextBox>

    <br />

    Files List:<br />

    <asp:ListBox ID="FilesList" runat="server"></asp:ListBox>

    <br />

    <br />

    <asp:Button ID="Submit" Text="Search" runat="server"/>

    </div>

    </form>

</body>

</html>


My Code-behind file looks like below:

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.IO;


public partial class _Default : System.Web.UI.Page

{

    /// <summary>

    /// Page Load event code

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void Page_Load(object sender, EventArgs e)

    {

        //Bind the file names to listbox control

        BindFileNamesToList();


        //Event Handler for search button click

        Submit.Click += new EventHandler(Submit_Click);

    }


    /// <summary>

    /// Submit button click functionality

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    void Submit_Click(object sender, EventArgs e)

    {

        //Bind the file names to listbox control

        BindFileNamesToList();

    }


    /// <summary>

    /// Get the files list by searching the files

    /// in the folder with the extension provided.

    /// </summary>

    private void BindFileNamesToList()

    {

        //get the file extension to be searched from the textbox

        string extension = FileExtension.Text;


        //Get the file information from the folder C:\Test based on the extension to be searched.

        //FileInfo class has methods for copying, moving, renaming, creating, opening, deleting,

        //and appending to files.

        FileInfo[] fileInfo = GetFilesFromFolder(@"C:\Test", (extension == "") ? "txt" : extension);


        //Refer http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx for more details.


        //Clear the listbox items before loading.

        FilesList.Items.Clear();


        //Loop thru the fileInfo array object to get each fileInfo object and get the name of the file.

        //Append the filename as a value and text of a listbox

        foreach (FileInfo fileInfoTemp in fileInfo)

        {

            ListItem listItem = new ListItem(fileInfoTemp.Name, fileInfoTemp.Name);

            FilesList.Items.Add(listItem);

        }

    }


    /// <summary>

    /// Method to get the files list

    /// </summary>

    /// <param name="folderName"></param>

    /// <param name="extension"></param>

    /// <returns></returns>

    FileInfo[] GetFilesFromFolder(string folderName, string extension)

    {

        DirectoryInfo directoryInfo = new DirectoryInfo(folderName);


        string internalExtension = string.Concat("*.", extension);


        FileInfo[] fileInfo = directoryInfo.GetFiles(internalExtension, SearchOption.AllDirectories);


        return fileInfo;

    }

}


Now let us run the web site and see how it works:



Since I did not specify any file extension, it takes “.txt” as default. Now let us enter the extension and search.



Search other types.



Hope you liked this article. You can add more search functionalities by providing user to enter other criteria and search the files using FileInfo class.