December 2008 - Posts

Visual Studio .NET 2005 Keyboard Shortcuts

Visual Studio 2005 is a great IDE to develop .NET applications. But If we don't know the keyboard shortcut for some function we have to do it with mouse and it will take lots of time.


I have found a great link which contains almost all the short cut for keyboards.


Here is the link for that article...

http://www.codinghorror.com/blog/files/Visual%20Studio%20.NET%202005%20Keyboard%20Shortcuts.htm

Posted by bmdayal | with no comments

ASP.NET Custom Paging with GridView using ObjectDataSource

Paging is perhaps one of the most required in data presentation, specially when it comes to huge amount of data, normal paging becomes nightmare. If you are developing your application using ASP.NET 2.0, then you can make use of ObjectDataSource in a very efficient manner to achieve paging.

The code which I am providing below will give you a complete understanding of how you can do this, this technique will fetch one the number of data which you set in PageSIze of GridView from the DataBase, instead of fetching entire data and on every PageIndexChanged event repeating the full cycle again,

First you need to either modify or write your procedure the input and output parameters which will fit into your .NET code to get the paging.

create procedure proc_EmployeeDetails
    @empId int,
    @empStatus varchar(10),
    @pagestart int = null,
    @pagesize int = null,
    @numresults int output
as

create table #empresults
(
    [rowid] [int] IDENTITY (1, 1) NOT NULL,
    [empID] [nchar] (5) ,
    [EmpName] [nvarchar] (30),
    [Address] [varchar] (200),
    [DOB] [datetime],
    [Age] [int],
)


insert into #empresults (empid, empname, address, DOB, Age) 
select empID, EmpName, Address, DOB, Age
where
    empid = @empId    AND empStatus = @empStatus
order by EmpName

set @numresults = @@rowcount 

if @pagesize is null
    set @pagesize = @numresults

if @pagestart is null
    set @pagestart = 1

set rowcount @pagesize

select * 
from #empresults
where rowid >= @pagestart

drop table #tempresults

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Next I create a Employee class which will hold the results from the database.

public class EmployeeCollection : IList<Employee> { }

public class Employee
{
    private int _empId;
    private string _empName;
    private DateTime? _DOB;
    private int _age;
    private string _address;

    public Employee() { }

    public int EmployeeId
    {
        get { return _empId; }
        set { _empId = value; }
    }

    public string EmployeeName
    {
        get { return _empName; }
        set { _empName = value; }
    }

    public DateTime? DOB
    {
        get { return _DOB; }
        set { _DOB = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public string Address
    {
        get { return _address; }
        set { _address = value; }
    }
   
}

Now as we have got the BusinessObjects, it time to create a class specifically designed to handle request from ObjectDataSource. This class you can keep in your app_code directory of web project and is used like facade layer between UI layer and Business Layer.

Excuses for the code formatting, but you got the idea what I mean to say, right ?

public class EmployeeDataSource
{
    public EmployeeDataSource() { }

    public int SelectCount(int empId, string employeeStatus, ObjectDataSourceSelectingEventArgs e)
    {
        return e.Arguments.TotalRowCount;
    }

    public EmployeeCollection Select(int empId, string employeeStatus, int maximumRows, int startRowIndex, ObjectDataSourceSelectingEventArgs e)
    {
        using (SqlConnection connection = new SqlConnection("Initial Catalog=Employee;Integrated Security=SSPI;Data Source=."))
        using (SqlCommand command = new SqlCommand("proc_EmployeeDetails", connection))
        {
            connection.Open();
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@empId", empId);
            command.Parameters.AddWithValue("@empStatus", employeeStatus);
            command.Parameters.AddWithValue("@pagestart", startRowIndex);
            command.Parameters.AddWithValue("@pagesize", maximumRows);
            command.Parameters.Add(new SqlParameter("@numresults", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, null, DataRowVersion.Default, 0));
            EmployeeCollection employees = new EmployeeCollection();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Employee emp = new Employee();
                    emp.EmployeeId = reader.GetInt32("empId");
                    emp.EmployeeName = reader.GetString("empname");
                    emp.DOB = reader.GetDateTime("DOB");
                    emp.Age = reader.GetInt32("Age");
                    emp.Address = reader.GetString("Address");
                    employees.Add(emp);
                }
            }
            e.Arguments.TotalRowCount = (int)command.Parameters["@numresults"].Value;
            return employees;
        }
    }

Now I am adding code to the code behind of the EmployeeDetails.aspx page.

protected void objectDataSourceOrders_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
   {
       if (!e.ExecutingSelectCount)
       {
           e.Arguments.MaximumRows = this.gridViewEmployees.PageSize;
           e.InputParameters.Add("e", e);
       }
   }
Here is the ASPX page code that goes along with the rest of this example

<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddlEmpStatus" runat="server">
    <asp:ListItem Text="Active" Value="Active" Selected="True"></asp:ListItem>
    <asp:ListItem Text="Disabled" Value="Disabled"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <div>
        <asp:GridView ID="gridViewEmployees" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="2" DataSourceID="objectDataSourceEmployee" ForeColor="Black" GridLines="None" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px">
            <FooterStyle BackColor="Tan" />
            <Columns>
                <asp:BoundField DataField="EmployeeId" HeaderText="ProductId" SortExpression="ProductId" />
                <asp:BoundField DataField="EmployeeName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="DOB" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="Age" HeaderText="CustomerId" SortExpression="CustomerId" />
                <asp:BoundField DataField="Address" HeaderText="OrderId" SortExpression="OrderId" />
            </Columns>
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
        </asp:GridView>
        <asp:ObjectDataSource ID="objectDataSourceEmployee" runat="server" EnablePaging="True"
            SelectMethod="Select" TypeName="EmployeeDataSource" OnSelecting="objectDataSourceOrders_Selecting" SelectCountMethod="SelectCount">
            <SelectParameters >
            <asp:QueryStringParameter QueryStringField="empid" DefaultValue="0" Name="empId" />
            <asp:ControlParameter ControlID="ddlEmpStatus" DefaultValue="Active" Name="employeeStatus" PropertyName="Value" />
            </SelectParameters>
            </asp:ObjectDataSource></div>
    </form>
</body>

In the aspx page I am passing the Query string and dropdown control value as a parameter, and Binding the result to the GridView.

The code above worked for me, I hope you too find this code useful.

Thanks

~Brij
Posted by bmdayal | 4 comment(s)

Change default Port for the ASP.NET Development Server

When you use the ASP.NET Development Server to run a file-system Web site, by default, the Web server is invoked on a randomly selected port for localhost. For example, if you are testing a page called Default.aspx, when you run the page on the ASP.NET Development Server, the URL of the page might be the following:

http://localhost:3499/Default.aspx

To specify a port for the ASP.NET Development Server
  1. In Solution Explorer, click the name of the application.

