Wednesday, June 11, 2014

What is Asp.net MVC?

MVC stands for model-view-controller. MVC is a pattern for developing applications that are well architected, testable and easy to maintain. MVC-based applications contain:

  • Models: Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically generate HTML responses.
  • Controllers: Classes that handle incoming browser requests, retrieve model data, and then specify view templates that return a response to the browser.

Entity Framework Development Workflows

Entity Framework supports four basic development workflows. You can choose which one is appropriate for you based on following questions.

1. Do you have Existing Database? or
2. Are you going to create New Database?

New Database:

There are two approaches for New Database:

1. Model First
  • Create model in designer
  • Database created from model
  • Classes auto-generated from model
2. Code First
  • Define classes & mapping in code
  • Database created from defined classes
  • Use Migrations to evolve database

Existing Database:

There are two approaches for Existing Database:

1. Database First
  • Reverse engineer model in designer
  • Classes auto-generated from model
2. Code First
  • Define classes & mapping in code
  • Reverse engineer tools available



What is Entity Framework?

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database.

Entity Framework: Four Development Workflows

Tuesday, June 10, 2014

How to keep jQuery UI Accordion collapsed by default?

You can do that by setting attribute -> "active: false".

    <script>
        $(function () {
            $("#accordion").accordion({
                collapsible: true,
                active: false 
            });
        });        
    </script>

How to increase Height of accordion 100% in JQuery?

100% means height should be expanded based on height of the content. You can do that by following way.

    <script>
        $(function () {
            $("#accordion").accordion({
                collapsible: true,
                heightStyle: "content"

            });
        });        
    </script>

Monday, June 9, 2014

How to create ErrorHandling Module Using IHttpModule?

I am going to explain IHttpModule using an example here. Imagine that you don’t want to write error handling code in each and every page/class instead you want to create separate “Error Handling” module in your project without touching “Global.asax” file. You can do so by implementing “IHttpModule” interface. Following example shows you very simple code about handling error globally. I am attaching some html in beginning and End of the request. And also in between I am showing the error message occurred anywhere in the project. So here is the sample code.

Public Class ErrorHandlingModule
    Implements IHttpModule
     
    Public Sub Dispose() Implements IHttpModule.Dispose

    End Sub

    Private _ErrorMessage As String
    Public Property ErrorMessage() As String
        Get
            Return _ErrorMessage
        End Get
        Set(ByVal value As String)
            _ErrorMessage = value
        End Set
    End Property


    Public Sub Init(context As HttpApplication) Implements IHttpModule.Init

        'Adding handler for Error '
        AddHandler context.Error, _
            AddressOf Me.Application_Error

        'Adding Begin Request Handler '
        AddHandler context.BeginRequest, _
            AddressOf Me.Application_BeginRequest

        'Adding End Request Handler '
        AddHandler context.EndRequest, _
            AddressOf Me.Application_EndRequest


    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender,  _
            HttpApplication)
        Dim context As HttpContext = application.Context

        context.Response.Write("<h3><font color=red>" & _
                "ErrorHandlingModule: Beginning of Request" & _
                "</font></h3><hr/><br/><br/>")

    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        'Handling Error: This is just an example '
        'In real time, you have to log your error in database ' 
        'as well as send email to admin '
        Dim LastException As Exception = HttpContext.Current.Server.GetLastError
        If LastException IsNot Nothing Then
            If LastException.InnerException IsNot Nothing Then

                ErrorMessage = LastException.InnerException.Message

            End If
        End If

        'Clear Error after handling it '
        HttpContext.Current.Server.ClearError()

    End Sub
     
    Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender,  _
            HttpApplication)
        Dim context As HttpContext = application.Context



        context.Response.Write(ErrorMessage + "<br/><br/><hr/><h3/><font color=red>" & _
                "ErrorHandlingModule: End of Request</font></h3>")

    End Sub

End Class


Steps:
1. Create a class “ErrorHandlingModule” in “App_Code” folder of your project
2. Implement “IHttpModule” in this class. When you press enter button at the end of “IHttpModule”, It will implement two methods “Dispose() and Init()”.
3. In Init(), I have added three handlers “Error, BeginRequest, EndRequest”.
4. To catch all requests and error, you have to subscribe those in “Init” and create methods in this class.
5. I have created three methods “Application_BeginRequest”, ”Application_Error”, ”Application_EndRequest”.
6. In “Application_Error” Method, just for example, I have assigned error message to “ErrorMessage” property. I have created this property just for that.
7. Now, just to see how it works, I have created one .aspx page and its Page_Load event, I have thrown exception as follows:

Public Class Home
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Throw New Exception("This is test ERROR")

    End Sub

End Class


When you run this page, error will be caught by our ErrorHandlingModule and you can see the result as below. You can log any error in the database as well as you can send an email to admin.

Friday, June 6, 2014

