Sunday, May 6, 2012

Windows 8 metro XAML - VariableSizedWrapGrid

VariableSizedWrapGrid for metro apps provides a grid-style layout panel where each tile/cell can be variable size based on content.If your first item is a big item and the subsequent items are small, then you will see that all the subsequent items are shown at the same size. If your first item is small and one/all subsequent items are bigger than the first item, then the subsequent items are clipped to the size of the first item. This is the behaviour of VSWG. You will need to use rowspan and colspan properties to achieve the variable size effect you want. Also you may need to set ItemHeight and ItemWidth properties. Here is the reason why? VSWG allows for variable sized items but the item sizes allowed are in multiples of the base cell size. The size of the layout cell is determined by ItemHeight and ItemWidth properties. If these properties are not set, then the item is measured in integral multiplication of the cell size based on RowSpan and ColumnSpan properties. Features that are not supported yet in VSWG: 1. You can not reorder items in a gridview with a variablesizedwrapgrid. It would be nice if microsoft implements this. 2. You can not change the size of an item once it is set.

Tuesday, February 21, 2012

How to improve Performance of applications

Here is the list of things I have done to improve performance

1. Use Javascript/JQuery when postbacks are not necessary to update portions of page.
2. Use Client Side Validation to save round trips. This way you do not post back the data unless all the controls pass the required validation criteria.
3. Use Page Methods if updating just a small piece of information.
4. Consider Table Partioning if the tables have grown enormously.
5. Consider Indexing on appropriate columns.
6. Return just the necessary data to the application. (Avoid using Select *)
7. If you have large query result, consider paginating data with Sql Server Row_Number() method.
8. Write your stored procedures WITH RECOMPILE option if you are writing a search page that allows its users to search by any of several columns.
9. Enable HTTP Compression.

I am looking forward to try HTTP Compression soon. Here is an article that details how to do this. http://madskristensen.net/post/Performance-tuning-tricks-for-ASPNET-and-IIS-7-part-1.aspx

Tuesday, January 31, 2012

PageRequestManagerParserErrorException when using Ajax UpdatePanel

Sys.WebForms.PageRequestManagerParserErrorException:The message received from the server could not be parsed.
Common causes for this error are when the response is modified by calls to response.Write(), response filters, HttpModules, or server trace is enabled.

Well, why do these cause the exception?
The updatepanel uses asynchronous postbacks. Asynchronous postbacks have the same life cycle and go through the same life cycle events as regular postbacks except for the rendering phase. Only the content that goes in the update panel is captured and sent to the client after combining the content with other pieces of information like page title, hidden form values, form action url and lists of scripts. The content is rendered out using a special format that the JavaScript on the client can understand. If you mess with the format by rendering things outside of the render phase of the page, by using Response.Write(), the client ends up receiving a blob of data that it can't parse, so it gives up and shows you a PageRequestManagerParserErrorException.

How to get around this exception and get the results you need?
If you can avoid writing code, that causes this exception, that is the route to take.

But, sometimes for example you may absolutely have to use Response.Write() because you want to open an active report in PDF format on a button click or you want to download a file. The solution then is to do a regular postback instead of an asynchronous postback.

There are a number of ways of doing this:

The easiest is to simply place the button outside of any UpdatePanels. Unfortunately the layout of your page might not allow for this.
Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
Call ScriptManager.RegisterPostBackControl() and pass in the button in question. This is the best solution for controls that are added dynamically, such as those inside a repeating template or for those control inside a user control.
Here is example code you can add in your page_Load event
ScriptManager sm = (ScriptManager)Page.Master.FindControl("ToolkitScriptManager1");
sm.RegisterPostBackControl(GeneratePDFReportButton);

Tuesday, January 17, 2012

Exception Handling in ASP.Net

In my experience, I have seen developers use variety of techniques for handling exceptions. Some developers surround each and every block of code with a Try...Catch. Some developers let them bubble up and handle them in the Main method for windows applications or handle them at the application level in the Application_Error method of the Global.asax file or handle them at the page level in the Page_Error method of the .aspx file for Web applications.

My take on Exception handling is that all exceptions should be logged no matter where you catch them. You could log them to the event log, database or file.

