Saturday, 22 August 2015

Default error page in web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
         <customErrors defaultRedirect="error.htm" mode="On" />
    </system.web>
</configuration>

Stack and Heap

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .

Stack:

Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Heap :

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.







Managed code and unmanaged code in .NET

Managed Code

The resource, which is with in your application domain is, managed code. The resources that are within domain are faster.

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.

Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

Unmanaged Code

The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

Unmanaged code can be unmanaged source code and unmanaged compile code.

Unmanaged code is executed with help of wrapper classes.



Applicants in a .NET interview should be able to point out that all Intermediate Language (IL) is managed code. (See Question 15 below.) One difference between managed and unmanaged code is that Visual Basic and C# compiler create managed code in .NET, but the only way to get unmanaged code is to write the application in C or C++. Since the .NET compiler creates managed code, this type of code does not depend on the target machine’s architecture. The Common Language Runtime (CLR) executes it, and not the operating system (OS). In contrast, unmanaged code is dependent on the architecture of the target machine. It is executed directly by the OS and directly compiled to native machine code.

MVC, MVP and MVVM Design Patterns

MVC Pattern

MVC stands for Model-View-Controller. It is a software design pattern which was introduced in 1970s. Also, MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from user interface (view). As a result maintenance and testing of the application become simpler and easier.
MVC design pattern splits an application into three main aspects: Model, View and Controller
  1. Model

    The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.
  2. View

    The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.
  3. Controller

    The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.
Today, this pattern is used by many popular framework like as Ruby on Rails, Spring Framework, Apple iOS Development and ASP.NET MVC.

MVP pattern

This pattern is similar to MVC pattern in which controller has been replaced by the presenter. This design pattern splits an application into three main aspects: Model, View and Presenter.
  1. Model

    The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
  2. View

    The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the presenter as the result. This also transforms the model(s) into UI.
  3. Presenter

    The Presenter is responsible for handling all UI events on behalf of the view. This receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate to each other’s by an interface.
    Also, presenter does not manage the incoming request traffic as controller.
This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit tests for their code-behind pages. This is also used with windows forms.

Key Points about MVP Pattern:

  1. User interacts with the View.
  2. There is one-to-one relationship between View and Presenter means one View is mapped to only one Presenter.
  3. View has a reference to Presenter but View has not reference to Model.
  4. Provides two way communication between View and Presenter.

MVVM pattern

MVVM stands for Model-View-View Model. This pattern supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.
  1. Model

    The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
  2. View

    The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI..
  3. View Model

    The View Model is responsible for exposing methods, commands, and other properties that helps to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.
This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.

Key Points about MVVM Pattern:

  1. User interacts with the View.
  2. There is many-to-one relationship between View and ViewModel means many View can be mapped to one ViewModel.
  3. View has a reference to ViewModel but View Model has no information about the View.
  4. Supports two-way data binding between View and ViewModel.

Sunday, 2 August 2015

Insert the data from view With MVC


Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/

     

        public ActionResult Test()
        {
            return View("Test");
        }



        [HttpPost]
        public ActionResult Test(ModelTest e, string Command)
        {
            if (Command == "Submit")
            {
                e.Insert();
                e.Reset();
               
            }

            return View("Test");
        }

    }

}

Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace MvcApplication1.Models
{
    public class ModelTest
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public int Phone_landline { get; set; }
        public int Mobile { get; set; }
        public string Relation { get; set; }

        public string  Insert()
        {
            //SqlConnection con = null;
            string result = "";
            try
            {
                string s = "Data Source=XXXX;Database=EmpDetails;Trusted_Connection=Yes;";
                //SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ToString());
                SqlConnection con=new SqlConnection(s);
                SqlCommand cmd = new SqlCommand("spcontacts", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Flage", "I");
                // i will pass zero to MobileID beacause its Primary .
                cmd.Parameters.AddWithValue("@Name", Name);
                cmd.Parameters.AddWithValue("@Address", Address);
                cmd.Parameters.AddWithValue("@Phone", Phone_landline);
                cmd.Parameters.AddWithValue("@Mobile", Mobile);
                cmd.Parameters.AddWithValue("@Relaction", Relation);
                con.Open();
                result = cmd.ExecuteScalar().ToString();
                return result;
            }
            catch
            {
                return result = "";
            }
            finally
            {
                //con.Close();
            }
        }

        public void Reset()
        {
            Name = string.Empty;
            Address = string.Empty;
            Phone_landline = Convert.ToInt16(string.Empty);
            Mobile = Convert.ToInt16( string.Empty);
            Relation = string.Empty;
        }

    }


}

