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