Sunday, 29 September 2013

What is ASP.Net MVC And its Advantages?

In this post,I am going to explain you the whole robust architecture of the MVC and why MVC is so powerful that every company switch from ASP.Net Web Forms to ASP.Net MVC.

MVC(Model View Controller)

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

    MVC design pattern:-


    before Explaining this image ,i want to explain you three most important terms MODEL,VIEW, and CONTROLLER.

    1.Models-Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.

                 In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.

    2.Views-Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.

    3.Controller-Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.



    Advantages of ASP.Net MVC

    The ASP.NET MVC framework offers the following advantages:
    • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
    • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
    • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure
    • It provides better support for test-driven development (TDD).
    • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

    Friday, 27 September 2013

    Tricks for generating SQL statements in Excel



    Tricks for generating SQL Statements ,Mainly Insert ,Update in Excel for various data import scenarios?


    This is one of the very powerful feature of the excel ,suppose of you have very large amount of data stored in excel sheet.
    Now you want to store that data into DataBase Table,for that you have to use this feature of the Excel .

    I am giving you the example of it.

    ex.
    1.CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")
    -->here the c2 and c3 represent the respective column we need in our query.
    2.=CONCATENATE("UPDATE ProfileData SET PrependUsername = '",A1, "' WHERE Username = '", B1, "'")
    -->this is also work same for update query.
    for graphical example see the images.

    Thursday, 26 September 2013

    ASP.Net MVC-Custom Razor View Engine


    In this post you will learn how can you customize the Razor View engine 

    Before reading this post, I expect you guys have some knowledge of ASP.Net  MVC.


    • Removing All the View Engines & registering the Razor Engine
    Open the Global.asax file and write this code in the Application_Start,this function calls first when run the Application.

    protected void Application_Start() 
    {

    //Remove All View Engine including Webform and Razor
    ViewEngines.Engines.Clear();

    //Register Razor View Engine
    ViewEngines.Engines.Add(new RazorViewEngine());

    //Other code is removed for clarity
    }

    After removing the Web Form and other View engine as you noticed that Razor View engine looks up the C# views as shown below.
    Now run the Application,you get this error on the browser after running the application.




    As you know MVC is highly extensible hence you can completely replace the Razor view engine with a new custom razor engine. by doing so, this will slightly improve your application performance.


    • Custom C# Razor View Engine
    1. public class CSharpRazorViewEngine : RazorViewEngine
    2. {
    3. public CSharpRazorViewEngine()
    4. {
    5. AreaViewLocationFormats = new[]
    6. {
    7. "~/Areas/{2}/Views/{1}/{0}.cshtml",
    8. "~/Areas/{2}/Views/Shared/{0}.cshtml"
    9. };
    10. AreaMasterLocationFormats = new[]
    11. {
    12. "~/Areas/{2}/Views/{1}/{0}.cshtml",
    13. "~/Areas/{2}/Views/Shared/{0}.cshtml"
    14. };
    15. AreaPartialViewLocationFormats = new[]
    16. {
    17. "~/Areas/{2}/Views/{1}/{0}.cshtml",
    18. "~/Areas/{2}/Views/Shared/{0}.cshtml"
    19. };
    20. ViewLocationFormats = new[]
    21. {
    22. "~/Views/{1}/{0}.cshtml",
    23. "~/Views/Shared/{0}.cshtml"
    24. };
    25. MasterLocationFormats = new[]
    26. {
    27. "~/Views/{1}/{0}.cshtml",
    28. "~/Views/Shared/{0}.cshtml"
    29. };
    30. PartialViewLocationFormats = new[]
    31. {
    32. "~/Views/{1}/{0}.cshtml",
    33. "~/Views/Shared/{0}.cshtml"
    34. };
    35. }
    36. }


    • Regisering the C# Razor View Engine
    1. protected void Application_Start()
    2. {
    3. //Remove All View Engine including Webform and Razor
    4. ViewEngines.Engines.Clear();
    5. //Register C# Razor View Engine
    6. ViewEngines.Engines.Add(new CSharpRazorViewEngine());
    7. //Other code is removed for clarity
    8. }



    Tuesday, 24 September 2013

    How to publish ASP.Net website on IIS

    Steps to publish website on IIS.

    1. Publish your site on some folder at specific folder in some disk drive.

    2. Now Right click on you folder-> go to properties-> Security->edit option->add option->advance-> find now.

    3. Now here you have to choose both IIS_USRS and IUSR (this is imp you have to give permission to both iis users and iuser), click ok.

    4. Open iis and add your web site, make sure you have selected correct version of your website in application pool while adding your website.

    5. if you are giving alias to localhost name  then you have to edit hosts file to do this C:->Windows->System32->drivers->etc->hosts.

    Monday, 23 September 2013

    StringBuilder in C#

    Once created a string cannot be changed. A StringBuilder can be changed as many times as necessary. It yields astonishing performance improvements. It eliminates millions of string copies. And in certain loops it is essential.

    Example

    As an introduction, this program shows how the StringBuilder type is used to build up a larger buffer of characters. You can call the Append method on the StringBuilder instance to add more and more data.
    Program that uses string builder C#
    using System;
    using System.Text;
    
    class Program
    {
        static void Main()
        {
     StringBuilder builder = new StringBuilder();
     // Append to StringBuilder.
     for (int i = 0; i < 10; i++)
     {
         builder.Append(i).Append(" ");
     }
     Console.WriteLine(builder);
        }
    }
    
    OUtPut
    
    0 1 2 3 4 5 6 7 8 9
    
    

    Example 2

    Next let's look at some of the essential methods on the StringBuilder type in the base class library. The methods shown here will allow you to use it effectively in many programs, appending strings and lines.
    Note:This example does not show a loop, and it is not ideal as a program, but it is for demonstration purposes.
    Program 2 [C#]
    
    using System;
    using System.Text;
    using System.Diagnostics;
    
    class Program
    {
        static void Main()
        {
     // 1.
     // Declare a new StringBuilder.
     StringBuilder bilder = new StringBuilder();
    
     // 2.
     builder.Append("The list starts here:");
    
     // 3.
     builder.AppendLine();
    
     // 4.
     builder.Append("1 cat").AppendLine();
    
     // 5.
     // Get a reference to the StringBuilder's buffer content.
     string innerString = builder.ToString();
    
     // Display with Debug.
     Debug.WriteLine(innerString);
        }
    }
    
    Output
    
    The list starts here:
    1 cat

    Rename Table Name,Column name in sqlserver 2008

    I often get requests from blog reader for T-SQL script to rename database table column name or rename table itself.
    Here is a video demonstrating the discussion
    The script for renaming any column :
    sp_RENAME 'TableName.[OldColumnName]' '[NewColumnName]''COLUMN'
    The script for renaming any object (table, sp etc) :
    sp_RENAME '[OldTableName]' '[NewTableName]'
    This article demonstrates two examples of renaming database object.
    1. Renaming database table column to new name.
    2. Renaming database table to new name.
    In both the cases we will first see existing table. Rename the object. Test object again with new name.

    1. Renaming database table column to new name.
    Example uses AdventureWorks database. A small table with name “Table_First” is created. Table has two fields ID and Name.

    Now, to change the Column Name from “Name” to “NameChange” we can usecommand:
    USE AdventureWorks
    GO
    sp_RENAME 'Table_First.Name''NameChange'COLUMN'GO
    2.Renaming database table to new name.
    We can change the table name too with the same command.
    sp_RENAME 'Table_First''Table_Last'GO

    Saturday, 21 September 2013

    ASP.Net MVC DropdownList HTML Helper

    I have seen many developers who are still confused about the Dropdownlist HTML helper in MVC.


    Syntax:-

    @Html.DropDownList("dList")

    this is the basic Syntax for Dropdownlist.

    There are so many constructors used for Dropdownlist.

    1.      @Html.DropDownList("ddlDropDown", new List<SelectListItem>
                         {
                           new SelectListItem{ Text="Zero", Value = "0" },
                             new SelectListItem{ Text="One", Value = "1" },
                               new SelectListItem{ Text="Two", Value = "2" },
                                 new SelectListItem{ Text="Three", Value = "3" },
                                     new SelectListItem{ Text="Four", Value = "4" }
                         }
                       )

    The output of this Dropdownlist :-

















    If you want to show optional option in the dropdownlist then you have to add an optional value in this syntax :-
    @Html.DropDownList("ddlDropDown", new List<SelectListItem>
                         {
                           new SelectListItem{ Text="Zero", Value = "0" },
                             new SelectListItem{ Text="One", Value = "1" },
                               new SelectListItem{ Text="Two", Value = "2" },
                                 new SelectListItem{ Text="Three", Value = "3" },
                                     new SelectListItem{ Text="Four", Value = "4" }
                         },"Select Value"
                       )

    OUTPUT:-



    2.    @Html.DropDownList("ddlServicePlan", new SelectList(@Model.Plans, "Value", "Text"),"Select Value")

            public List<ListItem> Plans
            {
                get
                {
                    List<ListItem> items = new List<ListItem>
                         {
                              new ListItem{ Text="Zero", Value = "0" },
                               new ListItem{ Text="One", Value = "1" },
                                 new ListItem{ Text="Two", Value = "2" },
                                    new ListItem{ Text="Three", Value = "3" },
                                        new ListItem{ Text="Four", Value = "4" },
                                             
                         };

                    return items;
                }
            }

    we define this Plans property in Any model.











    Nth highest salary of a employee



    SQL SERVER – Query to Retrieve the Nth Maximum Value


    Replace Employee with your table name, and Salary with your column name. Where N is the level of Salary to be determined.
    SELECT  * FROM Employee E1 
    WHERE (N-1) = (SELECT COUNT(DISTINCT(E2.Salary))
    FROM Employee E2WHERE E2.Salary > E1.Salary)

    In the above example, the inner query uses a value of the outer query in its filter condition meaning; the inner query cannot be evaluated before evaluating the outer query. So each row in the outer query is evaluated first and the inner query is run for that row.
    here N is any +ve  integer number.

    Friday, 20 September 2013

    SQL Server 2008 Cast and Convert Function

    One day I am writing a simple query where i have to append two columns value in a single column but both the columns have different data type.

    And then I search the solution of it.its very simple.

    By using Convert and cast function we can convert the value into another datatype easily :)


    so here are the example of these two interesting functions.


    Cast() Function
    The Cast() function is used to convert a data type variable or data from one data type to another data type. The Cast() function provides a data type to a dynamic parameter (?) or a NULL value.
    Syntax
    CAST ( [Expression] AS Datatype)

    The data type to which you are casting an expression is the target type. The data type of the expression from which you are casting is the source type.
    Example
    DECLARE @A varchar(2)
    DECLARE @B varchar(2)
    DECLARE @C varchar(2)
    set @A=25
    set @B=15
    set @C=33
    Select CAST(@A as int) + CAST(@B as int) +CAST (@C as int) as Result

    Cast-function-output-in-sqlserver.jpg

    Example
    DECLARE @Z char(30)
    SELECT @Z=current_timestamp
    select CAST (@Z as date) as result
    OUTPUT

    Cast-function-with-date-datatype-in-sqlserver.jpg

    Convert() Function

    When you convert expressions from one type to another, in many cases there will be a need within a stored procedure or other routine to convert data from a datetime type to a varchar type. The Convert function is used for such things. The CONVERT() function can be used to display date/time data in various formats.
    Syntax
    CONVERT(data_type(length), expression, style)
     Style - style values for datetime or smalldatetime conversion to character data.  Add 100 to a style value to get a four-place year that includes the century (yyyy).
    Example
    In this example we take a style value 108 which defines the following format:
    hh:mm:ss
    Now use the above style in the following query:
    select convert(varchar(20),GETDATE(),108)

    OUTPUT
    convert-function--in-sqlserver.jpg
    Example
    In this example we use the style value 107 which defines the following format:
    Mon dd, yy
    Now use that style in the following query:
    select convert(varchar(20),GETDATE(),107)

    OUTPUT
    convert-function--example-in-sqlserver.jpg
    Example
    In this example we see different style values which defines the following format.
    SELECT CONVERT(VARCHAR(15),GETDATE(),6)
    go
    SELECT CONVERT(VARCHAR(16),GETDATE(),106)
    go
    SELECT CONVERT(VARCHAR(24),GETDATE(),113)
    OUTPUT
    convert-function-with-different-value-in-sqlserver.jpg