View :

@model MvcApplication1.Models.ModelTest
@{
    ViewBag.Title = "Test";
}




<h2>Test</h2>
@using (Html.BeginForm())
{
<table><tr><td>Name</td><td>@Html.TextBoxFor(a=>a.Name)</td></tr>
<tr><td>Address</td><td>@Html.TextBoxFor(a=>a.Address)</td></tr>
<tr><td>LandLine No.</td><td>@Html.TextBoxFor(a=>a.Phone_landline)</td></tr>
<tr><td>Mobile/Cell</td><td>@Html.TextBoxFor(a=>a.Mobile)</td></tr>
<tr><td>Comments/Relations</td><td>@Html.TextBoxFor(a=>a.Relation)</td></tr>
<tr><td></td><td><input id="Submit1" type="submit" value="Submit" name="Command" /></td></tr>
<tr><td></td><td></td></tr></table>
}

Friday, 26 June 2015

AngularJS Architecture


AngularJS Module – Module in AngularJS is like a container. It can contain different parts of your application like – Controllers, Services, Filters, and Directives etc. You can have one or more than one module depending on how complex your application is. There are a couple of advantages of using Modules in AngularJS –
  • Bootstrapping of the application can be specified by module declaratively and hence they are easy to understand
  • Modules are reusable
  • Modules can be loaded in any order or even parallel because they delay execution
  • Testing is easier and faster as you need to load only those modules which are needed by the app.
Configuration – needed to inject the constants and providers into configuration blocks. Config block is executed as soon as the module loads. The routing configuration is done in the configuration. It can also be used to configure modules and add HTTP interceptors.
Routing – When you design a large application, you cannot build the entire application using a single controller or a single view. You will need multiple controllers and multiple views. In such situations, you will have to do a navigation between different views using routing.
Controller – Controllers contains the logic and share state. Controllers are in-charge of your application and build the models for the views and directives. You can create multiple controllers for your application. Controller also provide commands for the view to act upon using number of events.
Views – View is nothing but the information you want to render to the end users browser. A view is also called as AngularJS compiled DOM.
Directives - Directives are extensions to HTML. They extend HTML instead of manipulating HTML. AngularJS provides a number of directives out-of-box. For example - ng-app, ng-controller, ng-view, ng-repeat etc. You can also build your own custom directives.
$Scope – A $scope is the glue between a Controller and a View. The controller generates the Model on $scope. It acts as a ViewModel for the view
Services – Services play a vital role in AngularJS. It is a component in AngularJS to perform a specific job like –
  • Executing a reusable logic which can communicate over HTTP
  • Performing computation on an algorithm
  • To implement validation checks against data
  • To invoke the local store stored in a browser or manipulate cookies
  • Act as an abstraction layer between any external resource and application’s components
Two-Way Binding - AngularJS provides two-way data binding out-of-the-box. When model changes, the view reflects the changes without waiting for any specific event to be fired. Also, when view updates the model, the model gets updated automatically.



Sunday, 7 June 2015

AngularJS

AngularJS is a JavaScript framework

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>


The ng-app directive defines an AngularJS application.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-bind directive binds application data to the HTML view

The ng-init directive initializes application data.
The ng-repeat directive repeats an HTML element.

The ng-controller directive defines the application controller.
Example :

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p ng-bind="name"></p>
</div>
<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>


<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>


</body>
</html>

Saturday, 11 April 2015

Table Value Parameters and C#

Table Value Parameter Type


CREATE TYPE [dbo].[empname_tablevalue] AS TABLE(
[name] [varchar](max) NULL,
[salary] [int] NULL
)


Store Procedure 

