Thursday, October 8, 2015

Partial View

Intorduction

Hope you all aware concept of UserControl in asp.net which is use for making common things in one control and use everywhere in web application.

Similarly in MVC we have Partial View which renders the view content.Meaning it helps you to reduce your code and also avoid duplication.

For example if you have Address Control which includes address related controls and you have to put address in many place in your web application. So here you can make Partial view which reduce your time and duplication.

Create Partial View

Below are few steps to create Partial view and How to use of it :

Step 1 : To create partial view go to your solution and go to view folder and right click on View folder.and follow below image.

Add New Partial View

Step 2 :  Click on view and it will open below window, Now in that you need to tick "Create Partial view" and you have now same view as normal view but it will created as a partial view.


Now if you want to reuse partial view then its good habit to put in "Shared" folder under Views folder so you can view in whole application

Step 3 :  To call and render partial view you can use below two methods.Below are two method to call partial view


  1.   
  2.     @Html.Partial("PartialView")  
 
  •  
  •   
  •     @{  
  •         Html.RenderPartial("PartialView");  
  •     }  

  • @Html.Partial - This method renders the view as an HTML-encoded string. So using this method we can store result in string.

    @Html.RenderPartial - This method is written directly into the HTTP response, it means that this method used the same TextWriter object as used by the current view. This method returns nothing.

    Step 4 - Render Partial view from controller file using below approach:

    1. public ActionResult PartialView()  
    2. {  
    3.     return PartialView();  
    4. }  
      

    Using this way you can create Partial view and render and call your view.You can also pass the model to the partial view for strongly binding same as we pass in normal view.







    Tuesday, October 6, 2015

    Entity Framework - Lazy,Eager, Explicit loading

    Entity Framework

    There are several ways that the Entity Framework can load related data into the navigation properties of an entity:

    Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. These results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved.



    Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the Include method.




    Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace Collection(x => x.Courses) with Reference(x => x.Administrator).)




    Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
    In general, if you know you need related data for every entity retrieved, eager loading offers the best performance, because a single query sent to the database is typically more efficient than separate queries for each entity retrieved. For example, in the above examples, suppose that each department has ten related courses. The eager loading example would result in just a single (join) query. The lazy loading and explicit loading examples would both result in eleven queries.
    On the other hand, if you need to access an entity's navigation properties only infrequently or only for a small portion of a set of entities you're processing, lazy loading may be more efficient, because eager loading would retrieve more data than you need. Typically you'd use explicit loading only when you've turned lazy loading off. One scenario when you might turn lazy loading off is during serialization, when you know you don't need all navigation properties loaded. If lazy loading were on, all navigation properties would all be loaded automatically, because serialization accesses all properties.
    The database context class performs lazy loading by default. There are two ways to turn off lazy loading:

    • For specific navigation properties, omit the virtual keyword when you declare the property. 
    • For all navigation properties, set LazyLoadingEnabled to false. 

    Lazy loading can mask code that causes performance problems. For example, code that doesn't specify eager or explicit loading but processes a high volume of entities and uses several navigation properties in each iteration might be very inefficient (because of many round trips to the database), but it would work without errors if it relies on lazy loading. Temporarily disabling lazy loading is one way to discover where the code is relying on lazy loading, because without it the navigation properties will be null and the code will fail.

    Identity Framework Basic

    Identity Framework

    Asp.net team has introduce new Identity Framework which replaced the old membership framework.Identity has more features then before.

    In Today's world everyone want to authenticate web using third party social services like Facebook,Twitter and LinkedIn.Using Identity you can easily integrate third party social login into your web applications.

    Before start learning features of Identity install the sample project using below command

    PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre 

    In sample project they have given all basic things like login/logout/Forgot Password/Email Confirmation and all other basic things.

    Identity Features


    • Account Lockout: Using Identity we can configure the account lockout attempt so after failed attempt user account is locked for certain period. We can configure the duration and also we can set the how many time user can try.
    • Account Confirmation: ASP.NET Identity allows us to confirm the account by confirming the email of the user. 
    • Two-Factor Authentication via email or SMS messaging, functionally similar to that used by Google, Microsoft, and others.We can also enable/disable this 2FA after login.  I will discuss more about two factor later on.
    • Improved support for Social log-ins. We can easily integrate third party logins in our web application. I will explain more on this with example 
    Below are the main component of Identity
    1. User 
    2. Role
    3. User Manager
    4. Role Manager
    5. Authentication Manager
    6. Entity Framework DBContext
    I will explain more in separate blog about each and every feature with example.









    Monday, February 8, 2010

    Chaining Methods - A Simple Scenario

    Assuming that you are interested in training animals, let us start with a simple ITrainable interface. :)

    public interface ITrainable
    {
    ITrainable Train(string skill);
    ITrainable Do(string skill);
    }

    Well, nothing fancy there. Let us go ahead and create a Dog Class, which implements this interface. The only interesting piece you may find in the Dog class is, all methods are returning a type of ITrainable. As long as our Dog class implements ITrainable, we can return 'this', i.e the current Dog Instance.

    public class Dog : ITrainable
    {
    public string Name { get; set; }
    public List Skills { get; set; }

    public Dog(string name)
    {
    Console.WriteLine();
    Console.WriteLine("Dog " + name +
    " created");

    Name = name;
    Skills = new List();
    }
    public ITrainable Train(string skill)
    {
    Console.WriteLine("Dog " + Name +
    " learned " + skill);
    this.Skills.Add(skill);
    return this;
    }

    //Let us ask the dog to perform this skill
    public ITrainable Do(string skill)
    {
    if (Skills.Contains(skill))
    Console.WriteLine("Dog " + Name +
    " is doing " + skill);
    else
    Console.WriteLine("Dog " + Name +
    ": Don't know how to " + skill);

    return this;

    }


    Now, we are ready to train our Dog fluently.

    //Train one dog, Hope your name is not Bobby ;)
    var dog = new Dog("Bobby");
    dog.Train("Running").Train("Eating")
    .Do("Running").Do("Eating");



    As you can see, we are chaining the method calls, because in each call, we are returning an object of type ITrainable. You'll see what Bobby is doing in the console

    Dog Bobby created
    Dog Bobby learned Running
    Dog Bobby learned Eating
    Dog Bobby is doing Running
    Dog Bobby is doing Eating

    Friday, February 5, 2010

    Exporing IIS

    Hi All

    Please go through the below URL

    http://www.codeproject.com/KB/aspnet/ExploringIIS.aspx

    Concepts of ViewState

    Introduction

    The aim of this article is to clarify the question that many new Web developers might have about ViewState.

    Why do some Web controls like Textbox retain values even after disabling the ViewState while others do not?

    Background

    Let’s build a simple Web application to examine how ViewState works.

    Create a blank Web project and paste the code given below in the page:



    script runat="server">
    
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Handles btnSubmit.Click
    lblMessage.Text = "Goodbye everyone"
    lblMessage1.Text = "Goodbye everyone"
    txtMessage.Text = "Goodbye everyone"
    txtMessage1.Text = "Goodbye everyone"
    End Sub
    script>
    <form id="form1" runat="server">

    <asp:Label runat="server" ID="lblMessage" EnableViewState =true
    Text="Hello World"></asp:Label>
    <asp:Label runat="server" ID="lblMessage1" EnableViewState =false
    Text="Hello World"></asp:Label>
    <asp:Textbox runat="server" ID="txtMessage" EnableViewState =true
    Text="Hello World"></asp:Textbox>
    <asp:Textbox runat="server" ID="txtMessage1" EnableViewState =false
    Text="Hello World"></asp:Textbox>
    <br />
    <asp:Button runat="server"
    Text="Change Message" ID="btnSubmit"></asp:Button>
    <br />
    <asp:Button ID="btnEmptyPostBack" runat="server" Text="Empty Postback"></asp:Button>
    </form>


    The page rendered will have four controls (two text boxes and two labels) initialized with Hello World and two buttons.

    Click on the Change Message button, the value in controls will be changed to Goodbye Everyone.

    Now click on the Empty Postback button.

    The expected result is, after postback the Textbox (txtMessage) and label (lblMessage) with EnableViewState = false should not retain the value and hence the value should be Hello world, while the controls with ViewState enabled (txtMessage1 and lblMessage1) should retain the value and hence value should be Goodbye world.

    But this does not happen. Both the Textbox will maintain the value irrespective of whether ViewState is enabled or disabled, but in the case of label control if ViewState is disabled, the value we changed programmatically is not retained.



    Let's examine why this happens?

    Page LifeCycle and ViewState

    In page life cycle, two events are associated with ViewState:

    • Load View State: This stage follows the initialization stage of page lifecycle. During this stage, ViewState information saved in the previous postback is loaded into controls. As there is no need to check and load previous data, when the page is loaded for the first time this stage will not happen. On subsequent postback of the page as there may be previous data for the controls, the page will go through this stage.
    • Save View State: This stage precedes the render stage of the page. During this stage, current state (value) of controls is serialized into 64 bit encoded string and persisted in the hidden control (__ViewState) in the page.
    • Load Postback Data stage: Though this stage has nothing to do with ViewState, it causes most of the misconception among developers. This stage only happens when the page has been posted back. ASP.NET controls which implement IPostBackEventHandler will update its value (state) from the appropriate postback data. The important things to note about this stage are as follows:
    1. State (value) of controls are NOT retrieved from ViewState but from posted back form.
    2. Page class will hand over the posted back data to only those controls which implement IPostBackEventHandler.
    3. This stage follows the Load View State stage, in other words state of controls set during the Load View State stage will be overwritten in this stage.

    Answers

    Now with the above information, let us try to answer the question:

    Why some controls retain values even after disabling the ViewState while others do not?

    The answer is Controls which implements IPostBackEventHandler like Textbox, Checkbox, etc. will retain the state even after disabling the viewstate. The reason is during the Load Postback Data stage, these controls will get state information from Posted back form.

    But controls like label which do not implement IPostBackEventHandler will not get any state information from posted back data and hence depend entirely on viewstate to maintain the state.

    Conclusion

    In this article, we examined how the ViewState of control is persisted during the life cycle of page and why some controls maintain the state even if the ViewState is disabled. Hope the information provided here is useful.