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;

        }

    }