Thursday, January 26, 2012

Javascript Date formatting Techniques

Format Date and time :
We will be using following three methods:

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year


1. Date format like 21-January-2012)
The getMonth() function gives us the month in a numeric form. To convert this value into the month name, we will use an array. The array would contain all the 12 month names.

var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month]
+ "-" + curr_year);


2. Date Format like month/day/year

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year)


3.Format like Wednesday 25th January 2012

var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

document.write(d_names[curr_day] + " " + curr_date + ""
+ sup + "
" + m_names[curr_month] + " " + curr_year);

4.Hours:Minutes

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min);

5. Time with AM and PM
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
if (curr_hour == 0)
{
curr_hour = 12;
}
if (curr_hour > 12)
{
curr_hour = curr_hour - 12;
}

var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min + " " + a_p);

6. Two digit minutes
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
if (curr_hour == 0)
{
curr_hour = 12;
}
if (curr_hour > 12)
{
curr_hour = curr_hour - 12;
}

var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
{
curr_min = "0" + curr_min;
}
document.write(curr_hour + " : " + curr_min + " " + a_p);

7. GMT Time
getUTCDate(): Date
getUTCMonth(): Month
getUTCFullYear(): Year (4 digit)
getUTCDay(): Day
getUTCHours(): Hours
getUTCMinutes(): Minutes
getUTCSeconds(): Seconds
getUTCMilliseconds(): Milliseconds

Wednesday, January 25, 2012

Show an hourglass cursor to show the application is busy

function doHourglass()
{
document.body.style.cursor = 'wait';
}
<body onbeforeunload="doHourglass();">

Thursday, January 19, 2012

New features in ASP.Net 4.0

1. Adding MetaKeyword and MetaDescription Using Page objectEvery search engine will look for Meta Keywords tags to know more information of the page contents.Meta keywords and description are most important components of a page.
ASP.Net 4.0 added 2 new properties on the Page object to let you define the Meta keywords and Description.
Here is the code:

protected void Page_Load(object sender, EventArgs e)
{
Page.MetaKeywords = "asp.net,C#";
Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";
}

OR

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net" MetaDescription="asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>


2.ViewStateMode :ASP.Net 3.x, we have EnableViewState property both at Page level and server control level to control the view state. Disabling the ViewState at page level will disable the viewstate to all the page controls. In order to improve the performance, one need to switch off the viewstate for individual control for which saving the viewstate is not necessary and hence disabling viewstate at page level is not a suitable option. To overcome this difficulty, asp.net 4.0 added a new property to Page object and controls called ViewStateMode.
This property has 3 values:
1. Enabled
This value will enable the view state. This is the default value for the Page object.
2. Disabled
This value will disable the viewstate
3. Inherit
This value will make the control to inherit the setting of the parent. This is the default value for a control.
With this property, we can disable the viewstate for the page and enable it for the control if only required.
Consider the following code,

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









CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label1.Text = "Text Assigned in CodeBehind";
Label2.Text = "Text Assigned in CodeBehind";
}
}

When the page executed we will get the following output:
Text Assigned in CodeBehind
Text Assigned in CodeBehind

When the button is clicked:
Text Assigned in CodeBehind
Default Text

Since, the viewstate is disabled at page level (Page object) and the viewstate is enabled for “Label1” we will get the above output on Button click. Please note that if we have not set the value, the default will be “inherit” (for Label2).

3. CSS Improvements
The other major improvements in ASP.Net 4.0 are on the way the HTML rendered to the client browser. The rendered HTML will be complaint with latest HTML standards.
Few things will be:
1. A new property called controlRenderingCompatibilityVersion is added to the Pages element of configuration files.

pages controlRenderingCompatibilityVersion="3.5|4.0"/>

The value “3.5” indicates the controls are rendered in legacy ways. The value “4.0” indicates the control will be rendered with the latest improvements of 4.0 framework.

