April 25, 2016

Difference between WCF and Web API and WCF REST and Web Service

Web Service
It is based on SOAP and return data in XML form.
It supports only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.
WCF
It is also based on SOAP and return data in XML form.
It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.
It can be hosted with in the application or on IIS or using window service.

http://www.wcftutorial.net/Home.aspx

WCF Rest
To use WCF as WCF Rest service you have to enable webHttpBindings.
It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
It support XML, JSON and ATOM data format.
Web API
This is the new framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
Unlike WCF Rest service, it use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
It can be hosted within the application or on IIS.
It is light weight architecture and good for devices which have limited bandwidth like smart phones.
Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
To whom choose between WCF or WEB API
Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.
RestWebService
HttpGet
HttpPost
HtttpPut
HttpDelete

March 8, 2016

code shortcut



 ClassA x = new ClassA();
ClassA x  ie x is variable of Class A

New ClassA()
This constructor does nothing except set the memory to its default values. The default constructor is public.

http://anil-businessanalyst.weebly.com/domain-knowledge.html

call method

DataTable dtCustomer= new ClsCustomerDAL().LoadCustomers();


using System;
public class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal called");
    }
    public virtual void method()
    {
        Console.WriteLine("common method called from animal");
    }
}
public class Bird : Animal
{
    public Bird()
    {
        Console.WriteLine("Bird called");
    }
    public new void method()
    {
        Console.WriteLine("special method called from bird");
    }
    public void method1()
    {
        Console.WriteLine("BM1");
    }
}

class Program
{
    static void Main(string[] args)
    {
        //Animal obj = new Bird();// what is use of it?
        new Bird().method();
        //obj.method();
        Console.Read();
    }
}


public class Overload
    {
        public void Display()
        {
            int[] numbers = {10, 20, 30};
            DisplayOverload(40, numbers);
            Console.WriteLine(numbers[1]);
        }

        private void DisplayOverload(int a, params int[] parameterArray)
        {
            parameterArray[1] = 1000;
        }

    }
class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }
Output
1000

February 6, 2016

invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Reason: There are multiple scenario in which this error come.


if we try to change the property of asp.net control through the Javascript after page load then above issue comes.

This error might be coming from one of the user control present on the page
(Search or header)

Or

forgot to add an ID to a dynamically created control.

Or
check design contain two nested <form></form> tag

Or
other......

Solution:

Remove two nested <form></form> tag

OR
<pages validateRequest="false" enableEventValidation="false" />
and do Toolscriptmanager partial rendering is enabled

OR
IsPostBack in page load

OR
Use update panel which attribute is changing due to javascript

OR
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(buton1);

OR
Other...........

February 1, 2016

Base Class In asp.net

content copied .....

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. The Derived class re-use the code of base class based on accessibility level of those member.


Example Of Base Class :

public class Clsbase : System.Web.UI.Page
{  
    protected override void OnLoad(EventArgs e)
    {       
        Response.Write("From base class");
        base.OnLoad(e);
    }  
}



Example Of Derived Class :

public partial class ClsDerived : Clsbase

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("From Derived Class");    
    }
}

January 29, 2016

Layered architecture

  • Help reduce complexity and improve code reusability
  • It is often thought that this automatically creates a decoupled application. However, just creating layers doesn’t make your code loosely coupled.
  • Avoid Too Many Parameters 
  • Declare a class instead of too many parameters.
  • Creating a class that puts all these parameters together. This is generally a better design and valuable abstraction.
  • Avoid Complex Expressions
  • Minimize the Number of Returns
  • Use Parameterize queries instead of inline query

January 27, 2016

Entity Framework

The NuGet Gallery is the central package repository used by all package authors and consumers.



module is a set of functions, types, classes, ... put together in a common namespace.
library is a set of modules which makes sense to be together and that can be used in a program or another library.
package is a unit of distribution that can contain a library or an executable or both. It's a way to share your code with the community.
Entity Framework is ORM (Object relational mapper)

Entity Framework overview


Entity Framework Architecture

  • Extension of EF is .edmx
  • EF is directly talk with database. DAL is not required .
  • EF use ObjectContext =>DbContext interfacing with database
  • EF use EDM concept that describe the structure of data

https://msdn.microsoft.com/en-us/library/ee382825(v=vs.110).aspx


  • Entity type is class. it generate from table structure.
  • Entity type contain property and method where property is column of table and method is operation (Select/Insert/Update/Delete) done on that table
  • EF can do the operation on table with the help of LINQ or  store procedure
  • Complex object is created via Model browser if we have to call store procedure
  • Model browser - show the edmx file Model browser tab

EDM contain
  • CSDL- conceptual schema definition language
  • SSDL- storage schema definition language
  • Table Mapping - conceptual mapping and storage mapping
  • Schema contain multiple entity containers.
  • Entity container is namespace and contain entity type
  • EntityType (NavigationProperty,Scalar Property(facet),EntityKey).
  • Property contain facet (other information related to that column like Not NULL, Max length)
  • Validate - check CSDL or SSDL are synch or not
  • Complex Property
  • association - create relation between entity types

The relationship between an entity type and an entity set is analogous to the relationship between a row and a table in a relational database: Like a row, an entity type describes data structure, and, like a table, an entity set contains instances of a given structure.