Create  proc [dbo].[sptablevalues]( @f varchar(20), @tblemp empname_tablevalue readonly)
as 
begin 
if @f='L'
begin
select * from EmpName
end
if @f='I'
begin
insert into EmpName (Name,Salare) select name,salary from @tblemp;
select 'Successfully'
end
end

C#
protected void btnsave_Click(object sender, EventArgs e)
    {
        DataTable dt = tblempnameColumns();

        DataRow dr = dt.NewRow();
        dr["Name"] = txtFullname.Text;
        dr["Salary"] = txtsalary.Text;
        dt.Rows.Add(dr);

        BLClass _b = new BLClass();
        Info _I = new Info();
        _I._p_TableValue = dt;
        _b.InsertUser_TableValue(_I);

    }

    private DataTable tblempnameColumns()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Salary", typeof(int));
        return dt;
    }

BLClass

public class BLClass
{
public BLClass()
{
//
// TODO: Add constructor logic here
//
}

 public string InsertUser_TableValue(Info _I)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("sptablevalues", con);
        cmd.CommandType = CommandType.StoredProcedure;
        try
        {
            cmd.Parameters.AddWithValue("@tblemp", _I._p_TableValue);
            cmd.Parameters.AddWithValue("@f", "I");

            cmd.ExecuteNonQuery();

            con.Close();
            string i = "0";
            return i;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

}

Info Class

public class Info
{       
    
       private DataTable _TableValue;
        public DataTable _p_TableValue
        {
            get
            { return _TableValue; }
            set { _TableValue = value; }
        }
public Info()
{
}
}


Sunday, 11 January 2015

Difference between @@IDENTITY(),SCOPE_IDENTITY() and IDENT_CURRENT(‘tablename’)


SELECT @@IDENTITY() returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session, while it is not limited to the current scope. It will return the last identity value that is either explicitly created (creatd by any trigger or user defined function).

SELECT SCOPE_IDENTITY() returns the last IDENTITY value produced on a connection and within the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY  returns the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created (not includes the identity created by any trigger or user defined function).
SELECT IDENT_CURRENT(‘tablename’) returns the last IDENTITY value produced in a table. It does not depend on any session or scope, instead it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
More 

Difference between ListView and GridView

ListView
GridView
It was introduced with Asp.Net 3.5.
It was introduced with Asp.Net 2.0.
Template driven.
Rendered as Table.
Built-in supports for Data grouping.
Need to write custom code.
Built-in supports for Insert operation.
Need to write custom code.
Provides flexible layout to your data.
Need to write custom code.
Performance is fast is compared to GridView.
Performance is slow as compared to ListView.

Difference between GridView and DataGrid

GridView
DataGrid
It was introduced with Asp.Net 2.0.
It was introduced with Asp.Net 1.0.
Built-in supports for Paging and Sorting.
For sorting you need to handle SortCommand event and rebind grid required and for paging you need to handle the PageIndexChanged event and rebind grid required.
Built-in supports for Update and Delete operations.
Need to write code for implementing Update and Delete operations.
Supports auto format or style features.
This features is not supported.
Performance is slow as compared to DataGrid
Performance is fast as compared to GridView.


Cross-Page Posting in asp.net using c#

Page - 1



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Fullname:
        <asp:TextBox ID="txtFullname" runat="server"></asp:TextBox>
     
        <asp:Button ID="Button1" runat="server"   Text="Cross Page"
             PostBackUrl="~/Default2.aspx"/>
    </div>
    </form>
</body>
</html>

Page - 2



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>

</html>

Page - 2 .CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.PreviousPage != null)
        {
            TextBox txt = (TextBox)PreviousPage.FindControl("txtFullname");
            Label1.Text = txt.Text;
        
        }
    }
}

Cross page posting with Master page - ASP.NET 



            if (Page.PreviousPage != null)
            {
                var cp = PreviousPage.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
                TextBox txt1 = cp.FindControl("txtaddresse") as TextBox;
                //TextBox txt = (TextBox)PreviousPage.FindControl("ContentPlaceHolder1_txtaddresse");
                if (txt1.Text != null)
                {
                    string s = txt1.Text;
                }
            }