  2. In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

    This will enable editing of the Port number property.

  3. In the Properties pane, click the text box beside Port number and type in a port number.

  4. Click outside of the Properties pane. This saves the property settings.

    Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

Please note the above steps are based on WebSite/ WebServices project. For the Web Application project, we can fix the port number by following steps:

1.  Right click the Project in the Solution Explorer, and then select “Properties”
2.  Click “Web” tab.
3.  Check “Specific port” instead of “Auto-assign Port”.

If you want to debug with IIS, please follow the first and second steps above, and then check “Use IIS Web Server” instead of “Use Visual Studio Development Server”. Also, click the “Create Virtual Directory” button.

Note:

Visual Web Developer cannot guarantee that the port you specify will be available when you run your file-system Web site. If the port is in use when you run a page, Visual Web Developer displays an error message.

Using ASP.NET 3.5 Extensions History Control

This post will provide useful links on how the ASP.NET Extensions Preview allows control over the Browser back button in Ajax. Normally this is not possible using AJAX Controls in WebBrowsers, because AJAX Control's partial postback is not added to the history of Web Browser.

Note : ASP.NET AJAX Extensions are available in the ASP.NET 3.5 Extensions Preview (December 2007).

Watch the video   |   Download the video   |   Get VB code  or  C# code

Important Links :

http://www.asp.net/AJAX/downloads/

http://weblogs.asp.net/davidbarkol/archive/2007/12/28/asp-net-3-5-extensions-history-control-tip.aspx

http://www.bestechvideos.com/2008/06/10/introduction-to-asp-net-ajax-history

http://www.asp.net/learn/ajax-videos/video-149.aspx

Installing Sharepoint Services 3.0 on Windows Vista OS

Just few days back I started exploring Sharepoint Technologies, and started thinking where to start. The biggest setback for me was I cannot run Sharepoint Services on my windows Vista System because Sharepoint Services can only be installed on Windows Server Family of Operating System. But now I cannot go back and repartition my System and install Sharepoint, I also tried using Windows Virtual Machine, but Windows Server 2003 was not working properly on my Windows Virtual Machine.

So now I am left with only two option either repartition the whole harddisk and install dual boot OS or Find some way to run windows sharepoint services on my windows vista. So I started googling and finally I found a jackpot where I can install sharepoint on Windows Vista. First I thought its one more bluff, but thought to give a try, and it worked, and now I am using Windows Sharepoint Services on my Windows Vista Ultimate OS.

Just follow the link below which will guide you step by step process how to do that.

http://community.bamboosolutions.com/blogs/bambooteamblog/archive/2008/05/21/how-to-install-windows-sharepoint-services-3-0-sp1-on-vista-x64-x86.aspx

To download the setup helper file you can either download from the above link or you can download from here directly.

Cheers

~Brij

Method Overloading in WebServices

 

Web services are also classes just like any other .NET classes. Nevertheless they have methods marked as WebMethods that can be exposed by the WebServices to be consumed by the outside world. Apart from these WebMethods they can also have normal methods like any other classes have.


Since a web service is a class it can utilize all the OO features like method overloading. However to use this feature on WebMethods we need to do something more that is explained in this article.

Creating WebMethods:


Let us create a simple WebService that has the following overloaded methods:
public int AddNumbers(int a, int b)

public int AddNumbers(int a, int b, int c)

public decimal AddNumbers(decimal a, decimal b)

All these three methods return variants of a Added numbers to the WebClient. Let us now mark the methods as Web Methods. To acheive this apply the [WebMethod] attribute to the public methods.

[WebMethod]

public int AddNumbers(int a, int b)