Entity Framework Architecture

Setup Entity Framework Environment:


Entity Framework5


Entity Framework6




Install EF via Nuget:

Entity Framework install

Create Entity Data Model:




Entity Framework 5.0 Tutorial

Context & Entity Classes:

Entity Framework 5.0 Tutorial

Model Browser
Entity Framework 5.0 Tutorial

DBContext:

Entity Framework 5.0 Tutorial


Types of Entity in Entity Framework:

  • POCO Entity (Plain Old CLR Object):
  • Dynamic Proxy (POCO Proxy):



Entity Framework dbcontext


Entity Relationships:


Entity relationships in entity framework




entity relationships in entity framework





Entity Lifecycle:


entity states in Entity



Choose Entity Framework modling


can execute native SQL queries for a relational database

using (var ctx = new SchoolDBEntities())
{
    var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();
}    

Maintain change track


Connected scenario

Entity Framework tutorial 4.3 dbcontext




using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Perform create operation
    context.Students.Add(new Student() { StudentName = "New Student" });

    //Perform Update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Perform delete operation
    context.Students.Remove(studentList.ElementAt<Student>(0));

    //Execute Inser, Update & Delete queries in the database
    context.SaveChanges();
} 

Disconnected scenario






using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Add student in list
    studentList.Add(new Student() { StudentName = "New Student" });

    //Perform update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Delete student from list
    if (studentList.Count > 0)
        studentList.Remove(studentList.ElementAt<Student>(0));

    //SaveChanges will only do update operation not add and delete
    context.SaveChanges();
}

There are two ways to go with code first approach:
  1. Data annotation
  2. Fluent API

Code First Approach using Data Annotation

Create one .cs file and give name person.cs and paste the below code into it. As this his data annotation approaches, don’t forget to add System.ComponentModel.DataAnnotation namespace.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

    public class Address
    {
        [Key]
        public int personAdressId { get; set; }
        public string address { get; set; }

        [MaxLength(6)]
        public string pin { get; set; }

        [ForeignKey("Person")]
        public int PersonId { get; set; }

        //Navigation property
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext() : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}
we will specify connection string in web.config file in application. Here is code for mine.
<connectionStrings>
    <add name="DBConnectionString" 
        connectionString="Data Source=SOURAV-PC;Initial Catalog=personDB;Integrated Security=true" 
        providerName="System.Data.SqlClient"/>
  </connectionStrings>



We will implement the same model to create database using fluent API. Have a look at the below modified code of person.cs file.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        public int Id{get;set;}
        public string name { get; set; }
        public string surname { get; set; }
    }

    public class Address
    {
        public int personAdressId { get; set; }
        public string address { get; set; }
        public string pin { get; set; }
        public int PersonId { get; set; }
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Person table
            modelBuilder.Entity<Person>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
            //name fleld is required

            modelBuilder.Entity<Person>().Property(p => p.name).IsRequired();
            //surname is required
            modelBuilder.Entity<Person>().Property(p => p.surname).IsRequired();

            //set primary key to Address table
            modelBuilder.Entity<Address>().HasKey(m => m.personAdressId);

            //set max length property to 6 
            modelBuilder.Entity<Address>().Property(m => m.pin).HasMaxLength(6);

            //Set foreign key property
            modelBuilder.Entity<Address>().HasRequired(t => t.Person)
                .WithMany().HasForeignKey(t => t.PersonId);
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

September 17, 2015

Software categories

Computer software
  1. Application Software
  2. System software
  3. computer programming tool
  4. Mobile software & Apps

Application software

https://en.wikipedia.org/wiki/List_of_software_categories

https://en.wikipedia.org/wiki/Enterprise_software






Supply chain management (SCM) is the management of the flow of goods and services.It includes the movement and storage of raw materials, work-in-process inventory, and finished goods from point of origin to point of consumption


Enterprise resource planning (ERP) is business management software—typically a suite of integrated applications—that a company can use to collect, store, manage and interpret data from many business activities, including:



Enterprise asset management (EAM) is the optimal lifecycle management of the physical assets of an organization

Customer relationship management (CRM) is an approach to managing a company’s interaction with current and future customers. It often involves using technology to organize, automate, and synchronize salesmarketingcustomer service, and technical support.

content management system (CMS) is a computer application that allows publishingediting and modifying content, organizing, deleting as well as maintenance from a central interface. Such systems of content management provide procedures to manage workflow in a collaborative environment.
DotNetNuke
Umbraco

Business process management (BPM) is a field in operations management that focuses on improving corporate performance by managing and optimizing a company's business processes

Enterprise resource planning (ERP)
SAP(ERP)-it is ERP system.
supplier relation management(SRM)-procurement & logistics
cloud,
SMS,payment gateway,
e-commerce,
audit of software/
BI reports-Database analysis /power BI /spotfire/ tableau/ qlikview
highcharts

mobile apps

August 16, 2015

App_Code folder does not work with Web Application Projects.

If your application is a Web Application project rather than a Web Site project, the code files should not be in the App_Code folder (stupid design).

Solution:
1)Build Action of class.cs to be changed from "Content" to "Compile".

2)Create a new folder or something and put class files in there.