2. Till 3.5 framework, setting “Enabled=false” for any control will render disabled attributes in the HTML for the control. According to the latest HTML standard the disabled attribute should be set only for INPUT tags. ASP.Net 4.0 addresses this issue by rendering disabled attribute to only INPUT tags and a CSS class called “aspNetDisabled” to other controls to disable it when controlRenderingCompatibilityVersion property is set to “4.0”.

Below you can find a HTML rendered for a Label and TextBox control when controlRenderingCompatibilityVersion property is set to “4.0”.

Label
<input name="TextBox1" type="text" id="TextBox1" disabled="disabled" />

3. From ASP.Net 2.0, the hidden fields generated for viewstate are packed inside a div tag for XHTML standard. This leads a small white space on the page. ASP.Net 4.0 now includes this div with a css class “aspNetHidden”. We can now define the class to prevent the white space by setting border to 0.
4. Menu controls render markup that is semantically correct and compliant with accessibility guidelines.
5. Validation controls do not render inline styles.

4. RabioButtonList and CheckboxList Changes
From ASP.Net 4.0, the RadioButtonList and CheckBoxList controls includes 2 more value fro the property RepeatLayout.
1. OrderedList
The radiobutton/checkbox is rendered as li elements within an ol element.
2. UnorderedList
The radiobutton/checkbox is rendered as li elements within an ul element.

5. Improvements in Code Expressions
There is a new code expression syntax that is being shipped with ASP.Net 4.0. We commonly use the following syntax to output a value from aspx page called code expression.

<%= HTMLOutput %>
There is a new code expression releasing with ASP.Net 4.0 version that will html encode the value.

%: HTMLOutput %>

The above code expression will output the value after doing html encode. i.e. the above expression is equivalent to

%= HttpUtility.HtmlEncode(HTMLOutput) %>

6.Permanent Redirection with HTTP 301 Moved Permanently ResponseWhen we move our internet page to a different location, it is always required to send “HTTP 301 Moved Permanently” response to the search engines to hold back the page rank before redirecting to the new page. Understanding this need asp.net 4.0 includes a new method to do redirection called RedirectPermanent().

Refer below:
Response.RedirectPermanent("new url")


7. Optional ParametersTo implement optional parameters, we used to create overloaded functions before ASP.NET 4 however now optional parameters are no more a restriction in C#. Like VB, optional parameters must be mentioned last. For example:
public void FunctionOptionalParam(string Name, int Age, string Country = "") and we can call them without mentioning the value for the optional parameter.
FunctionOptionalParam("My Full Name",20);

8. Named ParametersNamed parameters allow you to ignore the parameter order and mention parameters with names in a different order. For example:

public void FunctionNamedParam(int x, int y , int z)

On function call, it would be:

FunctionNamedParam(x:1, z:3, y:2)

Although we are sending a value for the parameter z before its order in the function declaration, but these would be equal to x=1, y=2, z=3.

9. Dynamic Lookup
We can use dynamic as object of any type. If there is any error on its usage, we would get it on runtime only. For example:

dynamic integerValue = 1;
dynamic stringValue = " a string";
dynamic Result = integerValue + stringValue;

Output of this would be: 1 a string.

10. Compressing Session Values

ASP.NET session out-of-process state values are saved in a database or on the server. These are saved in a serialized format. Bigger session values consume more resources to be sent to the server. Now, those can be compressed with a new built-in property compressionEnabled. This attribute for the sessionState element can be mentioned in the web.config, like this:

mode="SQLServer"
stateConnectionString="connectionstring goes here"
compressionEnabled="true"/>

This option would be available for out-of-process sessions.


11. Add Reference Dialog

In previous versions of Visual Studio, on opening the Add Reference dialog box, it will take some time to load .NET assembly files initially till the time it loads all the references from the GAC. In VS2010, on opening Add Reference, it opens the Projects tab by default.



If you click on the .NET or COM tab by mistake, you still have an option of canceling it before it loads all the assemblies. So the VS IDE does not freeze like before.

Saturday, January 7, 2012

Common errors and solutions of ASP.net

1.When you debug an ASP.NET application in Visual Studio .NET, you may receive the following error message:

Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.
Possible Solution: To do this goto IIS management console and then go to your virtual directory in IIS.Right click and go to properties of virtual directory/website. Then goto Directory Security tab and then click Edit button under anonymous control and authentication control and then make sure to check the last checkbox which states Integrated windows security.

2.Object reference not set to an instance of an object
Possible solution
This is basically a runtime eror and is caused by your code trying to reference an object that is not available, or set to null.Foreg: Connectionobject you have opened and sed and later on you closed it and set it to null and in the later part of code you try to use the connection again.Then you will encounter this error message.
This error may also occur when improperly call an object without the "new" keyword.

3. Cannot implicitly convert type 'object' to 'string'
Possible solution
The solution here is to append ".ToString() which will represents the object as a string.

4.'name' is a type and cannot be used as an expression
Possible solution
This can happen usually when you forget to use the new keyword when instantiating an object or invoking a constructor.

5. Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Possible solution
a.If you call an object that requires parentheses() after the command, you will get this error. Ex. Conn.Open() not Conn.Open
b.Using an assignment operator as opposes to an equality operator

6. The name 'whatever' does not exist in the class or namespace / The type or namespace name 'whatever' could not be found (are you missing a using directive or an assembly reference?)
Possible solution
This occur when you have not declared a variable globally and or it is missing altogether or is improperly declared.

7. 'method name': not all code paths return a value
Possible solution
This will happen when you are trying to make a function method behave like a subroutine or vice-versa.Use the proper method keyword to remedy this. Void is for methods that do not return a value, although you could response write the output. Whereas, applying a keyword value like string, int, works alongside a return value at the end of the method.

8. System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
The three most common problems are:
1. Sql Server not configured for remote connections.
2. Firewall blocking sql server connections.
3. Wrong data source in connection string.

Wednesday, February 9, 2011

Tips on improving performance in Asp.Net

Improve Perfomance in ASP.net

1. Use Foreach loop instead of For loop for String Iteration.

2. Check “Page.IsPostBack”. To avoid repetition code execution.

3. GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

4. Turn off Session State, if not required.


5. Select the Release mode before making the final Build for your application.
This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

6. Disable ViewState when not required.
EnableViewState="false"

7.Use Caching to improve the performance of your application.

8. Use StringBuilder instead of String class.Strings occupy different memory location in every time of amended where stringbuilder use single memory location

9. Avoid Exceptions: Use If condition (if it is check proper condition)

10. Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

11. Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

12. Use Repeater control instead of DataGrid , DataList as it is efficient, customizable, and programmable.

13. Use single css file instead of multiple css file.

14. Don't make the member variables public or proteted. try to keep private and use public/protected as properties.

15. Use strString=string.Empty instead of strString=""

16. Use Server.Transfer instead of Response.Redirect.


More to come soon..........

Manually sorting gridview

private DataSet GetData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

GridView HTML Code:
The columns are generated automatically for the GridView control which are bound to the data source. Take a look at the HTML generated by the GridView control to have a clear picture.




public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}

private void SortGridView(string sortExpression,string direction)
{
//Cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}

Monday, November 22, 2010

Multiple Rows to column.

create table #Test (
ProdID varchar(5),
ProdDesc varchar(256)
)

insert into #Test (
ProdID,
ProdDesc
)
select 'Prod1', 'Description 1' union all
select 'Prod1', 'Description 2' union all
select 'Prod2', 'Description 1' union all
select 'Prod3', 'Description 1' union all
select 'Prod3', 'Description 2' union all
select 'Prod3', 'Description 3' union all
select 'Prod3', 'Description 4'


select distinct
a.ProdID,
stuff((select
',' + b.ProdDesc
from
#Test b
where
b.ProdID = a.ProdID
for xml path('')),1,1,'') as ProdDesc
from
#Test a