Sunday, November 14, 2010

Debugger Improvements VS 2010

1. Pinning Data Tips While Debugging
Visual Studio 2010 also includes some nice new “DataTip pinning” features that enable you to better see and track variable and expression values when in the debugger.

Simply hover over a variable or expression within the debugger to expose its DataTip (which is a tooltip that displays its value) – and then click the new “pin” button on it to make the DataTip always visible:




Also, you can even enter comments for a pinned data tip, so that you can view the comment later.


You can “pin” any number of DataTips you want onto the screen. In addition to pinning top-level variables, you can also drill into the sub-properties on variables and pin them as well.

Another great thing is Pinned DataTips are usable across both Debug Sessions and Visual Studio Sessions:

Pinned DataTips can be used across multiple debugger sessions. This means that if you stop the debugger, make a code change, and then recompile and start a new debug session - any pinned DataTips will still be there, along with any comments you associate with them.

Pinned DataTips can also be used across multiple Visual Studio sessions. This means that if you close your project, shutdown Visual Studio, and then later open the project up again – any pinned DataTips will still be there, along with any comments you associate with them.

See the Value from Last Debug Session:

DataTips are by default hidden when you are in the code editor and the debugger isn’t running. On the left-hand margin of the code editor, though, you’ll find a push-pin for each pinned DataTip that you’ve previously set-up.

Hovering your mouse over a pinned DataTip will cause it to display on the screen. Below you can see what happens when I hover over the first pin in the editor - it displays our debug session’s last values for the “Request” object DataTip along with the comment we associated with them

Importing/Exporting Pinned DataTips:
Pinned DataTips are by default saved across Visual Studio sessions (you don’t need to do anything to enable this).

VS 2010 also now supports importing/exporting pinned DataTips to XML files – which you can then pass off to other developers, attach to a bug report, or simply re-load later.


VS 2010 has also got a tone of other Debugger Enhancements, read about them from Scott Gu’s blog if you are interested.

2. Breakpoint Labels:

Visual Studio 2010 Ultimate : Generating Sequence Diagrams

Another cool feature in Visual Studio 2010 is the ability to generate Sequence diagrams. You may right click inside a method and select “Generate the sequence diagram” from the pop up menu, to generate the diagram on the fly.

To keep example illustrative and simple I will use simple code. Let’s suppose we have ASP.NET MVC application with following controller.

Let’s say we want to generate sequence diagram for AddToProducer() method. All we have to do is to right click on method with mouse, select “Generate Sequence Diagram …” and modify some options.



You can choose various options like the Call Depth and Call scope as shown below:


On hitting the OK button, VIsual Studio 2010 analyzes the code and builds a sequence diagram based on its analysis results as shown below:

Monday, May 10, 2010

Generic Delegate

Fun with Func : Generic Delegate
Func & Action:generic delegate is a cool feature introduced with .NET 3.5. We will look at Func & Action in this short article. But let's start with .NET 1.1.

For instance, take a look a tutorial from C# 1.1 or 2.0, the tutorial on how to use the lambda operator. In that tutorial, we wrote a method that would take a delegate and fold it across the rest of the arguments to the function. It looked like this


public delegate int FoldIntDelegate(int a, int b);

public int Fold(FoldIntDelegate fid, params int[] list)
{
int result = 1;
foreach (int i in list)
result = fid(result, i);
return result;
}


That first line is the line that I'm complaining about - the line I'd like to get rid of. Well, guess what? we can! There are a whole bunch of basic delegate declaration in the System name-space that cover almost all of the common delegate declaration cases by using generics. For instance, that Fold method could have been written like this:

public int Fold(Func fid, params int[] list)
{
int result = 1;
foreach (int i in list)
result = fid(result, i);
return result;
}

The Funcs
The Funcs are the delegate declaration for delegates that return a value, and were first introduced in .NET 3.5. We have already seen one, the two argument Func. But there are Func declarations for everything from no arguments to 4 arguments:

Func(TResult)
Func(T1, TResult)
Func(T1, T2, TResult)
Func(T1, T2, T3, TResult)
Func(T1, T2, T3, T4, TResult)

So if you need more than 4 arguments, you have to make your own declaration. But most of the time, you don't, and so this covers many of the common signatures.

what if I don't want to return a value? Well, don't worry, that is here too:

The Actions
The Actions are the delegate declarations to use when your delegate doesn't return a value. Again, there are Actions for everything from zero to 4 arguments. And just as a note, the zero argument Action is not actually a generic delegate - cause there is no need for it to be (there are no types to deal with). The single argument Action was introduced in .NET 2, and the rest of them were added in .NET 3.5.

Action()
Action(T1)
Action(T1, T2)
Action(T1, T2, T3)
Action(T1, T2, T3, T4)

So, I think we got some idea about the Fun & Action generic delegate. Now see how I am using the above Fold function.

class Program
{
static void Main(string[] args)
{
var aa = new int[] { 1, 2, 3, 4 };
var a12 = Fold(ABC, aa);
}

public static int Fold(Func fid, params int[] list)
{
int result = 1;
foreach (int i in list)
result = fid(result, i);
return result;
}

static int ABC(int i1, int i2)
{
return i1 * i2;
}
}

Enjoy:)...

Monday, March 29, 2010

ASP.NET MVC Partial Views

In ASP.NET WebForms, UserControls were used to break the application into smaller pieces. Each piece represented an important part of the application. In ASP.NET MVC application you can achieve the same effect using RenderPartial and RenderAction methods. In this article we are going to demonstrate how to use RenderPartial to construct and use partial views.

Partial Render:
RenderPartial serves the purpose of rendering a UserControl in an ASP.NET MVC application. The views rendered are called PartialViews. In order to use a partial view in your application add a MVC UserControl to your application. The screenshot below shows which project template to select when adding a user control to your MVC application.



You can add the MVC View UserControl in your current view folder or in the shared folder. First the view folder will be searched for the specified user control followed by the shared folder.

We have added a simple "ViewUserControl.ascx" to our views folder. Now, let's see how we can load the partial views on the page. Inside the view page you can load the partial view using RenderPartial HTML helper method.

User Control:


Parent Page:


Now, if you run the page you will see that the partial view is loaded inside the view page as shown in the screenshot below:


Passing Data to Partial View:
In the previous example our partial view was independent which means it was not dependent on any data populated by the view page. In real world applications this might not be the case. We may need to pass additional data to our partial view. The good news is that the partial view has access to the same ViewData dictionary which is used by the view page.

Lets add a class with name Category, which I will pass to the partial view:
namespace MvcPV.Models
{
public class Category
{
public string Name {get;set;}
}
}

1. Untyped ViewPages:
ViewDataDictionery is an untyped collection consisting of a string and an object. The string represents the key, and the object holds the actual data. Like any untyped collection, the object can be of any type, but must be cast to the correct type before it is used. Items are referenced via their key in the ViewData property of the ViewUserControl (in the case of a PartialView). The second is a strongly typed collection, where items are properties of the ViewUserControl.Model property.

No modify the Home Controller for the action 'Index' which is responsible to render the partial view:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";

var categories = new List()
{
new Category() {Name = "Beverages"},
new Category() {Name = "Condiments"},
new Category() {Name = "Meat"}
};
ViewData["Categories"] = categories;
return View();
}

Now, the Categories.ascx partial view can easily access the ViewData["Categories"] as shown below:


Now, if you run the page you will see that the partial view is loaded inside the view page as shown in the screenshot below:


2. Strongly Typed Views
As of now we show that the ViewData dictionary is shared between the view page and the view user control (partial view). We can even make it better by strong typing the partial view and sending the model as a second parameter to the RenderPartial method. The code below shows how to make the ViewUserControl as a strongly typed view which can handle IEnumerable collection.

