Thursday 11 February 2016

What is Httphandler and HttpModule in Asp.Net ?





ASP.NET handles all the HTTP requests coming from the user and generates the appropriate response for it. ASP.NET framework knows how to process different kind of requests based on extension, for example, It can handle request for .aspx, .ascx and .txt files, etc. When it receives any request, it checks the extension to see if it can handle that request and performs some predefined steps to serve that request.
ASP.NET default handlers:


  • Page Handler (.aspx) - Handles Web pages
  • User Control Handler (.ascx) - Handles Web user control pages
  • Web Service Handler (.asmx) - Handles Web service pages
  • Trace Handler (trace.axd) - Handles trace functionality


Now as a developer, we might want to have some of our own functionality plugged in. We might want to handle some new kind of requests or perhaps we want to handle an existing request ourselves to have more control on the generated response, for example, we may want to decide how the request for .jpg or .gif files will be handled. Here, we will need an HTTPHandler to have our functionality in place.



Example :

public class MyHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (context.Request.RawUrl.Contains(".cspx"))
            {
              
                string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");
                context.Server.Transfer(newUrl);
            }
         }

      }



Now we need to add our handler in webConfig file to use it.

<httpHandlers>
    <add verb="*" path="*.cspx" type="MyHandler "/>
</httpHandlers>





What is HTTP module:

Help in processing of page request by handing application events , similar to what global.asax does. A request can pass through many HTTP modules but is being handled by only one HTTP handlers.



Use of HTTP Modules:

ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc.
<add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file.


<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"/>
</httpModules>



Here I just explained about Httphandler and HttpModule. I hope its useful to readers. Please send your comments and feedback. Thank You.













Wednesday 10 February 2016

How to implement Dispose Method? Differences between Dispose and Finalize methods ?



It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessar

You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.

A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has destructor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method.

Code Example:-

public class MyClass : IDisposable
    {
        private bool disposed = false;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        //Implement Dispose method to dispose resources
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // TO DO: clean up managed objects
                    Console.WriteLine("Managed code has been disposing");
                    Console.ReadKey();
                }

                // TO DO: clean up unmanaged objects
                Console.WriteLine("UnManaged code has been disposing");
                Console.ReadKey();
                disposed = true;
            }
        }
    }
    class Program
    {
        public static void Main(String[] agues)
        {
            MyClass mc = new MyClass();
            mc.Dispose();
            Console.WriteLine("All resources are released from memory.");
            Console.ReadKey();
        }
         
    }



 Output:-


  



Dispose() Method:-

  • It is used to free unmanaged resources like files, database connections etc. at any time.
  • Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface.
  • It belongs to IDisposable interface.
  • It's implemented by implementing IDisposable interface Dispose() method.
  • There is no performance costs associated with Dispose method.

Finalize() Method:-

  • It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed.
  • Internally, it is called by Garbage Collector and cannot be called by user code.
  • It belongs to Object class.
  • It's implemented with the help of destructor in C++ & C#.
  • There is performance costs associated with Finalize method since it doesn't clean the memory immediately and called by GC automatically.





Monday 8 February 2016

To prevent Cut, Copy and Past in ASP.NET using Jquery functions .




1.  If you don't want to alert any message then just put  below property in your control to prevent Copy, Cut and Past 

oncopy="return false"

onpaste="return false"
oncut="return false"

Example:-
<asp:TextBox ID="txt" runat="server" oncopy="return false" onpaste="return false" oncut="return false"></asp:TextBox>




2.In JavaScript you can use below code

<script language="javascript" type="text/javascript">
     function DisableCopyPaste(e) {
         // Message to display
         var message = "Cntrl key/ Right Click Option disabled";
         // check mouse right click or Ctrl key press
         var kCode = event.keyCode || e.charCode;
         //FF and Safari use e.charCode, while IE use e.keyCode
         if (kCode == 17 || kCode == 2) {
             alert(message);
             return false;
         }
     }
</script>


 <asp:TextBox ID="txtId" runat="server" onKeyDown="return DisableCopyPaste(event)"onMouseDown="return DisableCopyPaste (event)"></asp:TextBox>


3.In JQuery you can use below code


<script lang="javascript" type="text/javascript">

         $(document).ready(function () {
             $('#<%=txt.ClientID%>').bind('copy paste cut', function (e) {
                 e.preventDefault(); //disable cut,copy,paste
                 alert('cut,copy & paste options are disabled !!');
             });
         });
       </script>

 <asp:TextBox ID="txt" runat="server"></asp:TextBox>


In the .bind(param1, param2) function first parameter you have to mention the name of property on which you want to execute function and in second parameter you write that function.



4. To check existence of substring in the string

    var str = $('#<%=txt.ClientID%>').val();
                 if (str.indexOf("Hello") >= 0) {
                     alert('Contains hello');
                 }


5. To change a string from Lower to Upper and Upper to Lower case

    var str = $('#<%=txt.ClientID%>').val();

                 alert(str.toLowerCase());

    var str = $('#<%=txt.ClientID%>').val();
                 alert(str.toUpperCase());


6. To check a numeric value 

    var str = $('#<%=txt.ClientID%>').val();

              $.isNumeric(str);

  Note- Its return boolean value.
  For numeric       - true
  For None numeric  - false





Sunday 7 February 2016

What is JQuery with a sample example ?



jQuery is a JavaScript library. It can:


  • Make your JavaScript code shorter, faster and cross browser.
  • Manipulate your HTML, like showing or hiding something from the page.
  • Handles events – it can do something when a user click a button or any other activity a user can do with a mouse.
  • Animation – for example make a part of your page fade in, fade out or just simply make something move.
  • AJAX – do a server request without refreshing your whole web page.

Code example:-


javaScript

   <script lang="javascript" type="text/javascript">
         $(document).ready(function () {
             $('#<%=Button1.ClientID%>').click(function () {

                 // this how to get text box value on button click
                 var txt = $('#<%=txt.ClientID%>').val();
                 // This how to set value to a label
                 $('#<%=lbl.ClientID%>').text(txt);
                 // This how make font bold os text
                 $('#<%=lbl.ClientID%>').css({'font-weight': 'bold', 'color':'red'});

                 $('#div1').css('background', 'yellow');
                 return false;
             });
           
         });

       </script>



HTML

     <div>   
        <Center>
        <table style="width: 60%">
            <tr>
            <td><asp:TextBox ID="txt" runat="server"></asp:TextBox></td>
            </tr>
             <tr>
             <td><asp:Label ID="lbl" runat="server" Text=""></asp:Label></td>
             </tr>
             <tr>
             <td> <asp:Button ID="Button1" runat="server" Text="Click me Now" /></td>
              </tr>
        </table>
            <div id="div1">
             <p> This is paragraph of  his might seem funny
                 because writing this jQuery tutorial
                 beginners in this blog is a little bit late.</p>

            </div>
        </Center>
    </div>



Before button click











After Entering some text and button click





















I hope its use for bignner to just undersatnd how its works.