How to increase maximum request length in web.config?

The default upload file size if 4MB. To increase it, please use this below section in your web.config

This code will allow file size upto 20MB.
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="20480" />
    </system.web>
</configuration>


Thursday, June 5, 2014

When and Why we need Interfaces in our Project? VB.Net

Today I will show you when and why we need to implement Interfaces. This is not something that you have to have in your project. There are some scenarios where you have to use Interfaces. I will give you two very simple but effective examples, which will give you a clear idea, when to use Interfaces in your project.

Before I give you basic scenarios, let me prepare the first platform. Here are 5 child classes and one parent class.

Public MustInherit Class Animal
    Public Property Legs As Integer
End Class
Public Class Cow
    Inherits Animal

    Public Property AverageMilkQuantity As Integer
 
End Class
Public Class Buffalo
    Inherits Animal

    Public Property AverageMilkQuantity As Integer

End Class
Public Class Camel
    Inherits Animal

    Public Property AverageMilkQuantity As Integer

End Class
Public Class Lion
    Inherits Animal

    Public Property MeatEatingQuantity As Integer

End Class
Public Class Tiger
    Inherits Animal

    Public Property MeatEatingQuantity As Integer

End Class

In above code, you can see parent class as “Animal” and 5 child classes which are inheriting parent class. Not all animals have the same properties. Some animals sub classes have different properties. For example, Dairy milk producer animals have different properties than meat eater animals.

Now our platform is ready. I will show you two scenarios.

Scenario no. 1:

        Dim animals As New List(Of Animal)

        Dim oCow As New Cow
        oCow.Legs = 4
        oCow.AverageMilkQuantity = 15

        Dim oBuffalo As New Buffalo
        oBuffalo.Legs = 4
        oBuffalo.AverageMilkQuantity = 20

        Dim oCamel As New Camel
        oCamel.Legs = 4
        oCamel.AverageMilkQuantity = 25

        Dim oTiger As New Tiger
        oTiger.Legs = 4
        oTiger.MeatEatingQuantity = 5

        Dim oLion As New Lion
        oLion.Legs = 4
        oLion.MeatEatingQuantity = 7

        animals.Add(oCow)
        animals.Add(oBuffalo)
        animals.Add(oCamel)
        animals.Add(oTiger)
        animals.Add(oLion)

        'For Milk Producer '
        For Each oAnimal As Animal In animals
            Dim MilkQuantity As Integer = 0 

            If TypeOf oAnimal Is Cow Then
                MilkQuantity = DirectCast(oAnimal, Cow).AverageMilkQuantity
                
            ElseIf TypeOf oAnimal Is Buffalo Then
                MilkQuantity = DirectCast(oAnimal, Buffalo).AverageMilkQuantity
                
            ElseIf TypeOf oAnimal Is Camel Then
                MilkQuantity = DirectCast(oAnimal, Camel).AverageMilkQuantity
                
            End If

        Next

In this code, you can see in the last “For each” loop, we have to repeat the same stuff again and again unnecessarily. To solve this problem, we will create an Interface. We can create an abstract class, but it is unnecessary because we are not going to write any kind of implementation code. So the best solution is to create an Interface. Here is the Interface, changed child classes and changed “For each” loop.

Public Interface IMilkProducer
    Property AverageMilkQuantity As Integer
End Interface
Public Class Cow
    Inherits Animal
    Implements IMilkProducer
     
    Public Property AverageMilkQuantity As Integer Implements IMilkProducer.AverageMilkQuantity
     
End Class
Public Class Buffalo
    Inherits Animal
    Implements IMilkProducer
     
    Public Property AverageMilkQuantity As Integer Implements IMilkProducer.AverageMilkQuantity
     
End Class
Public Class Camel
    Inherits Animal
    Implements IMilkProducer
     
    Public Property AverageMilkQuantity As Integer Implements IMilkProducer.AverageMilkQuantity
     
End Class
 'For Milk Producer '
For Each oAnimal As Animal In animals
     Dim MilkQuantity As Integer = 0
     
     If TypeOf oAnimal Is IMilkProducer Then
         MilkQuantity = DirectCast(oAnimal, IMilkProducer).AverageMilkQuantity
     End If

Next


Isn’t it great? It reduced number of code lines of "For each" loop and makes the code easy to use and maintainable. Interfaces are like “plug and play” instrument. You can create interfaces with closely related properties or methods. Classes have to implement those interfaces to make code easy to use and maintainable.

Scenario no. 2:

Now imagine that you want to manipulate some methods of particular group like “MilkProducer”. When somebody request “getMilkQuantity”, you want to put some logic and then you want to return “MilkQuantity”. How will you do that? Here is the simple code, which will solve this issue.