There are three general cases when Try...Catch blocks make sense:
1. When there is an opportunity to recover from the application by taking some alternative course of action. For Example: If an SMTP server fails, you may want to connect to a back up SMTP server.
2. When an exception indicates a problem that should not impede the current flow, log the exception and swallow the exception. For Example: If an email notification fails after an order is processed, you may just want to log the error and proceed.
3. When additional information needs to be included with the exception. In this case it is useful to catch the exception and re throw a new exception with the original exception as an inner exception.

There are Error Logging and notification libraries you could use like ELMAH.

Below is the example code on how to handle errors in Application_Error event of Global.asax file:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
if (ctx == null) return;
Exception exception = ctx.Server.GetLastError();
if (exception.InnerException != null)
{
EventLog MyLog = new EventLog();
MyLog.Source = e.Source;
MyLog.WriteEntry(e.Message + " " + e.StackTrace);
Response.Redirect("error.html");
}
}

Thursday, January 12, 2012

Exporting long strings to Excel format using Active Reports.

When you are pulling a huge text field data from the database, Active Reports breaks the text into multiple rows. Sorting the excel sheet columns will be a problem with the way active report generates the Exel report. Below is the code to change the default behavior of the excel format Active Report. All you will need to do is explicitly set wordwrap on the controls to false. Here, I am looping to find all the controls and setting the word wrap on each control to false.