    return a+b;

}

[WebMethod]

public int AddNumbers(int a, int b, int c)

    return a+b+c;

}

[WebMethod]

public decimal AddNumbers(decimal a, decimal b)

{

    return a+b;

}

This would compile fine. Run the WebService in the browser. That should give an error saying that the AddNumbers() methods use the same message name 'AddNumbers' and asking to use the MessageName property of the WebMethod.

Adding the MessageName property:

Add the MessageName property to the WebMethod attribute as shown below:

[WebMethod]

public int AddNumbers(int a, int b)

    return "a+b";

}

[WebMethod (MessageName="AddThreeNumbers")]

public int AddNumbers(int a, int b, int c)

    return a + b + c;

}

[WebMethod (MessageName="AddDecimal")]

public decimal AddNumbers(decimal a, decimal b)

{

    return a+b;

}

Now compile the WebService and run in the browser. You can see that the first method is displayed as AddNumbers wherein for the second and third method the alias we set using the MessageName property is displayed.

.NET Framework 4 Poster


First of all welcome guys to .NET 4.0.

This  a very cool poster that shows off the new stuff in .NET Framework 3.5 SP1 and .NET Framework 4.

Here is the DeepZoom version! (use your mouse wheel or click and control-click to zoom in and out)

Download the .NET Framework 4 Poster PDF for high quality printing.


Enjoy!

Posted by bmdayal | with no comments
Filed under:

ASP.NET MVC - Presentation in Bangalore 05-Dec-2008

 

Below are slides + demos of the presentation I've given on 05-Dec-2008. Feel free to re-use and take advantage of them however you want.

 

 

Download the Demo Project from

 

http://weblogs.asp.net/blogs/brijmohan/DemoPresentation/PhoneBook.zip

 

 

Download the Presentation from

 

http://weblogs.asp.net/blogs/brijmohan/DemoPresentation/A%20Brief%20overview%20of%20ASP.NET%20MVC.zip

 

 

Thanks

Brij Mohan

Posted by bmdayal | with no comments

Troubleshooting Visual Studio 2005 and Visual Studio 2008 On Windows Vista

With the introduction of IIS 7.0 in windows vista number of people have been reporting problems when trying to debug their ASP.NET applications on Windows Vista with Visual Studio 2005 F5 debugging support.  There are a handful of posts about trying to get this to work in various ways.

I also faced similar issues. As there are already some good articles floating on net, so instead of reinventing the wheel, I am giving below the links to those articles here. This post I am publishing for my reference only, but if you found this article then I hope this will provide you too with one stop solution to most of the issues. And if you have any good articles then please post as comment.

Fix problems with Visual Studio F5 debugging of ASP.NET applications on IIS7 Vista

Explore The Web Server For Windows Vista And Beyond

Using Visual Studio 2008 with IIS 7.0

Tip/Trick: Using IIS7 on Vista with VS 2005

For me just the first link was more then enough, but for your knowledge I think every link has got some unique combination of knowledge which may help you, and save you time googling with flooded search result.

Cheers

~Brij

CSS Browser Selector

While designing the webpage we often struggle to maintain the consistency of our site across different browsers. To achieve this we use different browser hacks. But again that ends up with making our programming more complicated.

In this post I am going to give you the link of a JavaScript using which you just need to know basics of CSS.

CSS Browser Selector is a very small JavaScript with just one line and less than 1kb which empower CSS selectors. It gives you the ability to write specific CSS code for each operating system and each browser.

This can work for the following Browsers

  • Internet Explorer (All versions)
  • Mozilla, Firefox (all versions), Camino
  • Opera (All versions)
  • Konqueror
  • Safari, NetNewsWire, OmniWeb, Shiira, Google Chrome

I think we have almost covered all the browsers right, if I am missing any let me know.

Instead of writing everything again here, and making this post lengthy I will suggest you to visit this site to download the JavaScript code and instructions on how to use this from here.

Posted by bmdayal | with no comments
Filed under: