Monday, September 20, 2010

javascript to change validation group name

change group name :

Enable proxy in web config

<system.net>

    <defaultProxy enabled="true">
        <proxy usesystemdefault="True" proxyaddress="http://192.168.0.254:3128" />    </defaultProxy>

</system.net>

javascript to set cookies

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

Create classes from xml file

Go to command prompt and execute the following commands:


xsd file.xdr [/outputdir:directory][/parameters:file.xml]
xsd file.xml [/outputdir:directory] [/parameters:file.xml]
xsd file.xsd {/classes | /dataset} [/element:element]
             [/language:language] [/namespace:namespace]
             [/outputdir:directory] [URI:uri] [/parameters:file.xml]
xsd {file.dll | file.exe} [/outputdir:directory] [/type:typename [...]][/parameters:file.xml]


example:

xsd ".xml" /outputdir:"C:"
xsd ".xsd" /outputdir:"C:" /language:C# /namespane:asd class
 

jQuery: copy to clipboard zero clipboard

Zero clipboard:

http://code.google.com/p/zeroclipboard/wiki/Instructions

Tuesday, July 27, 2010

Google Gadgets: Create and upload

Task: To create a google gadgets.
Step-1: Create an xml file:
test.xml.
Step-2: Copy and paste the following code to the xml file.
<?xml version="1.0" encoding="UTF-8" ?>

<Module>

<ModulePrefs title="test title" description="test description" author="test author" author_email="nitindhiman@gmail.com" author_link="http://nitindhiman.blospot.com/" title_url="http://nitindhiman.blospot.com/" screenshot="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg98F5SCXygyaV4vUASPtL3niQ0j_Kw4MlWU0njVLaMG0bKTgfBZW1s-sIv6UOrUdZDJbLfU1GvonXBtjPxrax3baGpZ__m-V7e-eJkC0WKzwocRF9dIEgkR2LU-FXrwG24_v68CI0vTAjJ/s220/Image015.jpg" thumbnail="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg98F5SCXygyaV4vUASPtL3niQ0j_Kw4MlWU0njVLaMG0bKTgfBZW1s-sIv6UOrUdZDJbLfU1GvonXBtjPxrax3baGpZ__m-V7e-eJkC0WKzwocRF9dIEgkR2LU-FXrwG24_v68CI0vTAjJ/s220/Image015.jpg" />

<UserPref name="show_date" display_name="Show Dates?" datatype="bool"/>

<UserPref name="show_summ" display_name="Show Summaries?" datatype="bool"/>

<UserPref name="num_entries" display_name="Number:" />

<Content type="html">

<![CDATA[

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

<style type="text/css">

body{font-size: 11px;font-style: normal;font-weight: normal;font-family: Arial,Helvetica,Sans-Serif;text-align: left;color: #206488;background-color: #bafffe;}

body a, a:link, a:hover, a:visited{color: #206488;letter-spacing: 1px;text-decoration: underline;}.cleared{border: medium none;clear: both;float: none;font-size: 1px;margin: 0;padding: 0;}

.saper{float: left;font-size: 0;height: 10px;line-height: 0;width: 100%;}

.tooltip{color:#000;padding: 5px 0;display: none;}

.toollnk{padding: 0 5px;float: left;}

.float-left{float: left;}

</style>

<div class="saper"></div><div id="dv_id" style="overflow:auto;height:200px;width:500px;"><a href="http://www.nitindhiman.blogspot.com">nitin dhiman's blog</a></div>

<script type="text/javascript">$(document).ready(function () {alert('hello external link');});</script>

]]>

</Content>

</Module>

Step-3: Upload the xml file to a web server so that we can browse the file in a browser(IE / FIREFOX / CHROME etc.)
Step-4: Go to following URL to submit google gadget:
http://www.google.com/ig/submit
Step-5: Enter the URL in the textbox and submit your gadget to the google:
Step-6: All done search for your widget and add that to your page.
Thanks,
Nitin Dhiman.

Monday, July 26, 2010

Handle Exception in Update panel(asp.net Ajax and Error/Exception Handling)

Problem: While using Ajax with asp.net, if we get crash on any event which was fired by a control in a update panel we do not get any yellow screen or error page. And end user does not get any message or result.

Solution:
Step-1: Add OnAsyncPostBackError event to the script manager and set AllowCustomErrorsRedirect property to true.

<asp:scriptmanager allowcustomerrorsredirect="true" id="smBody" onasyncpostbackerror="smBody_AsyncPostBackError" runat="server"></asp:scriptmanager>

Step-2: Add the following script after the script manager(Otherwise you will get javascript error on the page).

<script type="text/javascript">
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
</script>
Step-3: Add the following script to the page:
<script type="text/javascript">
    function EndRequestHandler(sender, args) {
      if (args.get_error() != undefined) {
        var Error = "Error Code: " + args.get_response().get_statusCode() + "\nError Message: " +
                    args.get_error().message;
        alert(Error);
        args.set_errorHandled(true);
        //Uncomment the following line to refresh the window after alert the error message.
        //window.location = window.location;
      }
    }
  </script>
Step-4: Write the script-manager's AsyncPostBackError event:
protected void smBody_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
smBody.AsyncPostBackErrorMessage = e.Exception.Message;
}
Now all the postback errors will be displayed in alert message and after that the page will be reloaded :-).
Thanks. :-)

Wednesday, July 21, 2010

.net Extension Menthod

Extension methods enable you to "add" methods to existing types without creating a new derived type or modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. There is no apparent difference between calling an extension method and actually defined methods of that type.
for example lets create an extension method for string type to check whether that particular string can be convert to int or not:
using System;
using System.ComponentModel;
using System.Reflection;
public static class Extension
{
    public static bool IsInt(this string str)
    {
        int iCount = 0;
        return int.TryParse(str, out iCount);
    }
}
And now we can use this static method to check whether a string can be converted to int or not:
string str1="a";
string str2="1";

    if(str1.IsInt())
    {
        Response.Write("string can be converted to int");
    }
    else
    {
        Response.Write("string can not convert to int");
    }
Few more Examples:

namespace ExtensionMethods
{
    public static class Extensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }

        public static int ActualLength(this string[] strArray)
        {
            int iCount = 0;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (strArray[i] != string.Empty && strArray[i] != null)
                    iCount++;
            }
            return iCount;
        }

        public static bool IsInt(this string str)
        {
            int iCount = 0;
            return int.TryParse(str, out iCount);
        }

        public static bool IsLong(this string str)
        {
            long iCount = 0;
            return long.TryParse(str, out iCount);
        }
        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
    }
}

Tuesday, July 20, 2010

"asp.net, C#" Control '******_*******_*******' of type 'GridView' must be placed inside a form tag with runat=server.

        //Problem:
        "Control 'ctl00_cphBody_dgReport' of type 'GridView' must be placed inside a form tag with runat=server."

        protected void btnExcel_Click(object sender, System.EventArgs e)
        {
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = null;
            Response.AddHeader("content-disposition", "attachment;filename=ActivatedUserDetails.xls");
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/xls";
            htmlWrite = new HtmlTextWriter(stringWrite);
            dgReport.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }

        //Solution: Step-1:
        //on page.aspx page set EnableEventValidation to false
        EnableEventValidation="false"
        //on page.aspx page set EnableEventValidation to false

        //Solution: Step-2:
        //on page.aspx.cs page add the following code snippet.
        public override void VerifyRenderingInServerForm(Control control)
        {

        }

        //and its all done :-)

Tuesday, July 6, 2010

ajax post to post data to server and get response using jQuery and JSON.

1. Create a page PageName.aspx, create a div on that:
    <div id="target_div_id">  

    </div>
2. Include the jQuery file.
3. call the following javascript function on any event:
function JsonPost(input1, input2, input3, input4) {

        URL = "PageName.aspx/WebMethodName";

    var options = {

        type: "POST",

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        url: URL,

        data: '{input1:"' + input1 + '", input2:"' + input2 + '", input3:"' + input3 + '", input4:"' + input4 + '"}',

        success: function (msg) {

            if (msg.d == 'error')

                alert(msg.d);

            else {

                $('#target_div_id').append(msg.d);

            }

            HideLoader();

        },

        error: function (msg) {

            alert(msg.d);

        }

    };

    $.ajax(options);

}
4. Following web method will automatically called:


    /// <summary>

    /// Create a web method, input parameter must be same as the parameters in our web method.

    /// from here we will have to return the complete html(including html controls, their ids and classes)

    /// </summary>

    /// <param name="input1"></param>

    /// <param name="input2"></param>

    /// <param name="input3"></param>

    /// <param name="input4"></param>

    /// <returns></returns>

    [WebMethod]

    public static string WebMethodName(string input1, string input2, string input3, string input4)

    {

        try

        {

            int j = 10;//some number depending upon our requirement

            StringBuilder sbResult = new StringBuilder();

            for (int i = 0; i < j; i++)

            {

                sbResult.AppendLine("<!--any required html containing controls and ids-->");

            }

            return sbResult.ToString();

        }

        catch (Exception ex)

        {

            return ex.Message;

        }

    }

Wednesday, May 19, 2010

alt key codes

Symbol Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
§ 21
22
23
24
25
26
27
28
29
30
31
space 32
! 33
" 34
# 35
$ 36
% 37
& 38
' 39
( 40
) 41
* 42
+ 43
, 44
- 45
. 46
/ 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
Symbol Number
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
] 93
^ 94
_ 95
` 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
{ 123
| 124
} 125
~ 126
127
Ç 128
Symbol Number
ü 129
é 130
â 131
ä 132
à 133
å 134
ç 135
ê 136
ë 137
è 138
ï 139
î 140
ì 141
Ä 142
Å 143
É 144
æ 145
Æ 146
ô 147
ö 148
ò 149
û 150
ù 151
ÿ 152
Ö 153
Ü 154
¢ 155
£ 156
¥ 157
158
ƒ 159
á 160
í 161
ó 162
ú 163
ñ 164
Ñ 165
ª 166
º 167
¿ 168
169
¬ 170
½ 171
¼ 172
¡ 173
« 174
» 175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
Symbol Number
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
α 224
ß 225
Γ 226
π 227
Σ 228
σ 229
µ 230
τ 231
Φ 232
Θ 233
Ω 234
δ 235
236
φ 237
ε 238
239
240
± 241
242
243
244
245
÷ 246
247
° 248
249
· 250
251
252
² 253
254
255

Friday, April 2, 2010


Custom Numeric Format Strings Output Examples
The following table illustrates the output created by applying some custom numeric format
strings to specific data types and values. The output was generated using the ToString method
and the English-United States (en-US) culture.

Format string

Data type
Value

Output
#####Double123123
00000Double12300123
(###) ### - ####Double1234567890(123) 456 – 7890
#.##Double1.21.2
0.00Double1.21.20
00.00Double1.201.20
#,#Double12345678901,234,567,890
#,,Double12345678901235
#,,,Double12345678901
#,##0,,Double12345678901,235
#0.##%Double0.0868.6%
0.###E+0Double860008.6E+4
0.###E+000Double860008.6E+004
0.###E-000Double860008.6E004
[##-##-##]Double123456[12-34-56]
##;(##)Double12341234
##;(##)Double-1234(1234)

Section Separators and Conditional Formatting

Section Separators and Conditional Formatting

Different formatting can be applied to a string based on whether the value is positive,
negative, or zero. To produce this behavior, a custom format string can contain
up to three sections separated by semicolons. These sections are described in the
following table.
No. of Sections
Description

One section

The format string applies to all values.

Two sections

The first section applies to positive values and zeros, and the second section applies
to negative values.
If the number to be formatted is negative, but becomes zero after rounding according
to the format in the second section, then the resulting zero is formatted according
to the first section.

Three sections

The first section applies to positive values, the second section applies to negative
values, and the third section applies to zeros.
The second section can be left empty (by having nothing between the semicolons),
in which case the first section applies to all nonzero values.
If the number to be formatted is nonzero, but becomes zero after rounding according
to the format in the first or second section, then the resulting zero is formatted
according to the third section.

Section separators ignore any preexisting formatting associated with a number when
the final value is formatted. For example, negative values are always displayed
without a minus sign when section separators are used. If you want the final formatted
value to have a minus sign, you should explicitly include the minus sign as part
of the custom format specifier.

.NET Custom Number Format Strings


.NET Custom Number Format Strings
Specifier
Name
Description
0Zero placeholderIf the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the result string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the result string. The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.
#Digit placeholderIf the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. This specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed. The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.
.Decimal pointThe first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo that controls formatting.
,Thousand separator and number scalingThousand Separator Specifier:If one or more ',' characters is specified between two digit placeholders (0 or #) that format the integral digits of a number, a group separator character is inserted between each number group in the integral part of the output. The NumberGroupSeparator and NumberGroupSizes properties of the current NumberFormatInfo object determine the character used as the number group separator and the size of each number group.
Number Scaling Specifier:If one or more ',' characters is specified immediately to the left of the explicit or implicit decimal point, the number to be formatted is divided by 1000 each time a number scaling specifier occurs. For example, if the string "0,," is used to format the number 100 million, the output is "100". You can use thousand separator and number scaling specifiers in the same format string.
%Percentage placeholderThe presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.
E0
E+0
E-0
e0
e+0
e-0
Scientific notationIf any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The "E+" and "e+" formats indicate that a sign character (plus or minus) should always precede the exponent. The "E", "E-", "e", or "e-" formats indicate that a sign character should only precede negative exponents.
\Escape characterIn C# and C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like '\n' (new line). In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display '\'. Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.
'ABC'
"ABC"
Literal stringCharacters enclosed in single or double quotes are copied to the result string, and do not affect formatting.
;Section separatorThe ';' character is used to separate sections for positive, negative, and zero numbers in the format string.
OtherAll other charactersAny other character is copied to the result string, and does not affect formatting.

.NET Custom DateTime Format Strings


Format String

Data type

Value
Output
CDouble12345.6789$12,345.68
DInt321234512345
D8Int321234500012345
EDouble12345.67891.234568E+004
E10Double12345.67891.2345678900E+004
EDouble12345.67891.2346e+004


Format String

Data type

Value
Output
FDouble12345.678912345.68
F0Double12345.6789123456
F6Double12345.678912345.678900
GDouble12345.678912345.6789
G7Double12345.678912345.68
GDouble0.00000232.3E-6


Format String

Data type

Value

Output
G2Double12341.2E3
GDoubleMath.PI3.14159265358979
NDouble12345.678912,345.68
N4Double123456789123,456,789.0000
PDouble.12612.60 %
rDoubleMath.PI3.141592653589793

.NET Standard Number Format Strings

.NET Standard Number Format Strings
Specifier
Name
Description
C or cCurrencyThe number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the current NumberFormatInfo object. Precision specifier (eg. “{0:C5}” allowed.
D or dDecimalThis format is supported only for integral types. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. Precision specifier (eg. “{0:d3}” allowed.
E or eScientific (expol)The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. Precision specifier (eg. “{0:E5}” allowed. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.
F or fFixed-pointThe number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. Precision specifier (eg. “{0:f4}” allowed.
G or gGeneralThe number is converted to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present.
N or nNumberThe number is converted to a string of the form "-d,ddd,ddd.ddd…", where '-' indicates a negative number symbol if required, 'd' indicates a digit (0-9), ',' indicates a thousand separator between number groups, and '.' indicates a decimal point symbol. The actual negative number pattern, number group size, thousand separator, and decimal separator are specified by the current NumberFormatInfo object. Precision specifier (eg. “{0:N5}” allowed.
P or pPercentThe number is converted to a string that represents a percent as defined by the NumberFormatInfo.PercentNegativePattern property if the number is negative, or the NumberFormatInfo.PercentPositivePattern property if the number is positive. The converted number is multiplied by 100 in order to be presented as a percentage. Precision specifier (eg. “{0:p6}” allowed.
R or rRound-tripThis format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Precision specifier NOT allowed.
X or xHexa decimalThis format is supported only for integral types. The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. Precision specifier (eg. "{0:x4}" allowed. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
Any other single char.(Unknown specifier)An unknown specifier throws a runtime format exception.

Tuesday, March 30, 2010

.NET Custom DateTime Format Strings


.NET Custom DateTime Format Strings
SpecifierDescription
dRepresents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero.
ddRepresents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero.
dddRepresents the abbreviated name of the day of the week as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames property.
ddddRepresents the full name of the day of the week as defined in the current System.Globalization.DateTimeFormatInfo.DayNames property.
fRepresents the most significant digit of the seconds fraction. Note that if the "f" format specifier is used alone, without other format specifiers, it is interpreted as the "f" standard DateTime format specifier (full date/time pattern). When you use this format specifier with the ParseExact or TryParseExact method, the number of "f" format specifiers that you use indicates the number of most significant digits of the seconds fraction to parse.
ff…Number of repeated specifiers represents most significant digits of the seconds fraction.
FRepresents the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. When you use this format specifier with the ParseExact or TryParseExact method, the number of "F" format specifiers that you use indicates the maximum number of most significant digits of the seconds fraction to parse.
FF…Number of repeated specifiers represents most significant digits of the seconds fraction. Trailing zeros, or two zero digits, are not displayed.
g or ggRepresents the period or era (A.D. for example). This specifier is ignored if the date to be formatted does not have an associated period or era string.
hRepresents the hour as a number from 1 through 12, that is, the hour as represented by a 12-hour clock that counts the whole hours since midnight or noon. A single-digit hour is formatted without a leading zero.
hhRepresents the hour as a number from 01 through 12, that is, the hour as represented by a 12-hour clock that counts the whole hours since midnight or noon. A single-digit hour is formatted with a leading zero.
HRepresents the hour as a number from 0 through 23, that is, the hour as represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted without a leading zero.
HHRepresents the hour as a number from 00 through 23, that is, the hour as represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.
KRepresents different values of the DateTime.Kind property, that is, Local, Utc, or Unspecified. This specifier round-trips the kind value in text and preserves the time zone. For the Local kind value, this specifier is equivalent to the "zzz" specifier and displays the local offset, for example, "-07:00". For the Utc kind value, the specifier displays a "Z" character to represent a UTC date. For the Unspecified kind value, the specifier is equivalent to "" (nothing).
mRepresents the minute as a number from 0 through 59. The minute represents whole minutes passed since the last hour. A single-digit minute is formatted without a leading zero.
mmRepresents the minute as a number from 00 through 59. The minute represents whole minutes passed since the last hour. A single-digit minute is formatted with a leading zero.
MRepresents the month as a number from 1 through 12. A single-digit month is formatted without a leading zero.
MMRepresents the month as a number from 01 through 12. A single-digit month is formatted with a leading zero.
MMMRepresents the abbreviated name of the month as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames property.
MMMMRepresents the full name of the month as defined in the current System.Globalization.DateTimeFormatInfo.MonthNames property.
sRepresents the seconds as a number from 0 through 59. The second represents whole seconds passed since the last minute. A single-digit second is formatted without a leading zero.
ssRepresents the seconds as a number from 00 through 59. The second represents whole seconds passed since the last minute. A single-digit second is formatted with a leading zero.
tRepresents the first character of the A.M./P.M. designator defined in the current System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator property.
ttRepresents the A.M./P.M. designator as defined in the current System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator property.
yRepresents the year as at most a two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the year has fewer than two digits, the number is formatted without a leading zero.
yyRepresents the year as a two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the year has fewer than two digits, the number is padded with leading zeroes to achieve two digits.
yyyRepresents the year as a three-digit number. If the year has more than three digits, only the three low-order digits appear in the result. If the year has fewer than three digits, the number is padded with leading zeroes to achieve three digits. Note that for the Thai Buddhist calendar, which can have five-digit years, this format specifier displays all five digits.
yyyyRepresents the year as a four-digit number. If the year has more than four digits, only the four low-order digits appear in the result. If the year has fewer than four digits, the number is padded with leading zeroes to achieve four digits. Note that for the Thai Buddhist calendar, which can have five-digit years, this format specifier renders all five digits.
yyyyyRepresents the year as a five-digit number. If the year has more than five digits, only the five low-order digits appear in the result. If the year has fewer than five digits, the number is padded with leading zeroes to achieve five digits. If there are additional "y" specifiers, the number is padded with as many leading zeroes as necessary to achieve the number of "y" specifiers.
zRepresents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours. For example, the offset for a computer in the Pacific Standard Time zone is "-8". The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from –12 through +13. A single-digit offset is formatted without a leading zero. The offset is affected by daylight savings time.
zzRepresents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours. For example, the offset for a computer in the Pacific Standard Time zone is "-08". The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from –12 through +13. A single-digit offset is formatted with a leading zero. The offset is affected by daylight savings time.
zzzRepresents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours and minutes. For example, the offset for a computer in the Pacific Standard Time zone is "-08:00". The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from –12 through +13. A single-digit offset is formatted with a leading zero. The offset is affected by daylight savings time.
:The time separator defined in the current System.Globalization.DateTimeFormatInfo.TimeSeparator property that is used to differentiate hours, minutes, and seconds.
/The date separator defined in the current System.Globalization.DateTimeFormatInfo.DateSeparator property that is used to differentiate years, months, and days.
"Quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Precede each quotation mark with an escape character (\).
'Quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%cRepresents the result associated with a custom format specifier "c", when the custom DateTime format string consists solely of that custom format specifier. That is, to use the "d", "f", "F", "h", "m", "s", "t", "y", "z", "H", or "M" custom format specifier by itself, specify "%d", "%f", "%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H", or "%M".
\cThe escape character. Displays the character "c" as a literal when that character is preceded by the escape character (\). To insert the backslash character itself in the result string, use two escape characters ("\\").
Any other char.Any other character is copied to the result string, and does not affect formatting.

.NET Standard DateTime Format Strings


.NET Standard DateTime Format Strings

Specifier

Name

Description

d

Short date pattern

Represents a custom DateTime format string defined by the current ShortDatePattern
property.

D

Long date pattern

Represents a custom DateTime format string defined by the current LongDatePattern
property.

f

Full date/time pattern (short time)

Represents a combination of the long date (D) and short time (t) patterns, separated
by a space.

F

Full date/time pattern (long time)

Represents a custom DateTime format string defined by the current FullDateTimePattern
property.

g

General date/time pattern (short time)

Represents a combination of the short date (d) and short time (t) patterns, separated
by a space.

G

General date/time pattern (long time)

Represents a combination of the short date (d) and long time (T) patterns, separated
by a space.

M or m

Month day pattern

Represents a custom DateTime format string defined by the current MonthDayPattern
property.

o

Round-trip date/time pattern

Represents a custom DateTime format string using a pattern that preserves time zone
information. The pattern is designed to round-trip DateTime formats, including the
Kind property, in text. Then the formatted string can be parsed back using Parse
or ParseExact with the correct Kind property value. Equivalent custom format string
is "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK".

R or r

RFC1123 pattern

Represents a custom DateTime format string defined by the current RFC1123Pattern
property. The pattern is a defined standard and the property is readonly. Equivalent
custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". Does not convert
DateTimes to UTC.

s

Sortable date/time pattern; ISO 8601

Represents a custom DateTime format string defined by the current SortableDateTimePattern
property. This pattern is a defined standard and the property is read-only. Equivalent
custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".

t

Short time pattern

Represents a custom DateTime format string defined by the current ShortTimePattern
property. For example, the custom format string for the invariant culture is "HH:mm".

T

Long time pattern

Represents a custom DateTime format string defined by the current LongTimePattern
property. For example, the custom format string for the invariant culture is "HH:mm:ss".

u

Universal sortable date/time pattern

Represents a custom DateTime format string defined by the current UniversalSortableDateTimePattern
property. Equivalent custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". Does
not convert DateTimes to UTC.

U

Universal sortable date/time pattern

Represents a custom DateTime format string defined by the current FullDateTimePattern
property. This pattern is the same as the full date/long time (F) pattern. However,
formatting operates on the Coordinated Universal Time (UTC) that is equivalent to
the DateTime object being formatted.

Y or y

Year month pattern

Represents a custom DateTime format string defined by the current YearMonthPattern
property. For example, the custom format string for the invariant culture is "yyyy
MMMM".

Any other single character

(Unknown specifier)

An unknown specifier throws a runtime format exception.

Monday, March 29, 2010

Casecading dropdown using JQuery.

1) Put the following JavaScript function on the page:

function BindDropDown(dropdown_parent,dropdown_child,selectedVal)
{
if(document.getElementById(dropdown_parent).selectedIndex>0)
{
$.ajax
({
url: "/GetAjaxData.aspx",
data: "type=products&value="+document.getElementById(dropdown_parent).options[document.getElementById(dropdown_parent).selectedIndex].value,
success: function(message1)
{
var selectedindex=0;
var rows1 = message1.split("\n");
var iCount = 0;
document.getElementById(dropdown_child).options.length = 0;
for (iCount = 0; iCount < rows1.length; iCount++)
{
var valu=rows1[iCount].split("|");
if(valu[1].replace(/^\s*/, "").replace(/\s*$/, "")==selectedVal)
selectedindex=iCount;
var oOption = new Option(valu[0],valu[1].replace(/^\s*/, "").replace(/\s*$/, ""));
document.getElementById(dropdown_child).options.add(oOption);
}
document.getElementById(dropdown_child).options[selectedindex].selected=true;
return false;
}
});
}
else
{
document.getElementById(dropdown_child).options.length = 0;
document.getElementById(dropdown_child).options.add(new Option("--Select--", "0"));
}
}

2) Call The Following function on dropdown's selected index change:


 BindProducts('<%=ddlParent.ClientID%>', '<%=ddlChild.ClientID%>', '<%=Id%>')


3) Put the following code on the GetAjaxData.aspx page:

protected void Page_Load(object sender, EventArgs e)
{
ReturnDDLData(Convert.ToInt32(Request.QueryString["value"]));
}
private void ReturnDDLData(Int32 selectedId)
{
Response.Clear();
StringBuilder sbResponse = new StringBuilder();
Collection m_oCollection = new Collection();
m_oCollection.GetCollection(selectedId);
sbResponse.Append(string.Concat("--Select--", "|0", Environment.NewLine));
foreach (Product m_oItem in m_oCollection)
{
sbResponse.Append(string.Concat(m_oItem.Name, "|", m_oItem.ID.Value.ToString().Trim()) + Environment.NewLine);
}
Response.Output.Write(sbResponse.ToString().Substring(0, sbResponse.ToString().LastIndexOf(Environment.NewLine)));
Response.End();
}