Now modify the user control:


Also modify the parent page to pass a strong type data to partial view:


Now Run the application and check how it looks:


Since, the ViewData dictionary is shared between the ViewUserControl and the ViewPage you can easily make changes to the object in the ViewUserControl and it will be reflected in the ViewPage using the controller.

Sunday, March 28, 2010

ASP.NET MVC - Displaying Multi-line String with line break

Today I am going to explain how to view multi-line string in ASP.NET MVC with line break which I come across recently while working on a Blog site.

Problem:
I have seen lots of web developers have problem to writing the text from a multi-line textbox to the SQL and displaying back in HTML table format. Lets say I am developing a blog site where users can post blogs and view them. Generally the best way to display blogs is the HTML table format. The problem is here the multi-line text with line break will lose all the line break while rendering. To get-rid of this I have found a simple/great way to do this..

Solution:
My input text was like this from a multi-line test box:
a
b
c
d
If I see the above string from C# before rendering to web browser it shows me like this "a\r\nb\r\nc\r\nd" but when it displays in web page, it changes to "a b c d" without line break which I doesn't want. Now to solve this problem I did the following.

InputString.Replace("\r\n", "Put here br")


One thing, Don't use Html.Encode() for this type of issue though it is not rite. Happy programming...

Saturday, March 27, 2010

General SQL Server Performance Tips

• Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table's columns. This can reduce network traffic and boost the overall performance of the query.
• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated subquery or derived tables, if you need to perform row-by-row operations.
• If you need to return the total table's row count, you can use alternative way instead of SELECT COUNT (*) statement.
Because SELECT COUNT (*) statement make a full table scan to return the total table's row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT (*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID ('table_name') AND indid < 2 So, you can improve the speed of such queries in several times.
• Use table variables instead of temporary tables.
Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only.
• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary.
• Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.
• Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients.
• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist.
• Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible.
• Use user-defined functions to encapsulate code for reuse.
The user-defined functions (UDFs) contain one or more Transact-SQL statements that can be used to encapsulate code for reuse. Using UDFs can reduce network traffic.
• You can specify whether the index keys are stored in ascending or descending order.
For example, using the CREATE INDEX statement with the DESC option (descending order) can increase the speed of queries, which return rows in the descending order. By default, the ascending order is used.
• If you need to delete all tables’ rows, consider using TRUNCATE TABLE instead of DELETE command.
Using the TRUNCATE TABLE is much fast way to delete all tables’ rows, because it removes all rows from a table without logging the individual row deletes.
• Don't use Enterprise Manager to access remote servers over a slow link or to maintain very large databases.
Because using Enterprise Manager is very resource expensive, use stored procedures and T-SQL statements, in this case.
• Use SQL Server cursors to allow your application to fetch a small subset of rows instead of fetching all tables’ rows.
SQL Server cursors allow application to fetch any block of rows from the result set, including the next n rows, the previous n rows, or n rows starting at a certain row number in the result set. Using SQL Server cursors can reduce network traffic because the smaller result set will be returned.