// To fix excel reports from displaying single cell data in multiple rows
if (IsXls == true)
{
Section Hsec = this.Sections["pageHeader"];
for (int i = 0; i < Hsec.Controls.Count; i++)
{
if ((Hsec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.Label")
{
((Label)(Hsec.Controls[i])).WordWrap = false;
}
}

Section sec = this.Sections["detail"];
for (int i = 0; i < sec.Controls.Count; i++)
{
if ((sec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.TextBox")
{
((TextBox)(sec.Controls[i])).WordWrap = false;
}
}
}

Tuesday, January 10, 2012

Java vs CSharp

I started reading a book on Java - 'Java How to Program' to learn and possibly start working with it. As I read, it is so similar to C#. There are just a very few subtle differences.

Static Import: A static import declaration in java enables you to import the static members of a class or interface so you can access them via their unqualified names in your class. The class name and a dot (.) are not required to use an imported static member.

Syntax:
import static packageName.ClassName.staticMemberName; to import a particular static member.
import static packageName.ClassName.*; to import all static members of the specified class

Example:
// Static import of Math class methods.
public class StaticImportTest
{
public static void main( String[] args )
{
System.out.printf( "sqrt( 900.0 ) = %.1f\n", );
System.out.printf( "ceil( -9.8 ) = %.1f\n", );
System.out.printf( "E = %f\n", E );
System.out.printf( "PI = %f\n", PI );
} // end main
}

Final Modifier: Final Modifier in Java is same as readonly in C#. final modifier in Java and readonly modifier in C# can be initialized when they're declared. If they are not, they must be initialized in every constructor of the class. Initializing constants in constructors enables each object of the class to have a different value for constant.

package: package in java is same as namespace in C#.

Import: Import in Java is same as Using in C#.
Java source code file has the following order
1. a package declaration (if any)
2. import declarations (if any), then
3. class declarations
Only one of the class declarations in a particular file can be public.

C# source code file has the following order
1. using declarations (if any)
2. namespace declaration (if any)
3. class declarations
Any number of class declarations in a particular file can be public.

Access modifiers :In Java, if no access modifier (public, protected or private) is specified for a method or variable when it’s declared in a class, the method or variable is considered to have package access. If a class has no access modifier, then it can only be accessed from same package.
In C#, if no access modifier is specified, the default accessibility of class members (including methods) is private. If no access modifier is specified for a class, The default accessibility of a class itself is internal.

Super: To call a base class method in Java, Super followed by dot is used. In C# base followed by dot is used.

Extends:In java to extend from a base class, keyword 'extends' is used. In C# : is used.
Java example:
public class CommissionEmployee extends Object
{
...
}
@Override: To override a super class method in Java, '@Override' is used.
In C# 'override' is used.

Also in .Net, The overridden base method/property must be virtual, abstract, or override. Both the override method/property and the overridden method/property must have the same access level modifier. When a class contains an abstract method, that class must be declared as abstract. classes that derive from that abstract class, must provide an implementation for this abstract method. A class can have a virtual method. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.

Java example:
@Override // indicates that this method overrides a superclass method
public String toString()
{
...
} // end

Class Object:All classes in Java inherit directly or indirectly from the Object class (package java.lang), so its 11 methods (some are overloaded) are inherited by all other classes - clone, equals, finalize, getClass, hashCode, wait, notify, notifyAll, toString.

Inheritence: In C#, To call a base class constructor from the derived class constructor, you should use ": base class name ( args)"
Csharp Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test : supertest
{
public test(int x): base(x){ }
}

In Java, you simply write super(args...); as the first line in the child class constructor to call the base class constructor
Java Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test extends supertest
{
public test(int x) { super(x); }
}

instanceof: Java's "instanceof" keyword equivalent in csharp is "is"
Java example:
if ( currentEmployee instanceof BasePlusCommissionEmployee )
{
}

C# example:
if ( currentEmployee is BasePlusCommissionEmployee )
{
}

Inteface: Interface in C# cannot contain fields.
In Java, Interface can contain fields and are implicitly public, static and final. All methods declared in an interface are implicitly public abstract methods. Interface methods in java are always public abstract, so they do not need to be declared as such. You will not have any compile errors by declaring methods in the interface public abstract.
In C#, you will have compile errors if you declare methods with any modifiers.

Implementing an interface: To implement an interface in java implements keyword is used. In C# ":" is used.
In Java, When a class implements from an interface, the class should override the methods defined in the interface using the keyword @override.
In C#, you do not override the method in the class implementing the interface.
Java example:
public interface Payable
{
double getPaymentAmount(); // You can declare public abstract double getPaymentAmount()
}
public class Invoice implements Payable
{
@Override
public double getPaymentAmount()
{
return getQuantity() * getPricePerItem(); // calculate total cost
} //
}

C# example:
public interface supertest
{
void printhello(string str); // You will have compile errors if you use public abstract void printhello(string str)
}
public class test : supertest
{
public void printhello(string str)
{
Console.WriteLine("hello Dear " + str);
}
}

In Java, when a class implements an interface, it makes a contract with the compiler stating either that the class will implement each of the methods in the interface or that the class will be declared abstract. So if you declare the class abstract, you do not have to implement the methods in the interface.
In C#, if the derived class does not implement the methods in the interface, you will have compile errors. If you want to declare the class that implements the interface abstract, you would have to still declare the methods you do not want to implement abstract inside the class.

Exception Handling: In Java exceptions are two types: 1. checked 2. unchecked. Java compiler enforces a catch-or-declare requirement for checked exceptions. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program— for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.
Another feature Java provides is Preconditions and Postconditions - A precondition must be true when a method is invoked. A postcondition is true after the method successfully returns. Typically, a method’s preconditions and postconditions are described as part of its specification. When designing your own methods, you should state the preconditions and
postconditions in a comment before the method declaration.

To catch multiple exceptions in java, operation '|' is used. The code is simple.
Java Example:
catch ( Type1 | Type2 | Type3 e )

A little more code should be written in C# to do the same.
C# Example:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}


(To be Continued...)

Wednesday, December 21, 2011

How to call Server Side function from Client Side Code

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds.
1. Use __doPostBack() and IPostBackEventHandler.
2. Set hidden variables and sumbit the form using form.submit()
3. Use PageMethods in ASP.net AJAX.

PageMethods can possibly save you a large amount of bandwidth which can mean faster response times for visitors on slower connections. Instead of posting all of the form values, we can send only what is needed. Instead of returning a large chunk of data, we can return precisely what we need to display to the user. For performance and bandwidth sensitive situations, they may be the right tool. So use PageMethods where possible instead of UpdatePanel as UpdatePanel posts all of the page's form values when all you might need to pass to the server is very little information. Using PageMethods you can save bandwidth.

Here is a link to learn how to use PageMethods: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109