Public Class MilkProducer
    Dim objMP As IMilkProducer

    Sub New(ByVal oMilkProducer As IMilkProducer)
        objMP = oMilkProducer
    End Sub

    Public Function getMilkQuantity() As Integer

        'Her You can manipulate '
        If TypeOf objMP Is Cow Then
            'This is just an example '
            objMP.AverageMilkQuantity = 10
        End If

        Return objMP.AverageMilkQuantity

    End Function
End Class
'For Milk Producer '
 For Each oAnimal As Animal In animals
     Dim MilkQuantity As Integer = 0
     
     If TypeOf oAnimal Is IMilkProducer Then
          Dim mp As New MilkProducer(oAnimal)

          MilkQuantity = mp.getMilkQuantity
          
     End If

Next


Isn’t it cool? Let me know if you have any questions. I will try my best to provide answers to your queries. I hope this will help you understand when and why we need to create Intefaces.

Wednesday, June 4, 2014

Explain Interfaces in .Net

Interfaces define the properties, methods, and events that classes can implement. Interfaces allow you to define features as small groups of closely related properties, methods, and events; this reduces compatibility problems because you can develop enhanced implementations for your interfaces without jeopardizing existing code. You can add new features at any time by developing additional interfaces and implementations. Interfaces cannot contain any implementation code or statements associated with implementation code

Click here to see when and why we need to create Interfaces

There are several other reasons why you might want to use interfaces instead of class inheritance:

• Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

• Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.

• Interfaces are better in situations in which you do not have to inherit implementation from a base class.

• Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

Tuesday, June 3, 2014

How to resize images using IHttpHandler?

Today we will see how to resize Images with IHttpHandler. Let’s put Image controls with three different sized images. Image will be same, but only sizes will be different.

<asp:Image ID="img" runat="server" ImageUrl="~/Desert.jpg?size=64" />
<asp:Image ID="Image1" runat="server" ImageUrl="~/Desert.jpg?size=164" />
<asp:Image ID="Image2" runat="server" ImageUrl="~/Desert.jpg?size=364" />

Here, you can see, I have passed sizes in querystring. Size=64 means I am requesting 64x64 size of that image. Now the next step is to make “ResizeImageHandler”. I am resizing image on the fly, means not storing anywhere. Just resizing image and throwing back to the response.
Note: requested image "Desert.jpg" must exist on your server, otherwise it will throw exception. I haven't handled exception because this is just example to understand IHttpHandler

Imports System.Drawing
Imports System.IO

Public Class ResizeImageHandler
    Implements IHttpHandler


    Public ReadOnly Property IsReusable As Boolean 
    Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property

    Public Sub ProcessRequest(context As HttpContext) 
    Implements IHttpHandler.ProcessRequest
         
        Dim req As HttpRequest = context.Request
        Dim res As HttpResponse = context.Response

        'Get the image file path '
        Dim path As String = req.PhysicalPath

        'Get the Image '
        Dim img As Image = Image.FromFile(path)

        'Image converter '
        Dim converter As New ImageConverter

        Dim s As Size
        If req.QueryString("size") IsNot Nothing Then

            'Get the size to Resize original image '
            Dim sz As String = req.QueryString("size")

            s = New Size(sz, sz)

            'Resize the original image to requested size '
            Dim bm As Bitmap = New Bitmap(img, s)

            'Convert to Image '
            Dim fImg As Image = bm

            'Write the Resized Image to browser '
            res.BinaryWrite(converter.ConvertTo(fImg, GetType(Byte())))
        Else

            'Write the original image '
            res.BinaryWrite(converter.ConvertTo(img, GetType(Byte())))
        End If
             
End Sub
 
End Class

Now, after creating class which implements IHttpHandler, we have to register it. I am using IIS 7 with Integrated Mode, so I have registered as below. There are different ways to register the Handler based on which IIS you are using and in which mode (classic/Integrated).
To know, which registration method you have to use, read this MSDN Article

<configuration>
  <system.webServer>
 <handlers>
    <add name="ResizeImageHandler" verb="GET"
           path="*.jpg"
           type="ResizeImageHandler"
           resourceType="Unspecified" />

 </handlers>
  </system.webServer>
</configuration>

Now it’s time to run the page with above Image server controls. After running that page, you will see following output.

Monday, June 2, 2014

HTTP Handlers and HTTP Modules Overview

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

Click here to see IHttpHandler Example Code

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

Click here to see IHttpModule Example Code

Scenarios:

Typical uses for custom HTTP handlers include the following:

RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.

Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.

Typical uses for HTTP modules include the following:

Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.

Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.


Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.

Features:

HTTP handler and module features include the following:

• The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.

• The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.

• Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.

• Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change. For more information, see Moving an ASP.NET Application from IIS 6.0 to IIS 7.0.

• Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.

• In IIS 7.0, the request pipeline is integrated with the Web server request pipeline. HTTP modules can be used for any request to the Web server, not just ASP.NET requests.

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...