Optimization tips for designing tables in SQL Server

  • Normalize your tables to the third normal form.
    A table is in third normal form (3NF) if it is in second normal form (2NF) and if it does not contain transitive dependencies. In most cases, you should normalize your tables to the third normal form. The normalization is used to reduce the total amount of redundant data in the database. The less data there is, the less work SQL Server has to perform, speeding its performance.


  • *****

  • Consider the denormalization of your tables from the forth or fifth normal forms to the third normal form.
    Normalization to the forth and fifth normal forms can result in some performance degradation, especially when you need to perform many joins against several tables. It may be necessary to denormalize your tables to prevent performance degradation.


  • *****

  • Consider horizontal partitioning of the very large tables into the current and the archives versions.
    The less space used, the smaller the table, the less work SQL Server has to perform to evaluate your queries. For example, if you need to query only data for the current year in your daily work, and you need all the data only once per month for the monthly report, you can create two tables: one with the current year's data and one with the old data.


  • *****

  • Create the table's columns as narrow as possible.
    This can reduce the table's size and improve performance of your queries as well as some maintenance tasks (such as backup, restore and so on).


  • *****

  • Try to reduce the number of columns in a table.
    The fewer the number of columns in a table, the less space the table will use, since more rows will fit on a single data page, and less I/O overhead will be required to access the table's data.


  • *****

  • Try to use constraints instead of triggers, rules, and defaults whenever possible.
    Constraints are much more efficient than triggers and can boost performance. Constraints are more consistent and reliable in comparison to triggers, rules and defaults, because you can make errors when you write your own code to perform the same actions as the constraints.


  • *****

  • If you need to store integer data from 0 through 255, use tinyint data type.
    The columns with tinyint data type use only one byte to store their values, in comparison with two bytes, four bytes and eight bytes used to store the columns with smallint, int and bigint data types accordingly. For example, if you design tables for a small company with 5-7 departments, you can create the departments table with the DepartmentID tinyint column to store the unique number of each department.


  • *****

  • If you need to store integer data from -32,768 through 32,767, use smallintdata type.
    The columns with smallint data type use only two bytes to store their values, in comparison with four bytes and eight bytes used to store the columns with int and bigint data types respectively. For example, if you design tables for a company with several hundred employees, you can create an employee table with the EmployeeID smallint column to store the unique number of each employee.


  • *****

  • If you need to store integer data from -2,147,483,648 through 2,147,483,647, use int data type.
    The columns with int data type use only four bytes to store their values, in comparison with eight bytes used to store the columns with bigint data types. For example, to design tables for a library with more than 32,767 books, create a books table with a BookID int column to store the unique number of each book.


  • *****

  • Use smallmoney data type instead of money data type, if you need to store monetary data values from 214,748.3648 through 214,748.3647.
    The columns with smallmoney data type use only four bytes to store their values, in comparison with eight bytes used to store the columns with money data types. For example, if you need to store the monthly employee payments, it might be possible to use a column with the smallmoney data type instead of money data type.


  • *****

  • Use smalldatetime data type instead of datetime data type, if you need to store the date and time data from January 1, 1900 through June 6, 2079, with accuracy to the minute.
    The columns with smalldatetime data type use only four bytes to store their values, in comparison with eight bytes used to store the columns with datetime data types. For example, if you need to store the employee's hire date, you can use column with the smalldatetime data type instead of datetime data type.


  • *****

  • Use varchar/nvarchar columns instead of text/ntext columns whenever possible.
    Because SQL Server stores text/ntext columns on the Text/Image pages separately from the other data, stored on the Data pages, it can take more time to get the text/ntext values.


  • *****

  • Use char/varchar columns instead of nchar/nvarchar if you do not need to store unicode data.
    The char/varchar value uses only one byte to store one character, the nchar/nvarchar value uses two bytes to store one character, so the char/varchar columns use two times less space to store data in comparison with nchar/nvarchar columns.


  • *****

  • Consider setting the 'text in row' SQL Server 2000 table's option.
    The text, ntext, and image values are stored on the Text/Image pages, by default. This option specifies that small text, ntext, and image values will be placed on the Data pages with other data values in a data row. This can increase the speed of read and write operations and reduce the amount of space used to store small text, ntext, and image data values. You can set the 'text in row' table option by using the sp_tableoption stored procedure.


  • *****

  • If you work with SQL Server 2000, use cascading referential integrity constraints instead of triggers whenever possible.
    For example, if you need to make cascading deletes or updates, specify the ON DELETE or ON UPDATE clause in the REFERENCES clause of the CREATE TABLE or ALTER TABLE statements. The cascading referential integrity constraints are much more efficient than triggers and can boost performance.


  • *****